hexsha
stringlengths
40
40
size
int64
4
996k
ext
stringclasses
8 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
245
max_stars_repo_name
stringlengths
6
130
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
245
max_issues_repo_name
stringlengths
6
130
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
245
max_forks_repo_name
stringlengths
6
130
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
4
996k
avg_line_length
float64
1.33
58.2k
max_line_length
int64
2
323k
alphanum_fraction
float64
0
0.97
content_no_comment
stringlengths
0
946k
is_comment_constant_removed
bool
2 classes
is_sharp_comment_removed
bool
1 class
f725901ae4990c796dfc0c6fd9dcacb4bed91c78
3,385
py
Python
examples/basic_operations/update_ad_group.py
JakobSteixner/google-ads-python
df2b802cc7e78295a4ece21cc7ef3787cd35dab0
[ "Apache-2.0" ]
null
null
null
examples/basic_operations/update_ad_group.py
JakobSteixner/google-ads-python
df2b802cc7e78295a4ece21cc7ef3787cd35dab0
[ "Apache-2.0" ]
null
null
null
examples/basic_operations/update_ad_group.py
JakobSteixner/google-ads-python
df2b802cc7e78295a4ece21cc7ef3787cd35dab0
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This example updates an ad group. To get ad groups, run get_ad_groups.py. """ import argparse import sys from google.ads.googleads.client import GoogleAdsClient from google.ads.googleads.errors import GoogleAdsException from google.api_core import protobuf_helpers # [START update_ad_group] def main(client, customer_id, ad_group_id, cpc_bid_micro_amount): ad_group_service = client.get_service("AdGroupService") # Create ad group operation. ad_group_operation = client.get_type("AdGroupOperation") ad_group = ad_group_operation.update ad_group.resource_name = ad_group_service.ad_group_path( customer_id, ad_group_id ) ad_group.status = client.enums.AdGroupStatusEnum.PAUSED ad_group.cpc_bid_micros = cpc_bid_micro_amount client.copy_from( ad_group_operation.update_mask, protobuf_helpers.field_mask(None, ad_group._pb), ) # Update the ad group. ad_group_response = ad_group_service.mutate_ad_groups( customer_id=customer_id, operations=[ad_group_operation] ) print(f"Updated ad group {ad_group_response.results[0].resource_name}.") # [END update_ad_group] if __name__ == "__main__": # GoogleAdsClient will read the google-ads.yaml configuration file in the # home directory if none is specified. googleads_client = GoogleAdsClient.load_from_storage(version="v10") parser = argparse.ArgumentParser( description=( "Updates an ad group for specified customer and campaign " "id with the given bid micro amount." ) ) # The following argument(s) should be provided to run the example. parser.add_argument( "-c", "--customer_id", type=str, required=True, help="The Google Ads customer ID.", ) parser.add_argument( "-a", "--ad_group_id", type=str, required=True, help="The ad group ID." ) parser.add_argument( "-b", "--cpc_bid_micro_amount", type=int, required=True, help="The cpc bid micro amount.", ) args = parser.parse_args() try: main( googleads_client, args.customer_id, args.ad_group_id, args.cpc_bid_micro_amount, ) except GoogleAdsException as ex: print( f'Request with ID "{ex.request_id}" failed with status ' f'"{ex.error.code().name}" and includes the following errors:' ) for error in ex.failure.errors: print(f'\tError with message "{error.message}".') if error.location: for field_path_element in error.location.field_path_elements: print(f"\t\tOn field: {field_path_element.field_name}") sys.exit(1)
32.548077
79
0.676809
import argparse import sys from google.ads.googleads.client import GoogleAdsClient from google.ads.googleads.errors import GoogleAdsException from google.api_core import protobuf_helpers def main(client, customer_id, ad_group_id, cpc_bid_micro_amount): ad_group_service = client.get_service("AdGroupService") ad_group_operation = client.get_type("AdGroupOperation") ad_group = ad_group_operation.update ad_group.resource_name = ad_group_service.ad_group_path( customer_id, ad_group_id ) ad_group.status = client.enums.AdGroupStatusEnum.PAUSED ad_group.cpc_bid_micros = cpc_bid_micro_amount client.copy_from( ad_group_operation.update_mask, protobuf_helpers.field_mask(None, ad_group._pb), ) ad_group_response = ad_group_service.mutate_ad_groups( customer_id=customer_id, operations=[ad_group_operation] ) print(f"Updated ad group {ad_group_response.results[0].resource_name}.") if __name__ == "__main__": googleads_client = GoogleAdsClient.load_from_storage(version="v10") parser = argparse.ArgumentParser( description=( "Updates an ad group for specified customer and campaign " "id with the given bid micro amount." ) ) parser.add_argument( "-c", "--customer_id", type=str, required=True, help="The Google Ads customer ID.", ) parser.add_argument( "-a", "--ad_group_id", type=str, required=True, help="The ad group ID." ) parser.add_argument( "-b", "--cpc_bid_micro_amount", type=int, required=True, help="The cpc bid micro amount.", ) args = parser.parse_args() try: main( googleads_client, args.customer_id, args.ad_group_id, args.cpc_bid_micro_amount, ) except GoogleAdsException as ex: print( f'Request with ID "{ex.request_id}" failed with status ' f'"{ex.error.code().name}" and includes the following errors:' ) for error in ex.failure.errors: print(f'\tError with message "{error.message}".') if error.location: for field_path_element in error.location.field_path_elements: print(f"\t\tOn field: {field_path_element.field_name}") sys.exit(1)
true
true
f72590d6e6483328b9562e5788fc07feb3ad4594
11,628
py
Python
tests/suite.py
dannielarriola/uai-coursebuilder
fbd440a8bfe1a928ac52985aea2949d5e91ad203
[ "Apache-2.0" ]
null
null
null
tests/suite.py
dannielarriola/uai-coursebuilder
fbd440a8bfe1a928ac52985aea2949d5e91ad203
[ "Apache-2.0" ]
27
2016-08-31T19:04:46.000Z
2016-09-29T00:22:32.000Z
tests/suite.py
dannielarriola/uai-coursebuilder
fbd440a8bfe1a928ac52985aea2949d5e91ad203
[ "Apache-2.0" ]
null
null
null
# Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Course Builder test suite. This script runs all functional and units test in the Course Builder project. Here is how to use the script: - if you don't have pip, install it using 'sudo apt-get install python-pip' - install WebTest using: 'sudo pip install WebTest' - make sure your PYTHONPATH contains: google_appengine, google_appengine/lib/jinja2-2.6, google_appengine/lib/webapp2-2.5.1 and the 'coursebuilder' directory itself - invoke this test suite from the command line: # Run test method baz in unittest.TestCase Bar found in tests/foo.py. python tests/suite.py --test_class_name tests.foo.Bar.baz - review the output to make sure there are no errors or warnings Good luck! """ __author__ = 'Sean Lip' import argparse import cStringIO import logging import os import shutil import sys import unittest import task_queue import webtest import appengine_config from tools.etl import etl from google.appengine.api.search import simple_search_stub from google.appengine.datastore import datastore_stub_util from google.appengine.ext import testbed _PARSER = argparse.ArgumentParser() _PARSER.add_argument( '--test_class_name', help='optional dotted module name of the test(s) to run', type=str) # Direct key access so we'll throw if os.environ is misconfigured. TEST_DATA_BASE = os.path.join( os.environ['COURSEBUILDER_RESOURCES'], 'test-data') def empty_environ(): os.environ['AUTH_DOMAIN'] = 'example.com' os.environ['SERVER_NAME'] = 'localhost' os.environ['HTTP_HOST'] = 'localhost' os.environ['SERVER_PORT'] = '8080' os.environ['USER_EMAIL'] = '' os.environ['USER_ID'] = '' os.environ['DEFAULT_VERSION_HOSTNAME'] = ( os.environ['HTTP_HOST'] + ':' + os.environ['SERVER_PORT']) def iterate_tests(test_suite_or_case): """Iterate through all of the test cases in 'test_suite_or_case'.""" try: suite = iter(test_suite_or_case) except TypeError: yield test_suite_or_case else: for test in suite: for subtest in iterate_tests(test): yield subtest class TestBase(unittest.TestCase): """Base class for all Course Builder tests.""" INTEGRATION_SERVER_BASE_URL = 'http://localhost:8081' ADMIN_SERVER_BASE_URL = 'http://localhost:8000' STOP_AFTER_FIRST_FAILURE = False HAS_PENDING_FAILURE = False # Log level for all tests in this test case. Override if you need to test # against different logging levels. Be very careful when setting this to # logging.DEBUG: downstream code is sometimes very chatty at logging.DEBUG, # and can generate enough logging data that tests run out of memory. LOG_LEVEL = logging.ERROR def setUp(self): if TestBase.STOP_AFTER_FIRST_FAILURE: assert not TestBase.HAS_PENDING_FAILURE super(TestBase, self).setUp() self._set_up_logging() # e.g. TEST_DATA_BASE/tests/functional/tests/MyTestCase. self.test_tempdir = os.path.join( TEST_DATA_BASE, self.__class__.__module__.replace('.', os.sep), self.__class__.__name__) self.reset_filesystem() self._originals = {} # Map of object -> {symbol_string: original_value} def _set_up_logging(self): self._log = cStringIO.StringIO() self._stream_handler = logging.StreamHandler(self._log) self._stream_handler.setFormatter( logging.Formatter(fmt='%(levelname)s: %(message)s')) self._logger = logging.getLogger() self._logger.addHandler(self._stream_handler) self._logger.setLevel(self.LOG_LEVEL) def tearDown(self): self._unswap_all() self.reset_filesystem(remove_only=True) self._tear_down_logging() super(TestBase, self).tearDown() def _tear_down_logging(self): self._logger.removeHandler(self._stream_handler) self._log.close() def get_log(self): self._log.flush() return self._log.getvalue() def assertLogContains(self, message): self.assertIn(message, self.get_log()) def reset_filesystem(self, remove_only=False): if os.path.exists(self.test_tempdir): shutil.rmtree(self.test_tempdir) if not remove_only: os.makedirs(self.test_tempdir) def run(self, result=None): if not result: result = self.defaultTestResult() super(TestBase, self).run(result) if not result.wasSuccessful(): TestBase.HAS_PENDING_FAILURE = True def shortDescription(self): """Additional information logged during unittest invocation.""" # Suppress default logging of docstrings. Instead log name/status only. return None def swap(self, source, symbol, new): # pylint: disable=invalid-name """Swaps out source.symbol for a new value. Allows swapping of members and methods: myobject.foo = 'original_foo' self.swap(myobject, 'foo', 'bar') self.assertEqual('bar', myobject.foo) myobject.baz() # -> 'original_baz' self.swap(myobject, 'baz', lambda: 'quux') self.assertEqual('quux', myobject.bar()) Swaps are automatically undone in tearDown(). Args: source: object. The source object to swap from. symbol: string. The name of the symbol to swap. new: object. The new value to swap in. """ if source not in self._originals: self._originals[source] = {} if not self._originals[source].get(symbol, None): self._originals[source][symbol] = getattr(source, symbol) setattr(source, symbol, new) def _unswap_all(self): for source, symbol_to_value in self._originals.iteritems(): for symbol, value in symbol_to_value.iteritems(): setattr(source, symbol, value) class FunctionalTestBase(TestBase): """Base class for functional tests.""" class AppEngineTestBase(FunctionalTestBase): """Base class for tests that require App Engine services.""" def getApp(self): """Returns the main application to be tested.""" raise Exception('Not implemented.') def setUp(self): super(AppEngineTestBase, self).setUp() empty_environ() # setup an app to be tested self.testapp = webtest.TestApp(self.getApp()) self.testbed = testbed.Testbed() self.testbed.activate() # configure datastore policy to emulate instantaneously and globally # consistent HRD; we also patch dev_appserver in main.py to run under # the same policy policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy( probability=1) # declare any relevant App Engine service stubs here self.testbed.init_user_stub() self.testbed.init_memcache_stub() self.testbed.init_datastore_v3_stub(consistency_policy=policy) self.testbed.init_taskqueue_stub(root_path=os.environ['SOURCE_DIR']) self.taskq = self.testbed.get_stub(testbed.TASKQUEUE_SERVICE_NAME) self.testbed.init_urlfetch_stub() self.testbed.init_files_stub() self.testbed.init_blobstore_stub() self.testbed.init_mail_stub() self.testbed.init_app_identity_stub() # TODO(emichael): Fix this when an official stub is created self.testbed._register_stub( 'search', simple_search_stub.SearchServiceStub()) self.task_dispatcher = task_queue.TaskQueueHandlerDispatcher( self.testapp, self.taskq) # Handle for testing sent mail. self.mail_stub = self.testbed.get_stub(testbed.MAIL_SERVICE_NAME) def tearDown(self): self.testbed.deactivate() super(AppEngineTestBase, self).tearDown() def get_mail_stub(self): return self.testbed.get_stub(testbed.MAIL_SERVICE_NAME) def create_test_suite(parsed_args): """Loads all requested test suites. By default, loads all unittest.TestCases found under the project root's tests/ directory. Args: parsed_args: argparse.Namespace. Processed command-line arguments. Returns: unittest.TestSuite. The test suite populated with all tests to run. """ loader = unittest.TestLoader() if not parsed_args.test_class_name: raise Exception('Expected --test_class_name to be specified.') return loader.loadTestsFromName(parsed_args.test_class_name) def fix_sys_path(): """Fix the sys.path to include GAE extra paths.""" import dev_appserver # pylint: disable=C6204 # dev_appserver.fix_sys_path() prepends GAE paths to sys.path and hides # our classes like 'tests' behind other modules that have 'tests'. # Here, unlike dev_appserver, we append the path instead of prepending it, # so that our classes come first. sys.path += dev_appserver.EXTRA_PATHS[:] # This is to work around an issue with the __import__ builtin. The # problem seems to be that if the sys.path list contains an item that # partially matches a package name to import, __import__ will get # confused, and report an error message (which removes the first path # element from the module it's complaining about, which does not help # efforts to diagnose the problem at all). # # The specific case where this causes an issue is between # $COURSEBUILDER_HOME/tests/internal and $COURSEBUILDER_HOME/internal # Since the former exists, __import__ will ignore the second, and so # things like .../internal/experimental/autoregister/autoregister # cannot be loaded. # # To address this issue, we ensure that COURSEBUILDER_HOME is on sys.path # before anything else, and do it before appengine_config's module # importation starts running. (And we have to do it here, because if we # try to do this within appengine_config, AppEngine will throw an error) if appengine_config.BUNDLE_ROOT in sys.path: sys.path.remove(appengine_config.BUNDLE_ROOT) sys.path.insert(0, appengine_config.BUNDLE_ROOT) def main(): """Starts in-process server and runs all test cases in this module.""" fix_sys_path() etl._set_env_vars_from_app_yaml() parsed_args = _PARSER.parse_args() test_suite = create_test_suite(parsed_args) result = unittest.TextTestRunner(verbosity=2).run(test_suite) if result.errors or result.failures: raise Exception( 'Test suite failed: %s errors, %s failures of ' ' %s tests run.' % ( len(result.errors), len(result.failures), result.testsRun)) import tests.functional.actions as actions count = len(actions.UNIQUE_URLS_FOUND.keys()) result.stream.writeln('INFO: Unique URLs found: %s' % count) result.stream.writeln('INFO: All %s tests PASSED!' % result.testsRun) if __name__ == '__main__': appengine_config.gcb_force_default_encoding('ascii') main()
36.566038
80
0.689456
__author__ = 'Sean Lip' import argparse import cStringIO import logging import os import shutil import sys import unittest import task_queue import webtest import appengine_config from tools.etl import etl from google.appengine.api.search import simple_search_stub from google.appengine.datastore import datastore_stub_util from google.appengine.ext import testbed _PARSER = argparse.ArgumentParser() _PARSER.add_argument( '--test_class_name', help='optional dotted module name of the test(s) to run', type=str) TEST_DATA_BASE = os.path.join( os.environ['COURSEBUILDER_RESOURCES'], 'test-data') def empty_environ(): os.environ['AUTH_DOMAIN'] = 'example.com' os.environ['SERVER_NAME'] = 'localhost' os.environ['HTTP_HOST'] = 'localhost' os.environ['SERVER_PORT'] = '8080' os.environ['USER_EMAIL'] = '' os.environ['USER_ID'] = '' os.environ['DEFAULT_VERSION_HOSTNAME'] = ( os.environ['HTTP_HOST'] + ':' + os.environ['SERVER_PORT']) def iterate_tests(test_suite_or_case): try: suite = iter(test_suite_or_case) except TypeError: yield test_suite_or_case else: for test in suite: for subtest in iterate_tests(test): yield subtest class TestBase(unittest.TestCase): INTEGRATION_SERVER_BASE_URL = 'http://localhost:8081' ADMIN_SERVER_BASE_URL = 'http://localhost:8000' STOP_AFTER_FIRST_FAILURE = False HAS_PENDING_FAILURE = False # Log level for all tests in this test case. Override if you need to test # against different logging levels. Be very careful when setting this to # logging.DEBUG: downstream code is sometimes very chatty at logging.DEBUG, # and can generate enough logging data that tests run out of memory. LOG_LEVEL = logging.ERROR def setUp(self): if TestBase.STOP_AFTER_FIRST_FAILURE: assert not TestBase.HAS_PENDING_FAILURE super(TestBase, self).setUp() self._set_up_logging() # e.g. TEST_DATA_BASE/tests/functional/tests/MyTestCase. self.test_tempdir = os.path.join( TEST_DATA_BASE, self.__class__.__module__.replace('.', os.sep), self.__class__.__name__) self.reset_filesystem() self._originals = {} # Map of object -> {symbol_string: original_value} def _set_up_logging(self): self._log = cStringIO.StringIO() self._stream_handler = logging.StreamHandler(self._log) self._stream_handler.setFormatter( logging.Formatter(fmt='%(levelname)s: %(message)s')) self._logger = logging.getLogger() self._logger.addHandler(self._stream_handler) self._logger.setLevel(self.LOG_LEVEL) def tearDown(self): self._unswap_all() self.reset_filesystem(remove_only=True) self._tear_down_logging() super(TestBase, self).tearDown() def _tear_down_logging(self): self._logger.removeHandler(self._stream_handler) self._log.close() def get_log(self): self._log.flush() return self._log.getvalue() def assertLogContains(self, message): self.assertIn(message, self.get_log()) def reset_filesystem(self, remove_only=False): if os.path.exists(self.test_tempdir): shutil.rmtree(self.test_tempdir) if not remove_only: os.makedirs(self.test_tempdir) def run(self, result=None): if not result: result = self.defaultTestResult() super(TestBase, self).run(result) if not result.wasSuccessful(): TestBase.HAS_PENDING_FAILURE = True def shortDescription(self): # Suppress default logging of docstrings. Instead log name/status only. return None def swap(self, source, symbol, new): # pylint: disable=invalid-name if source not in self._originals: self._originals[source] = {} if not self._originals[source].get(symbol, None): self._originals[source][symbol] = getattr(source, symbol) setattr(source, symbol, new) def _unswap_all(self): for source, symbol_to_value in self._originals.iteritems(): for symbol, value in symbol_to_value.iteritems(): setattr(source, symbol, value) class FunctionalTestBase(TestBase): class AppEngineTestBase(FunctionalTestBase): def getApp(self): raise Exception('Not implemented.') def setUp(self): super(AppEngineTestBase, self).setUp() empty_environ() # setup an app to be tested self.testapp = webtest.TestApp(self.getApp()) self.testbed = testbed.Testbed() self.testbed.activate() # configure datastore policy to emulate instantaneously and globally # consistent HRD; we also patch dev_appserver in main.py to run under # the same policy policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy( probability=1) # declare any relevant App Engine service stubs here self.testbed.init_user_stub() self.testbed.init_memcache_stub() self.testbed.init_datastore_v3_stub(consistency_policy=policy) self.testbed.init_taskqueue_stub(root_path=os.environ['SOURCE_DIR']) self.taskq = self.testbed.get_stub(testbed.TASKQUEUE_SERVICE_NAME) self.testbed.init_urlfetch_stub() self.testbed.init_files_stub() self.testbed.init_blobstore_stub() self.testbed.init_mail_stub() self.testbed.init_app_identity_stub() # TODO(emichael): Fix this when an official stub is created self.testbed._register_stub( 'search', simple_search_stub.SearchServiceStub()) self.task_dispatcher = task_queue.TaskQueueHandlerDispatcher( self.testapp, self.taskq) # Handle for testing sent mail. self.mail_stub = self.testbed.get_stub(testbed.MAIL_SERVICE_NAME) def tearDown(self): self.testbed.deactivate() super(AppEngineTestBase, self).tearDown() def get_mail_stub(self): return self.testbed.get_stub(testbed.MAIL_SERVICE_NAME) def create_test_suite(parsed_args): loader = unittest.TestLoader() if not parsed_args.test_class_name: raise Exception('Expected --test_class_name to be specified.') return loader.loadTestsFromName(parsed_args.test_class_name) def fix_sys_path(): import dev_appserver # pylint: disable=C6204 # dev_appserver.fix_sys_path() prepends GAE paths to sys.path and hides # our classes like 'tests' behind other modules that have 'tests'. # Here, unlike dev_appserver, we append the path instead of prepending it, # so that our classes come first. sys.path += dev_appserver.EXTRA_PATHS[:] # This is to work around an issue with the __import__ builtin. The # problem seems to be that if the sys.path list contains an item that # partially matches a package name to import, __import__ will get # confused, and report an error message (which removes the first path # element from the module it's complaining about, which does not help # importation starts running. (And we have to do it here, because if we # try to do this within appengine_config, AppEngine will throw an error) if appengine_config.BUNDLE_ROOT in sys.path: sys.path.remove(appengine_config.BUNDLE_ROOT) sys.path.insert(0, appengine_config.BUNDLE_ROOT) def main(): fix_sys_path() etl._set_env_vars_from_app_yaml() parsed_args = _PARSER.parse_args() test_suite = create_test_suite(parsed_args) result = unittest.TextTestRunner(verbosity=2).run(test_suite) if result.errors or result.failures: raise Exception( 'Test suite failed: %s errors, %s failures of ' ' %s tests run.' % ( len(result.errors), len(result.failures), result.testsRun)) import tests.functional.actions as actions count = len(actions.UNIQUE_URLS_FOUND.keys()) result.stream.writeln('INFO: Unique URLs found: %s' % count) result.stream.writeln('INFO: All %s tests PASSED!' % result.testsRun) if __name__ == '__main__': appengine_config.gcb_force_default_encoding('ascii') main()
true
true
f7259138e078865f2f6c44a93538b382ee2f400a
786
py
Python
pyleecan/Methods/Output/OutElec/get_Nr.py
tobsen2code/pyleecan
5b1ded9e389e0c79ed7b7c878b6e939f2d9962e9
[ "Apache-2.0" ]
5
2020-03-05T15:22:39.000Z
2022-03-02T15:26:08.000Z
pyleecan/Methods/Output/OutElec/get_Nr.py
Eomys/Pyleecan
4d7f0cbabf0311006963e7a2f435db2ecd901118
[ "Apache-2.0" ]
8
2020-07-09T07:43:01.000Z
2022-03-08T12:52:06.000Z
pyleecan/Methods/Output/OutElec/get_Nr.py
Eomys/Pyleecan
4d7f0cbabf0311006963e7a2f435db2ecd901118
[ "Apache-2.0" ]
4
2019-12-23T12:38:01.000Z
2022-01-07T10:47:48.000Z
from numpy import ones def get_Nr(self, Time=None): """Create speed in function of time vector Nr Parameters ---------- self : OutElec An OutElec object Time : Data a time axis (SciDataTool Data object) Returns ------- Nr: ndarray speed in function of time """ if Time is None: if self.axes_dict is not None and "time" in self.axes_dict: Time = self.axes_dict["time"] else: raise Exception('You must define "time" property before calling get_Nr') if self.OP.get_N0() is None: raise Exception('You must define "N0" before calling get_Nr') # Same speed for every timestep Nr = self.OP.get_N0() * ones(Time.get_length(is_smallestperiod=True)) return Nr
23.818182
84
0.611959
from numpy import ones def get_Nr(self, Time=None): if Time is None: if self.axes_dict is not None and "time" in self.axes_dict: Time = self.axes_dict["time"] else: raise Exception('You must define "time" property before calling get_Nr') if self.OP.get_N0() is None: raise Exception('You must define "N0" before calling get_Nr') Nr = self.OP.get_N0() * ones(Time.get_length(is_smallestperiod=True)) return Nr
true
true
f725918c5d899450e00f379c56c435cdc1df4d6a
8,936
py
Python
python/ccxt/async/base/exchange.py
bilibilihuangyifan/ccxt
e3e058067808014c7110813d626d8a076ce96edb
[ "MIT" ]
73
2018-05-15T00:53:50.000Z
2022-03-07T14:45:11.000Z
python/ccxt/async/base/exchange.py
bilibilihuangyifan/ccxt
e3e058067808014c7110813d626d8a076ce96edb
[ "MIT" ]
20
2018-05-15T08:46:45.000Z
2018-06-19T08:49:27.000Z
python/ccxt/async/base/exchange.py
bilibilihuangyifan/ccxt
e3e058067808014c7110813d626d8a076ce96edb
[ "MIT" ]
11
2018-05-15T00:09:30.000Z
2022-03-07T14:45:27.000Z
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- __version__ = '1.13.142' # ----------------------------------------------------------------------------- import asyncio import concurrent import socket import time import math import random import certifi import aiohttp import ssl import yarl # ----------------------------------------------------------------------------- from ccxt.async.base.throttle import throttle # ----------------------------------------------------------------------------- from ccxt.base.errors import ExchangeError from ccxt.base.errors import ExchangeNotAvailable from ccxt.base.errors import RequestTimeout from ccxt.base.errors import NotSupported # ----------------------------------------------------------------------------- from ccxt.base.exchange import Exchange as BaseExchange # ----------------------------------------------------------------------------- __all__ = [ 'BaseExchange', 'Exchange', ] # ----------------------------------------------------------------------------- class Exchange(BaseExchange): def __init__(self, config={}): if 'asyncio_loop' in config: self.asyncio_loop = config['asyncio_loop'] self.asyncio_loop = self.asyncio_loop or asyncio.get_event_loop() self.own_session = 'session' not in config if self.own_session: # Create out SSL context object with our CA cert file context = ssl.create_default_context(cafile=certifi.where()) # Pass this SSL context to aiohttp and create a TCPConnector connector = aiohttp.TCPConnector(ssl_context=context, loop=self.asyncio_loop) self.session = aiohttp.ClientSession(loop=self.asyncio_loop, connector=connector) super(Exchange, self).__init__(config) self.init_rest_rate_limiter() def init_rest_rate_limiter(self): self.throttle = throttle(self.extend({ 'loop': self.asyncio_loop, }, self.tokenBucket)) def __del__(self): if self.session is not None: self.logger.warning(self.id + ' requires to release all resources with an explicit call to the .close() coroutine.') async def close(self): if self.session is not None: if self.own_session: await self.session.close() self.session = None async def wait_for_token(self): while self.rateLimitTokens <= 1: # if self.verbose: # print('Waiting for tokens: Exchange: {0}'.format(self.id)) self.add_new_tokens() seconds_delays = [0.001, 0.005, 0.022, 0.106, 0.5] delay = random.choice(seconds_delays) await asyncio.sleep(delay) self.rateLimitTokens -= 1 def add_new_tokens(self): # if self.verbose: # print('Adding new tokens: Exchange: {0}'.format(self.id)) now = time.monotonic() time_since_update = now - self.rateLimitUpdateTime new_tokens = math.floor((0.8 * 1000.0 * time_since_update) / self.rateLimit) if new_tokens > 1: self.rateLimitTokens = min(self.rateLimitTokens + new_tokens, self.rateLimitMaxTokens) self.rateLimitUpdateTime = now async def fetch2(self, path, api='public', method='GET', params={}, headers=None, body=None): """A better wrapper over request for deferred signing""" if self.enableRateLimit: await self.throttle() self.lastRestRequestTimestamp = self.milliseconds() request = self.sign(path, api, method, params, headers, body) return await self.fetch(request['url'], request['method'], request['headers'], request['body']) async def fetch(self, url, method='GET', headers=None, body=None): """Perform a HTTP request and return decoded JSON data""" headers = self.prepare_request_headers(headers) url = self.proxy + url if self.verbose: print("\nRequest:", method, url, headers, body) self.logger.debug("%s %s, Request: %s %s", method, url, headers, body) encoded_body = body.encode() if body else None session_method = getattr(self.session, method.lower()) http_status_code = None try: async with session_method(yarl.URL(url, encoded=True), data=encoded_body, headers=headers, timeout=(self.timeout / 1000), proxy=self.aiohttp_proxy) as response: http_status_code = response.status text = await response.text() self.last_http_response = text self.last_response_headers = response.headers self.handle_errors(http_status_code, text, url, method, self.last_response_headers, text) self.handle_rest_errors(None, http_status_code, text, url, method) if self.verbose: print("\nResponse:", method, url, str(http_status_code), str(response.headers), self.last_http_response) self.logger.debug("%s %s, Response: %s %s %s", method, url, response.status, response.headers, self.last_http_response) except socket.gaierror as e: self.raise_error(ExchangeNotAvailable, url, method, e, None) except concurrent.futures._base.TimeoutError as e: self.raise_error(RequestTimeout, method, url, e, None) except aiohttp.client_exceptions.ClientConnectionError as e: self.raise_error(ExchangeNotAvailable, url, method, e, None) except aiohttp.client_exceptions.ClientError as e: self.raise_error(ExchangeError, url, method, e, None) self.handle_errors(http_status_code, text, url, method, self.last_response_headers, text) return self.handle_rest_response(text, url, method, headers, body) async def load_markets(self, reload=False): if not reload: if self.markets: if not self.markets_by_id: return self.set_markets(self.markets) return self.markets markets = await self.fetch_markets() currencies = None if self.has['fetchCurrencies']: currencies = await self.fetch_currencies() return self.set_markets(markets, currencies) async def load_fees(self): await self.load_markets() self.populate_fees() if not (self.has['fetchTradingFees'] or self.has['fetchFundingFees']): return self.fees fetched_fees = self.fetch_fees() if fetched_fees['funding']: self.fees['funding']['fee_loaded'] = True if fetched_fees['trading']: self.fees['trading']['fee_loaded'] = True self.fees = self.deep_extend(self.fees, fetched_fees) return self.fees async def fetch_markets(self): return self.markets async def fetch_order_status(self, id, market=None): order = await self.fetch_order(id) return order['status'] async def fetch_partial_balance(self, part, params={}): balance = await self.fetch_balance(params) return balance[part] async def fetch_l2_order_book(self, symbol, limit=None, params={}): orderbook = await self.fetch_order_book(symbol, limit, params) return self.extend(orderbook, { 'bids': self.sort_by(self.aggregate(orderbook['bids']), 0, True), 'asks': self.sort_by(self.aggregate(orderbook['asks']), 0), }) async def perform_order_book_request(self, market, limit=None, params={}): raise NotSupported(self.id + ' performOrderBookRequest not supported yet') async def fetch_order_book(self, symbol, limit=None, params={}): await self.load_markets() market = self.market(symbol) orderbook = await self.perform_order_book_request(market, limit, params) return self.parse_order_book(orderbook, market, limit, params) async def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}): if not self.has['fetchTrades']: self.raise_error(NotSupported, details='fetch_ohlcv() not implemented yet') await self.load_markets() trades = await self.fetch_trades(symbol, since, limit, params) return self.build_ohlcv(trades, timeframe, since, limit) async def fetch_full_tickers(self, symbols=None, params={}): tickers = await self.fetch_tickers(symbols, params) return tickers async def edit_order(self, id, symbol, *args): if not self.enableRateLimit: self.raise_error(ExchangeError, details='updateOrder() requires enableRateLimit = true') await self.cancel_order(id, symbol) return await self.create_order(symbol, *args)
40.618182
135
0.602171
__version__ = '1.13.142' import asyncio import concurrent import socket import time import math import random import certifi import aiohttp import ssl import yarl from ccxt.async.base.throttle import throttle from ccxt.base.errors import ExchangeError from ccxt.base.errors import ExchangeNotAvailable from ccxt.base.errors import RequestTimeout from ccxt.base.errors import NotSupported from ccxt.base.exchange import Exchange as BaseExchange __all__ = [ 'BaseExchange', 'Exchange', ] class Exchange(BaseExchange): def __init__(self, config={}): if 'asyncio_loop' in config: self.asyncio_loop = config['asyncio_loop'] self.asyncio_loop = self.asyncio_loop or asyncio.get_event_loop() self.own_session = 'session' not in config if self.own_session: context = ssl.create_default_context(cafile=certifi.where()) connector = aiohttp.TCPConnector(ssl_context=context, loop=self.asyncio_loop) self.session = aiohttp.ClientSession(loop=self.asyncio_loop, connector=connector) super(Exchange, self).__init__(config) self.init_rest_rate_limiter() def init_rest_rate_limiter(self): self.throttle = throttle(self.extend({ 'loop': self.asyncio_loop, }, self.tokenBucket)) def __del__(self): if self.session is not None: self.logger.warning(self.id + ' requires to release all resources with an explicit call to the .close() coroutine.') async def close(self): if self.session is not None: if self.own_session: await self.session.close() self.session = None async def wait_for_token(self): while self.rateLimitTokens <= 1: self.add_new_tokens() seconds_delays = [0.001, 0.005, 0.022, 0.106, 0.5] delay = random.choice(seconds_delays) await asyncio.sleep(delay) self.rateLimitTokens -= 1 def add_new_tokens(self): now = time.monotonic() time_since_update = now - self.rateLimitUpdateTime new_tokens = math.floor((0.8 * 1000.0 * time_since_update) / self.rateLimit) if new_tokens > 1: self.rateLimitTokens = min(self.rateLimitTokens + new_tokens, self.rateLimitMaxTokens) self.rateLimitUpdateTime = now async def fetch2(self, path, api='public', method='GET', params={}, headers=None, body=None): """A better wrapper over request for deferred signing""" if self.enableRateLimit: await self.throttle() self.lastRestRequestTimestamp = self.milliseconds() request = self.sign(path, api, method, params, headers, body) return await self.fetch(request['url'], request['method'], request['headers'], request['body']) async def fetch(self, url, method='GET', headers=None, body=None): """Perform a HTTP request and return decoded JSON data""" headers = self.prepare_request_headers(headers) url = self.proxy + url if self.verbose: print("\nRequest:", method, url, headers, body) self.logger.debug("%s %s, Request: %s %s", method, url, headers, body) encoded_body = body.encode() if body else None session_method = getattr(self.session, method.lower()) http_status_code = None try: async with session_method(yarl.URL(url, encoded=True), data=encoded_body, headers=headers, timeout=(self.timeout / 1000), proxy=self.aiohttp_proxy) as response: http_status_code = response.status text = await response.text() self.last_http_response = text self.last_response_headers = response.headers self.handle_errors(http_status_code, text, url, method, self.last_response_headers, text) self.handle_rest_errors(None, http_status_code, text, url, method) if self.verbose: print("\nResponse:", method, url, str(http_status_code), str(response.headers), self.last_http_response) self.logger.debug("%s %s, Response: %s %s %s", method, url, response.status, response.headers, self.last_http_response) except socket.gaierror as e: self.raise_error(ExchangeNotAvailable, url, method, e, None) except concurrent.futures._base.TimeoutError as e: self.raise_error(RequestTimeout, method, url, e, None) except aiohttp.client_exceptions.ClientConnectionError as e: self.raise_error(ExchangeNotAvailable, url, method, e, None) except aiohttp.client_exceptions.ClientError as e: self.raise_error(ExchangeError, url, method, e, None) self.handle_errors(http_status_code, text, url, method, self.last_response_headers, text) return self.handle_rest_response(text, url, method, headers, body) async def load_markets(self, reload=False): if not reload: if self.markets: if not self.markets_by_id: return self.set_markets(self.markets) return self.markets markets = await self.fetch_markets() currencies = None if self.has['fetchCurrencies']: currencies = await self.fetch_currencies() return self.set_markets(markets, currencies) async def load_fees(self): await self.load_markets() self.populate_fees() if not (self.has['fetchTradingFees'] or self.has['fetchFundingFees']): return self.fees fetched_fees = self.fetch_fees() if fetched_fees['funding']: self.fees['funding']['fee_loaded'] = True if fetched_fees['trading']: self.fees['trading']['fee_loaded'] = True self.fees = self.deep_extend(self.fees, fetched_fees) return self.fees async def fetch_markets(self): return self.markets async def fetch_order_status(self, id, market=None): order = await self.fetch_order(id) return order['status'] async def fetch_partial_balance(self, part, params={}): balance = await self.fetch_balance(params) return balance[part] async def fetch_l2_order_book(self, symbol, limit=None, params={}): orderbook = await self.fetch_order_book(symbol, limit, params) return self.extend(orderbook, { 'bids': self.sort_by(self.aggregate(orderbook['bids']), 0, True), 'asks': self.sort_by(self.aggregate(orderbook['asks']), 0), }) async def perform_order_book_request(self, market, limit=None, params={}): raise NotSupported(self.id + ' performOrderBookRequest not supported yet') async def fetch_order_book(self, symbol, limit=None, params={}): await self.load_markets() market = self.market(symbol) orderbook = await self.perform_order_book_request(market, limit, params) return self.parse_order_book(orderbook, market, limit, params) async def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}): if not self.has['fetchTrades']: self.raise_error(NotSupported, details='fetch_ohlcv() not implemented yet') await self.load_markets() trades = await self.fetch_trades(symbol, since, limit, params) return self.build_ohlcv(trades, timeframe, since, limit) async def fetch_full_tickers(self, symbols=None, params={}): tickers = await self.fetch_tickers(symbols, params) return tickers async def edit_order(self, id, symbol, *args): if not self.enableRateLimit: self.raise_error(ExchangeError, details='updateOrder() requires enableRateLimit = true') await self.cancel_order(id, symbol) return await self.create_order(symbol, *args)
false
true
f72592c33a736521f66954a48dff265345cf299f
1,296
py
Python
Homeautomation/Alarmpi/get_trypico2wave.py
EtechProjects/Curtains-and-Blinds-Tests
7bfacf50ee7a4b951337e60f0fa288fbe59762e2
[ "Apache-2.0" ]
null
null
null
Homeautomation/Alarmpi/get_trypico2wave.py
EtechProjects/Curtains-and-Blinds-Tests
7bfacf50ee7a4b951337e60f0fa288fbe59762e2
[ "Apache-2.0" ]
null
null
null
Homeautomation/Alarmpi/get_trypico2wave.py
EtechProjects/Curtains-and-Blinds-Tests
7bfacf50ee7a4b951337e60f0fa288fbe59762e2
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- import os.path import subprocess import uuid from aptts import alarmpi_tts class trypico2wave(alarmpi_tts): def play(self, content, ramdrive='/mnt/ram/'): if self.debug: print "Trying pico2wave." rval = True p2w = self.sconfig['head'] lang =self.sconfig['lang'] if not os.path.isfile(p2w): # The executable does not exist if self.debug: print 'File ' + p2w + ' does not exist.' return False try: tmfn = ramdrive + str(uuid.uuid4()) + self.sconfig['tail'] cmd = p2w + ' -l ' + lang + ' -w ' + tmfn + ' "' + content + '"' if self.debug: print cmd print subprocess.call(cmd, shell=True) cmd = self.sconfig['player'] + ' ' + tmfn if self.debug: print cmd print subprocess.call(cmd, shell=True) cmd = 'rm -f ' + tmfn if self.debug: print cmd print subprocess.call(cmd, shell=True) except subprocess.CalledProcessError: rval = False # Cleanup any ogg files created in this directory. if self.debug: print 'cleaning up now' rmcmd = 'rm -f ' + ramdrive + '*' + self.sconfig['tail'] if self.debug: print rmcmd print subprocess.call (rmcmd, shell=True) return rval
28.173913
70
0.595679
import os.path import subprocess import uuid from aptts import alarmpi_tts class trypico2wave(alarmpi_tts): def play(self, content, ramdrive='/mnt/ram/'): if self.debug: print "Trying pico2wave." rval = True p2w = self.sconfig['head'] lang =self.sconfig['lang'] if not os.path.isfile(p2w): if self.debug: print 'File ' + p2w + ' does not exist.' return False try: tmfn = ramdrive + str(uuid.uuid4()) + self.sconfig['tail'] cmd = p2w + ' -l ' + lang + ' -w ' + tmfn + ' "' + content + '"' if self.debug: print cmd print subprocess.call(cmd, shell=True) cmd = self.sconfig['player'] + ' ' + tmfn if self.debug: print cmd print subprocess.call(cmd, shell=True) cmd = 'rm -f ' + tmfn if self.debug: print cmd print subprocess.call(cmd, shell=True) except subprocess.CalledProcessError: rval = False if self.debug: print 'cleaning up now' rmcmd = 'rm -f ' + ramdrive + '*' + self.sconfig['tail'] if self.debug: print rmcmd print subprocess.call (rmcmd, shell=True) return rval
false
true
f72595be695d8aadf33d417466be973d11af82cd
21,863
py
Python
qkeras/qoctave.py
thaarres/qkeras
a04bfe65a144ef6dd0ca0880866ef6109c3638fc
[ "Apache-2.0" ]
1
2019-12-08T16:22:21.000Z
2019-12-08T16:22:21.000Z
qkeras/qoctave.py
Athena-INT/qkeras
4cd7bb948bca11507d124cdddc3afda4956a72db
[ "Apache-2.0" ]
null
null
null
qkeras/qoctave.py
Athena-INT/qkeras
4cd7bb948bca11507d124cdddc3afda4956a72db
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Octave Convolution.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import re from keras.layers import Activation from keras.layers import Add from keras.layers import AveragePooling2D from keras.layers import Conv2D from keras.layers import SeparableConv2D from keras.layers import UpSampling2D from .qlayers import QActivation from .qlayers import QAveragePooling2D from .qlayers import QConv2D from .qlayers import QSeparableConv2D def GetActivationSuffix(activation): """Returns suffix for layer name to facilitate debugging.""" if not activation: return "linear" if "po2" in activation: return "q2" elif "quantized_relu" in activation: suffix = "qr" elif "quantized_tanh" in activation: suffix = "qt" else: suffix = "qb" numbers = re.findall(r"[0-9]+", activation) numbers = [n + "_" if len(n) > 1 else n for n in numbers] return suffix + "".join(numbers) def QOctaveConv2D( filters, kernel_size, alpha, strides=(1, 1), padding="valid", kernel_initializer="he_normal", bias_initializer="zeros", # NOTE: kernel_regularizer not used with separable convolution kernel_regularizer=None, bias_regularizer=None, kernel_constraint=None, bias_constraint=None, use_separable=True, name="", **kwargs): """Implements quantized QOctaveConv2D.""" def _QOctaveConv2DInternal(x): """Computes QOctaveConv2D on a tensor.""" x_h, x_l = x bias_quantizer = kwargs.get("bias_quantizer", None) kernel_quantizer = kwargs.get("kernel_quantizer", None) depthwise_quantizer = kwargs.get("depthwise_quantizer", None) pointwise_quantizer = kwargs.get("pointwise_quantizer", None) acc_quantizer = kwargs.get("acc_quantizer", None) pooling_quantizer = kwargs.get("pooling_quantizer", None) depthwise_activation = kwargs.get("depthwise_activation", None) activation = kwargs.get("activation", None) bias_range = kwargs.get("bias_range", 1.0) kernel_range = kwargs.get("kernel_range", 1.0) depthwise_range = kwargs.get("depthwise_range", 1.0) pointwise_range = kwargs.get("pointwise_range", 1.0) if activation: act_suffix = "_" + GetActivationSuffix(activation) acc_suffix = "_" + GetActivationSuffix(acc_quantizer) if alpha == -1.0: if use_separable: x_h = QSeparableConv2D( filters, kernel_size, strides=strides, padding=padding, depthwise_regularizer=kernel_regularizer, depthwise_constraint=kernel_constraint, depthwise_initializer=kernel_initializer, pointwise_regularizer=kernel_regularizer, pointwise_constraint=kernel_constraint, pointwise_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, depthwise_quantizer=depthwise_quantizer, pointwise_quantizer=pointwise_quantizer, bias_quantizer=bias_quantizer, depthwise_activation=depthwise_activation, pointwise_range=pointwise_range, depthwise_range=depthwise_range, bias_range=bias_range, name=name + "_c_h_to_h")(x_h) else: x_h = QConv2D( filters, kernel_size, strides=strides, padding=padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, kernel_quantizer=kernel_quantizer, bias_quantizer=bias_quantizer, kernel_range=kernel_range, bias_range=bias_range, name=name + "_c_h_to_h")(x_h) if activation: x_h = QActivation( activation, name=name + "_c_h_to_h_act" + act_suffix)( x_h) return [x_h, None] co_h = int(filters * (1 - alpha)) co_l = filters - co_h x_h_to_h = None x_h_to_l = None x_l_to_l = None x_l_to_h = None if co_h > 0: if x_h is not None: if use_separable: x_h_to_h = QSeparableConv2D( co_h, kernel_size, strides=strides, padding=padding, depthwise_regularizer=kernel_regularizer, depthwise_constraint=kernel_constraint, depthwise_initializer=kernel_initializer, pointwise_regularizer=kernel_regularizer, pointwise_constraint=kernel_constraint, pointwise_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, depthwise_quantizer=depthwise_quantizer, pointwise_quantizer=pointwise_quantizer, bias_quantizer=bias_quantizer, depthwise_activation=depthwise_activation, pointwise_range=pointwise_range, depthwise_range=depthwise_range, bias_range=bias_range, name=name + "_c_h_to_h")(x_h) else: x_h_to_h = QConv2D( co_h, kernel_size, strides=strides, padding=padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, kernel_quantizer=kernel_quantizer, bias_quantizer=bias_quantizer, kernel_range=kernel_range, bias_range=bias_range, name=name + "_c_h_to_h")(x_h) if acc_quantizer: x_h_to_h = QActivation( acc_quantizer, name=name + "_c_h_to_h_act" + acc_suffix)(x_h_to_h) if co_l > 0: if x_h is not None: x_h_to_l = QAveragePooling2D( pool_size=2, strides=2, quantizer=pooling_quantizer, name=name + "_avg_h_to_l")(x_h) if use_separable: x_h_to_l = QSeparableConv2D( co_l, kernel_size, strides=strides, padding=padding, depthwise_regularizer=kernel_regularizer, depthwise_constraint=kernel_constraint, depthwise_initializer=kernel_initializer, pointwise_regularizer=kernel_regularizer, pointwise_constraint=kernel_constraint, pointwise_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, depthwise_quantizer=depthwise_quantizer, pointwise_quantizer=pointwise_quantizer, bias_quantizer=bias_quantizer, depthwise_activation=depthwise_activation, pointwise_range=pointwise_range, depthwise_range=depthwise_range, bias_range=bias_range, name=name + "_c_h_to_l")(x_h_to_l) else: x_h_to_l = QConv2D( co_l, kernel_size, strides=strides, padding=padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, kernel_quantizer=kernel_quantizer, bias_quantizer=bias_quantizer, kernel_range=kernel_range, bias_range=bias_range, name=name + "_c_h_to_l")(x_h_to_l) if acc_quantizer: x_h_to_l = QActivation( acc_quantizer, name=name + "_c_h_to_l_act" + acc_suffix)(x_h_to_l) if co_h > 0: if x_l is not None: _, height, width, _ = x_l.shape.as_list() if height == 1 and width == 1: local_kernel = 1 local_strides = 1 local_padding = "same" upsampling = False else: local_kernel = kernel_size local_strides = strides local_padding = padding upsampling = True if use_separable and upsampling: x_l_to_h = QSeparableConv2D( co_h, kernel_size, strides=strides, padding=padding, depthwise_regularizer=kernel_regularizer, depthwise_constraint=kernel_constraint, depthwise_initializer=kernel_initializer, pointwise_regularizer=kernel_regularizer, pointwise_constraint=kernel_constraint, pointwise_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, depthwise_quantizer=depthwise_quantizer, pointwise_quantizer=pointwise_quantizer, bias_quantizer=bias_quantizer, depthwise_activation=depthwise_activation, pointwise_range=pointwise_range, depthwise_range=depthwise_range, bias_range=bias_range, name=name + "_c_l_to_h")(x_l) else: x_l_to_h = QConv2D( co_h, local_kernel, strides=local_strides, padding=local_padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, kernel_quantizer=kernel_quantizer, bias_quantizer=bias_quantizer, kernel_range=kernel_range, bias_range=bias_range, name=name + "_c_l_to_h")(x_l) if acc_quantizer: x_l_to_h = QActivation( acc_quantizer, name=name + "_c_l_to_h_act" + acc_suffix)(x_l_to_h) if upsampling: x_l_to_h = UpSampling2D( size=(2, 2), name=name + "_u_l_to_h")(x_l_to_h) if co_l > 0: if x_l is not None: if use_separable: x_l_to_l = QSeparableConv2D( co_l, kernel_size, strides=strides, padding=padding, depthwise_regularizer=kernel_regularizer, depthwise_constraint=kernel_constraint, depthwise_initializer=kernel_initializer, pointwise_regularizer=kernel_regularizer, pointwise_constraint=kernel_constraint, pointwise_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, depthwise_quantizer=depthwise_quantizer, pointwise_quantizer=depthwise_quantizer, bias_quantizer=bias_quantizer, depthwise_activation=depthwise_activation, pointwise_range=pointwise_range, depthwise_range=depthwise_range, bias_range=bias_range, name=name + "_c_l_to_l")(x_l) else: x_l_to_l = QConv2D( co_l, kernel_size, strides=strides, padding=padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, kernel_quantizer=kernel_quantizer, bias_quantizer=bias_quantizer, kernel_range=kernel_range, bias_range=bias_range, name=name + "_c_l_to_l")(x_l) if acc_quantizer: x_l_to_l = QActivation( acc_quantizer, name=name + "_c_l_to_l_act" + acc_suffix)( x_l_to_l) if x_h_to_h is not None and x_l_to_h is not None: x_h = Add(name=name + "_a_h")([x_h_to_h, x_l_to_h]) elif x_h_to_h is not None: x_h = x_h_to_h elif x_l_to_h is not None: x_h = x_l_to_h else: x_h = None if x_l_to_l is not None and x_h_to_l is not None: x_l = Add(name=name + "_a_l")([x_l_to_l, x_h_to_l]) elif x_l_to_l is not None: x_l = x_l_to_l elif x_h_to_l is not None: x_l = x_h_to_l else: x_l = None if x_h is not None and activation is not None: x_h = QActivation(activation, name=name + "_h_act" + act_suffix)(x_h) if x_l is not None and activation is not None: x_l = QActivation(activation, name=name + "_l_act" + act_suffix)(x_l) return [x_h, x_l] return _QOctaveConv2DInternal def OctaveConv2D( filters, kernel_size, alpha, strides=(1, 1), padding="valid", kernel_initializer="he_normal", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, kernel_constraint=None, bias_constraint=None, activation=None, use_separable=True, name="", **kwargs): """Implements OctaveConv2D.""" def _OctaveConv2DInternal(x): """Computes octave on tensor.""" acc_quantizer = kwargs.get("acc_quantizer", None) x_h, x_l = x if alpha == -1.0: if use_separable: x_h = SeparableConv2D( filters, kernel_size, strides=strides, padding=padding, depthwise_regularizer=kernel_regularizer, depthwise_constraint=kernel_constraint, depthwise_initializer=kernel_initializer, pointwise_regularizer=kernel_regularizer, pointwise_constraint=kernel_constraint, pointwise_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name + "_c_h_to_h")(x_h) else: x_h = Conv2D( filters, kernel_size, strides=strides, padding=padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name+"_c_h_to_h")(x_h) if activation: x_h = Activation(activation, name=name + "_c_h_to_h_act")(x_h) return [x_h, None] co_h = int(filters * (1 - alpha)) co_l = filters - co_h x_h_to_h = None x_h_to_l = None x_l_to_l = None x_l_to_h = None if co_h > 0: if x_h is not None: if use_separable: x_h_to_h = SeparableConv2D( co_h, kernel_size, strides=strides, padding=padding, depthwise_regularizer=kernel_regularizer, depthwise_constraint=kernel_constraint, depthwise_initializer=kernel_initializer, pointwise_regularizer=kernel_regularizer, pointwise_constraint=kernel_constraint, pointwise_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name + "_c_h_to_h")(x_h) else: x_h_to_h = Conv2D( co_h, kernel_size, strides=strides, padding=padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name + "_c_h_to_h")(x_h) if activation: x_h_to_h = Activation( acc_quantizer, name=name + "_c_h_to_h_act")(x_h_to_h) if co_l > 0: if x_h is not None: x_h_to_l = AveragePooling2D(pool_size=2, strides=2, name=name + "_p_h_to_l")(x_h) if use_separable: x_h_to_l = SeparableConv2D( co_l, kernel_size, strides=strides, padding=padding, depthwise_regularizer=kernel_regularizer, depthwise_constraint=kernel_constraint, depthwise_initializer=kernel_initializer, pointwise_regularizer=kernel_regularizer, pointwise_constraint=kernel_constraint, pointwise_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name + "_c_h_to_l")(x_h_to_l) else: x_h_to_l = Conv2D( co_l, kernel_size, strides=strides, padding=padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name + "_c_h_to_l")(x_h_to_l) if activation: x_h_to_l = Activation( acc_quantizer, name=name + "_c_h_to_l_act")(x_h_to_l) if co_h > 0: if x_l is not None: _, height, width, _ = x_l.shape.as_list() if height == 1 and width == 1: local_kernel = 1 local_strides = 1 local_padding = "same" upsampling = False else: local_kernel = kernel_size local_strides = strides local_padding = padding upsampling = True if use_separable and upsampling: x_l_to_h = SeparableConv2D( co_h, kernel_size, strides=strides, padding=padding, depthwise_regularizer=kernel_regularizer, depthwise_constraint=kernel_constraint, depthwise_initializer=kernel_initializer, pointwise_regularizer=kernel_regularizer, pointwise_constraint=kernel_constraint, pointwise_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name + "_c_l_to_h")(x_l) else: x_l_to_h = Conv2D( co_h, local_kernel, strides=local_strides, padding=local_padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name + "_c_l_to_h")(x_l) if activation: x_l_to_h = Activation( acc_quantizer, name=name + "_c_l_to_h_act")(x_l_to_h) if upsampling: x_l_to_h = UpSampling2D( size=(2, 2), name=name + "_u_l_to_h")(x_l_to_h) if co_l > 0: if x_l is not None: if use_separable: x_l_to_l = SeparableConv2D( co_l, kernel_size, strides=strides, padding=padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name + "_c_l_to_l")(x_l) else: x_l_to_l = Conv2D( co_l, kernel_size, strides=strides, padding=padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name + "_c_l_to_l")(x_l) if activation: x_l_to_l = Activation( acc_quantizer, name=name + "_c_l_to_l_act")(x_l_to_l) if x_h_to_h is not None and x_l_to_h is not None: x_h = Add(name=name + "_a_h")([x_h_to_h, x_l_to_h]) elif x_h_to_h is not None: x_h = x_h_to_h elif x_l_to_h is not None: x_h = x_l_to_h else: x_h = None if x_l_to_l is not None and x_h_to_l is not None: x_l = Add(name=name + "_a_l")([x_l_to_l, x_h_to_l]) elif x_l_to_l is not None: x_l = x_l_to_l elif x_h_to_l is not None: x_l = x_h_to_l else: x_l = None if x_h is not None: x_h = Activation(activation, name=name + "_h_act")(x_h) if x_l is not None: x_l = Activation(activation, name=name + "_l_act")(x_l) return (x_h, x_l) return _OctaveConv2DInternal
36.806397
80
0.634725
from __future__ import absolute_import from __future__ import division from __future__ import print_function import re from keras.layers import Activation from keras.layers import Add from keras.layers import AveragePooling2D from keras.layers import Conv2D from keras.layers import SeparableConv2D from keras.layers import UpSampling2D from .qlayers import QActivation from .qlayers import QAveragePooling2D from .qlayers import QConv2D from .qlayers import QSeparableConv2D def GetActivationSuffix(activation): if not activation: return "linear" if "po2" in activation: return "q2" elif "quantized_relu" in activation: suffix = "qr" elif "quantized_tanh" in activation: suffix = "qt" else: suffix = "qb" numbers = re.findall(r"[0-9]+", activation) numbers = [n + "_" if len(n) > 1 else n for n in numbers] return suffix + "".join(numbers) def QOctaveConv2D( filters, kernel_size, alpha, strides=(1, 1), padding="valid", kernel_initializer="he_normal", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, kernel_constraint=None, bias_constraint=None, use_separable=True, name="", **kwargs): def _QOctaveConv2DInternal(x): x_h, x_l = x bias_quantizer = kwargs.get("bias_quantizer", None) kernel_quantizer = kwargs.get("kernel_quantizer", None) depthwise_quantizer = kwargs.get("depthwise_quantizer", None) pointwise_quantizer = kwargs.get("pointwise_quantizer", None) acc_quantizer = kwargs.get("acc_quantizer", None) pooling_quantizer = kwargs.get("pooling_quantizer", None) depthwise_activation = kwargs.get("depthwise_activation", None) activation = kwargs.get("activation", None) bias_range = kwargs.get("bias_range", 1.0) kernel_range = kwargs.get("kernel_range", 1.0) depthwise_range = kwargs.get("depthwise_range", 1.0) pointwise_range = kwargs.get("pointwise_range", 1.0) if activation: act_suffix = "_" + GetActivationSuffix(activation) acc_suffix = "_" + GetActivationSuffix(acc_quantizer) if alpha == -1.0: if use_separable: x_h = QSeparableConv2D( filters, kernel_size, strides=strides, padding=padding, depthwise_regularizer=kernel_regularizer, depthwise_constraint=kernel_constraint, depthwise_initializer=kernel_initializer, pointwise_regularizer=kernel_regularizer, pointwise_constraint=kernel_constraint, pointwise_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, depthwise_quantizer=depthwise_quantizer, pointwise_quantizer=pointwise_quantizer, bias_quantizer=bias_quantizer, depthwise_activation=depthwise_activation, pointwise_range=pointwise_range, depthwise_range=depthwise_range, bias_range=bias_range, name=name + "_c_h_to_h")(x_h) else: x_h = QConv2D( filters, kernel_size, strides=strides, padding=padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, kernel_quantizer=kernel_quantizer, bias_quantizer=bias_quantizer, kernel_range=kernel_range, bias_range=bias_range, name=name + "_c_h_to_h")(x_h) if activation: x_h = QActivation( activation, name=name + "_c_h_to_h_act" + act_suffix)( x_h) return [x_h, None] co_h = int(filters * (1 - alpha)) co_l = filters - co_h x_h_to_h = None x_h_to_l = None x_l_to_l = None x_l_to_h = None if co_h > 0: if x_h is not None: if use_separable: x_h_to_h = QSeparableConv2D( co_h, kernel_size, strides=strides, padding=padding, depthwise_regularizer=kernel_regularizer, depthwise_constraint=kernel_constraint, depthwise_initializer=kernel_initializer, pointwise_regularizer=kernel_regularizer, pointwise_constraint=kernel_constraint, pointwise_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, depthwise_quantizer=depthwise_quantizer, pointwise_quantizer=pointwise_quantizer, bias_quantizer=bias_quantizer, depthwise_activation=depthwise_activation, pointwise_range=pointwise_range, depthwise_range=depthwise_range, bias_range=bias_range, name=name + "_c_h_to_h")(x_h) else: x_h_to_h = QConv2D( co_h, kernel_size, strides=strides, padding=padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, kernel_quantizer=kernel_quantizer, bias_quantizer=bias_quantizer, kernel_range=kernel_range, bias_range=bias_range, name=name + "_c_h_to_h")(x_h) if acc_quantizer: x_h_to_h = QActivation( acc_quantizer, name=name + "_c_h_to_h_act" + acc_suffix)(x_h_to_h) if co_l > 0: if x_h is not None: x_h_to_l = QAveragePooling2D( pool_size=2, strides=2, quantizer=pooling_quantizer, name=name + "_avg_h_to_l")(x_h) if use_separable: x_h_to_l = QSeparableConv2D( co_l, kernel_size, strides=strides, padding=padding, depthwise_regularizer=kernel_regularizer, depthwise_constraint=kernel_constraint, depthwise_initializer=kernel_initializer, pointwise_regularizer=kernel_regularizer, pointwise_constraint=kernel_constraint, pointwise_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, depthwise_quantizer=depthwise_quantizer, pointwise_quantizer=pointwise_quantizer, bias_quantizer=bias_quantizer, depthwise_activation=depthwise_activation, pointwise_range=pointwise_range, depthwise_range=depthwise_range, bias_range=bias_range, name=name + "_c_h_to_l")(x_h_to_l) else: x_h_to_l = QConv2D( co_l, kernel_size, strides=strides, padding=padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, kernel_quantizer=kernel_quantizer, bias_quantizer=bias_quantizer, kernel_range=kernel_range, bias_range=bias_range, name=name + "_c_h_to_l")(x_h_to_l) if acc_quantizer: x_h_to_l = QActivation( acc_quantizer, name=name + "_c_h_to_l_act" + acc_suffix)(x_h_to_l) if co_h > 0: if x_l is not None: _, height, width, _ = x_l.shape.as_list() if height == 1 and width == 1: local_kernel = 1 local_strides = 1 local_padding = "same" upsampling = False else: local_kernel = kernel_size local_strides = strides local_padding = padding upsampling = True if use_separable and upsampling: x_l_to_h = QSeparableConv2D( co_h, kernel_size, strides=strides, padding=padding, depthwise_regularizer=kernel_regularizer, depthwise_constraint=kernel_constraint, depthwise_initializer=kernel_initializer, pointwise_regularizer=kernel_regularizer, pointwise_constraint=kernel_constraint, pointwise_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, depthwise_quantizer=depthwise_quantizer, pointwise_quantizer=pointwise_quantizer, bias_quantizer=bias_quantizer, depthwise_activation=depthwise_activation, pointwise_range=pointwise_range, depthwise_range=depthwise_range, bias_range=bias_range, name=name + "_c_l_to_h")(x_l) else: x_l_to_h = QConv2D( co_h, local_kernel, strides=local_strides, padding=local_padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, kernel_quantizer=kernel_quantizer, bias_quantizer=bias_quantizer, kernel_range=kernel_range, bias_range=bias_range, name=name + "_c_l_to_h")(x_l) if acc_quantizer: x_l_to_h = QActivation( acc_quantizer, name=name + "_c_l_to_h_act" + acc_suffix)(x_l_to_h) if upsampling: x_l_to_h = UpSampling2D( size=(2, 2), name=name + "_u_l_to_h")(x_l_to_h) if co_l > 0: if x_l is not None: if use_separable: x_l_to_l = QSeparableConv2D( co_l, kernel_size, strides=strides, padding=padding, depthwise_regularizer=kernel_regularizer, depthwise_constraint=kernel_constraint, depthwise_initializer=kernel_initializer, pointwise_regularizer=kernel_regularizer, pointwise_constraint=kernel_constraint, pointwise_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, depthwise_quantizer=depthwise_quantizer, pointwise_quantizer=depthwise_quantizer, bias_quantizer=bias_quantizer, depthwise_activation=depthwise_activation, pointwise_range=pointwise_range, depthwise_range=depthwise_range, bias_range=bias_range, name=name + "_c_l_to_l")(x_l) else: x_l_to_l = QConv2D( co_l, kernel_size, strides=strides, padding=padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, kernel_quantizer=kernel_quantizer, bias_quantizer=bias_quantizer, kernel_range=kernel_range, bias_range=bias_range, name=name + "_c_l_to_l")(x_l) if acc_quantizer: x_l_to_l = QActivation( acc_quantizer, name=name + "_c_l_to_l_act" + acc_suffix)( x_l_to_l) if x_h_to_h is not None and x_l_to_h is not None: x_h = Add(name=name + "_a_h")([x_h_to_h, x_l_to_h]) elif x_h_to_h is not None: x_h = x_h_to_h elif x_l_to_h is not None: x_h = x_l_to_h else: x_h = None if x_l_to_l is not None and x_h_to_l is not None: x_l = Add(name=name + "_a_l")([x_l_to_l, x_h_to_l]) elif x_l_to_l is not None: x_l = x_l_to_l elif x_h_to_l is not None: x_l = x_h_to_l else: x_l = None if x_h is not None and activation is not None: x_h = QActivation(activation, name=name + "_h_act" + act_suffix)(x_h) if x_l is not None and activation is not None: x_l = QActivation(activation, name=name + "_l_act" + act_suffix)(x_l) return [x_h, x_l] return _QOctaveConv2DInternal def OctaveConv2D( filters, kernel_size, alpha, strides=(1, 1), padding="valid", kernel_initializer="he_normal", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, kernel_constraint=None, bias_constraint=None, activation=None, use_separable=True, name="", **kwargs): def _OctaveConv2DInternal(x): acc_quantizer = kwargs.get("acc_quantizer", None) x_h, x_l = x if alpha == -1.0: if use_separable: x_h = SeparableConv2D( filters, kernel_size, strides=strides, padding=padding, depthwise_regularizer=kernel_regularizer, depthwise_constraint=kernel_constraint, depthwise_initializer=kernel_initializer, pointwise_regularizer=kernel_regularizer, pointwise_constraint=kernel_constraint, pointwise_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name + "_c_h_to_h")(x_h) else: x_h = Conv2D( filters, kernel_size, strides=strides, padding=padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name+"_c_h_to_h")(x_h) if activation: x_h = Activation(activation, name=name + "_c_h_to_h_act")(x_h) return [x_h, None] co_h = int(filters * (1 - alpha)) co_l = filters - co_h x_h_to_h = None x_h_to_l = None x_l_to_l = None x_l_to_h = None if co_h > 0: if x_h is not None: if use_separable: x_h_to_h = SeparableConv2D( co_h, kernel_size, strides=strides, padding=padding, depthwise_regularizer=kernel_regularizer, depthwise_constraint=kernel_constraint, depthwise_initializer=kernel_initializer, pointwise_regularizer=kernel_regularizer, pointwise_constraint=kernel_constraint, pointwise_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name + "_c_h_to_h")(x_h) else: x_h_to_h = Conv2D( co_h, kernel_size, strides=strides, padding=padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name + "_c_h_to_h")(x_h) if activation: x_h_to_h = Activation( acc_quantizer, name=name + "_c_h_to_h_act")(x_h_to_h) if co_l > 0: if x_h is not None: x_h_to_l = AveragePooling2D(pool_size=2, strides=2, name=name + "_p_h_to_l")(x_h) if use_separable: x_h_to_l = SeparableConv2D( co_l, kernel_size, strides=strides, padding=padding, depthwise_regularizer=kernel_regularizer, depthwise_constraint=kernel_constraint, depthwise_initializer=kernel_initializer, pointwise_regularizer=kernel_regularizer, pointwise_constraint=kernel_constraint, pointwise_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name + "_c_h_to_l")(x_h_to_l) else: x_h_to_l = Conv2D( co_l, kernel_size, strides=strides, padding=padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name + "_c_h_to_l")(x_h_to_l) if activation: x_h_to_l = Activation( acc_quantizer, name=name + "_c_h_to_l_act")(x_h_to_l) if co_h > 0: if x_l is not None: _, height, width, _ = x_l.shape.as_list() if height == 1 and width == 1: local_kernel = 1 local_strides = 1 local_padding = "same" upsampling = False else: local_kernel = kernel_size local_strides = strides local_padding = padding upsampling = True if use_separable and upsampling: x_l_to_h = SeparableConv2D( co_h, kernel_size, strides=strides, padding=padding, depthwise_regularizer=kernel_regularizer, depthwise_constraint=kernel_constraint, depthwise_initializer=kernel_initializer, pointwise_regularizer=kernel_regularizer, pointwise_constraint=kernel_constraint, pointwise_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name + "_c_l_to_h")(x_l) else: x_l_to_h = Conv2D( co_h, local_kernel, strides=local_strides, padding=local_padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name + "_c_l_to_h")(x_l) if activation: x_l_to_h = Activation( acc_quantizer, name=name + "_c_l_to_h_act")(x_l_to_h) if upsampling: x_l_to_h = UpSampling2D( size=(2, 2), name=name + "_u_l_to_h")(x_l_to_h) if co_l > 0: if x_l is not None: if use_separable: x_l_to_l = SeparableConv2D( co_l, kernel_size, strides=strides, padding=padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name + "_c_l_to_l")(x_l) else: x_l_to_l = Conv2D( co_l, kernel_size, strides=strides, padding=padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name + "_c_l_to_l")(x_l) if activation: x_l_to_l = Activation( acc_quantizer, name=name + "_c_l_to_l_act")(x_l_to_l) if x_h_to_h is not None and x_l_to_h is not None: x_h = Add(name=name + "_a_h")([x_h_to_h, x_l_to_h]) elif x_h_to_h is not None: x_h = x_h_to_h elif x_l_to_h is not None: x_h = x_l_to_h else: x_h = None if x_l_to_l is not None and x_h_to_l is not None: x_l = Add(name=name + "_a_l")([x_l_to_l, x_h_to_l]) elif x_l_to_l is not None: x_l = x_l_to_l elif x_h_to_l is not None: x_l = x_h_to_l else: x_l = None if x_h is not None: x_h = Activation(activation, name=name + "_h_act")(x_h) if x_l is not None: x_l = Activation(activation, name=name + "_l_act")(x_l) return (x_h, x_l) return _OctaveConv2DInternal
true
true
f7259600ce77f1327a75cfc7ad33fc54ddf8e263
261
py
Python
daily_work/daily_work/doctype/daily_default_setting/daily_default_setting.py
muirawachanga/mwai
1a95cba5bc6368361fc48984ba05307ae4093ead
[ "MIT" ]
null
null
null
daily_work/daily_work/doctype/daily_default_setting/daily_default_setting.py
muirawachanga/mwai
1a95cba5bc6368361fc48984ba05307ae4093ead
[ "MIT" ]
null
null
null
daily_work/daily_work/doctype/daily_default_setting/daily_default_setting.py
muirawachanga/mwai
1a95cba5bc6368361fc48984ba05307ae4093ead
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Copyright (c) 2019, steve and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document class DailyDefaultSetting(Document): pass
23.727273
49
0.785441
from __future__ import unicode_literals import frappe from frappe.model.document import Document class DailyDefaultSetting(Document): pass
true
true
f7259615a162f1f9b8997248b81998d51618e2f1
1,384
py
Python
cli.py
stesla/arxtools
7f1a3b973e3d78faed4085d547b7d27ebcd9838d
[ "MIT" ]
null
null
null
cli.py
stesla/arxtools
7f1a3b973e3d78faed4085d547b7d27ebcd9838d
[ "MIT" ]
null
null
null
cli.py
stesla/arxtools
7f1a3b973e3d78faed4085d547b7d27ebcd9838d
[ "MIT" ]
null
null
null
import click import configparser import json import sys from arxtools import export_clues, fetch_clues from arxtools.clue import Clue @click.group() def cli(): pass def get_character_info(name): config = configparser.ConfigParser() config.read('arxtools.ini') try: return config[name.lower()] except KeyError: click.echo(f'No character named "{name}" found.', err=True) sys.exit(1) @cli.command("import") @click.argument('name') def _import(name): info = get_character_info(name) username = info['username'] password = info['password'] clues = fetch_clues(username, password) click.echo(json.dumps([c.to_dict() for c in clues])) @cli.command("export") @click.argument('name') def _export(name): info = get_character_info(name) directory = info['directory'] clues = [Clue.from_dict(c) for c in json.load(sys.stdin)] export_clues(clues, directory) @cli.command('update') @click.argument('name') def _update(name): info = get_character_info(name) username = info['username'] password = info['password'] directory = info['directory'] click.echo(f'Fetching clues for {username}...', err=True) clues = fetch_clues(username, password) click.echo(f'Exporting to markdown in {directory}...', err=True) export_clues(clues, directory) if __name__ == '__main__': cli()
24.714286
68
0.682803
import click import configparser import json import sys from arxtools import export_clues, fetch_clues from arxtools.clue import Clue @click.group() def cli(): pass def get_character_info(name): config = configparser.ConfigParser() config.read('arxtools.ini') try: return config[name.lower()] except KeyError: click.echo(f'No character named "{name}" found.', err=True) sys.exit(1) @cli.command("import") @click.argument('name') def _import(name): info = get_character_info(name) username = info['username'] password = info['password'] clues = fetch_clues(username, password) click.echo(json.dumps([c.to_dict() for c in clues])) @cli.command("export") @click.argument('name') def _export(name): info = get_character_info(name) directory = info['directory'] clues = [Clue.from_dict(c) for c in json.load(sys.stdin)] export_clues(clues, directory) @cli.command('update') @click.argument('name') def _update(name): info = get_character_info(name) username = info['username'] password = info['password'] directory = info['directory'] click.echo(f'Fetching clues for {username}...', err=True) clues = fetch_clues(username, password) click.echo(f'Exporting to markdown in {directory}...', err=True) export_clues(clues, directory) if __name__ == '__main__': cli()
true
true
f7259776fb98e992d885bf99cf4adf99f37e8745
8,549
py
Python
gui/qt/utxo_list.py
ComputerCraftr/openswap
7de04aa80dab79bebe4b64483011dad70a48694c
[ "MIT" ]
16
2018-11-05T13:19:02.000Z
2021-04-06T12:11:49.000Z
gui/qt/utxo_list.py
ComputerCraftr/openswap
7de04aa80dab79bebe4b64483011dad70a48694c
[ "MIT" ]
11
2018-11-11T08:56:03.000Z
2018-12-08T02:31:57.000Z
gui/qt/utxo_list.py
ComputerCraftr/openswap
7de04aa80dab79bebe4b64483011dad70a48694c
[ "MIT" ]
5
2019-01-07T13:45:05.000Z
2020-06-12T14:13:21.000Z
#!/usr/bin/env python # # Electrum - lightweight Bitcoin client # Copyright (C) 2015 Thomas Voegtlin # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, merge, # publish, distribute, sublicense, and/or sell copies of the Software, # and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from .util import * from electroncash.i18n import _ class UTXOList(MyTreeWidget): filter_columns = [0, 2] # Address, Label def __init__(self, parent=None): MyTreeWidget.__init__(self, parent, self.create_menu, [ _('Address'), _('Label'), _('Amount'), _('Height'), _('Output point')], 1) self.setSelectionMode(QAbstractItemView.ExtendedSelection) self.setSortingEnabled(True) # force attributes to always be defined, even if None, at construction. self.wallet = self.parent.wallet if hasattr(self.parent, 'wallet') else None self.utxos = list() def get_name(self, x): return x.get('prevout_hash') + ":%d"%x.get('prevout_n') @rate_limited(1.0) # performance tweak -- limit updates to no more than oncer per second def update(self): if self.wallet and self.wallet.thread and not self.wallet.thread.isRunning(): # short-cut return if window was closed and wallet is stopped return super().update() def on_update(self): prev_selection = self.get_selected() # cache previous selection, if any self.clear() self.wallet = self.parent.wallet if not self.wallet: return self.utxos = self.wallet.get_utxos() for x in self.utxos: address = x['address'] address_text = address.to_ui_string() height = x['height'] name = self.get_name(x) label = self.wallet.get_label(x['prevout_hash']) amount = self.parent.format_amount(x['value']) utxo_item = SortableTreeWidgetItem([address_text, label, amount, str(height), name[0:10] + '...' + name[-2:]]) utxo_item.DataRole = Qt.UserRole+100 # set this here to avoid sorting based on Qt.UserRole+1 utxo_item.setFont(0, QFont(MONOSPACE_FONT)) utxo_item.setFont(4, QFont(MONOSPACE_FONT)) utxo_item.setData(0, Qt.UserRole, name) a_frozen = self.wallet.is_frozen(address) c_frozen = x['is_frozen_coin'] if a_frozen and not c_frozen: # address is frozen, coin is not frozen # emulate the "Look" off the address_list .py's frozen entry utxo_item.setBackground(0, QColor('lightblue')) elif c_frozen and not a_frozen: # coin is frozen, address is not frozen utxo_item.setBackground(0, ColorScheme.BLUE.as_color(True)) elif c_frozen and a_frozen: # both coin and address are frozen so color-code it to indicate that. utxo_item.setBackground(0, QColor('lightblue')) utxo_item.setForeground(0, QColor('#3399ff')) # save the address-level-frozen and coin-level-frozen flags to the data item for retrieval later in create_menu() below. utxo_item.setData(0, Qt.UserRole+1, "{}{}".format(("a" if a_frozen else ""), ("c" if c_frozen else ""))) self.addChild(utxo_item) if name in prev_selection: # NB: This needs to be here after the item is added to the widget. See #979. utxo_item.setSelected(True) # restore previous selection def get_selected(self): return { x.data(0, Qt.UserRole) : x.data(0, Qt.UserRole+1) # dict of "name" -> frozen flags string (eg: "ac") for x in self.selectedItems() } def create_menu(self, position): selected = self.get_selected() if not selected: return menu = QMenu() coins = filter(lambda x: self.get_name(x) in selected, self.utxos) spendable_coins = list(filter(lambda x: not selected.get(self.get_name(x), ''), coins)) # Unconditionally add the "Spend" option but leave it disabled if there are no spendable_coins menu.addAction(_("Spend"), lambda: self.parent.spend_coins(spendable_coins)).setEnabled(bool(spendable_coins)) if len(selected) == 1: # single selection, offer them the "Details" option and also coin/address "freeze" status, if any txid = list(selected.keys())[0].split(':')[0] frozen_flags = list(selected.values())[0] tx = self.wallet.transactions.get(txid) if tx: label = self.wallet.get_label(txid) or None menu.addAction(_("Details"), lambda: self.parent.show_transaction(tx, label)) act = None needsep = True if 'c' in frozen_flags: menu.addSeparator() menu.addAction(_("Coin is frozen"), lambda: None).setEnabled(False) menu.addAction(_("Unfreeze Coin"), lambda: self.set_frozen_coins(list(selected.keys()), False)) menu.addSeparator() needsep = False else: menu.addAction(_("Freeze Coin"), lambda: self.set_frozen_coins(list(selected.keys()), True)) if 'a' in frozen_flags: if needsep: menu.addSeparator() menu.addAction(_("Address is frozen"), lambda: None).setEnabled(False) menu.addAction(_("Unfreeze Address"), lambda: self.set_frozen_addresses_for_coins(list(selected.keys()), False)) else: menu.addAction(_("Freeze Address"), lambda: self.set_frozen_addresses_for_coins(list(selected.keys()), True)) else: # multi-selection menu.addSeparator() if any(['c' not in flags for flags in selected.values()]): # they have some coin-level non-frozen in the selection, so add the menu action "Freeze coins" menu.addAction(_("Freeze Coins"), lambda: self.set_frozen_coins(list(selected.keys()), True)) if any(['c' in flags for flags in selected.values()]): # they have some coin-level frozen in the selection, so add the menu action "Unfreeze coins" menu.addAction(_("Unfreeze Coins"), lambda: self.set_frozen_coins(list(selected.keys()), False)) if any(['a' not in flags for flags in selected.values()]): # they have some address-level non-frozen in the selection, so add the menu action "Freeze addresses" menu.addAction(_("Freeze Addresses"), lambda: self.set_frozen_addresses_for_coins(list(selected.keys()), True)) if any(['a' in flags for flags in selected.values()]): # they have some address-level frozen in the selection, so add the menu action "Unfreeze addresses" menu.addAction(_("Unfreeze Addresses"), lambda: self.set_frozen_addresses_for_coins(list(selected.keys()), False)) menu.exec_(self.viewport().mapToGlobal(position)) def on_permit_edit(self, item, column): # disable editing fields in this tab (labels) return False def set_frozen_coins(self, coins, b): if self.parent: self.parent.set_frozen_coin_state(coins, b) def set_frozen_addresses_for_coins(self, coins, b): if not self.parent: return addrs = set() for utxo in self.utxos: name = self.get_name(utxo) if name in coins: addrs.add(utxo['address']) if addrs: self.parent.set_frozen_state(list(addrs), b)
52.771605
138
0.63177
from .util import * from electroncash.i18n import _ class UTXOList(MyTreeWidget): filter_columns = [0, 2] def __init__(self, parent=None): MyTreeWidget.__init__(self, parent, self.create_menu, [ _('Address'), _('Label'), _('Amount'), _('Height'), _('Output point')], 1) self.setSelectionMode(QAbstractItemView.ExtendedSelection) self.setSortingEnabled(True) self.wallet = self.parent.wallet if hasattr(self.parent, 'wallet') else None self.utxos = list() def get_name(self, x): return x.get('prevout_hash') + ":%d"%x.get('prevout_n') @rate_limited(1.0) def update(self): if self.wallet and self.wallet.thread and not self.wallet.thread.isRunning(): return super().update() def on_update(self): prev_selection = self.get_selected() self.clear() self.wallet = self.parent.wallet if not self.wallet: return self.utxos = self.wallet.get_utxos() for x in self.utxos: address = x['address'] address_text = address.to_ui_string() height = x['height'] name = self.get_name(x) label = self.wallet.get_label(x['prevout_hash']) amount = self.parent.format_amount(x['value']) utxo_item = SortableTreeWidgetItem([address_text, label, amount, str(height), name[0:10] + '...' + name[-2:]]) utxo_item.DataRole = Qt.UserRole+100 utxo_item.setFont(0, QFont(MONOSPACE_FONT)) utxo_item.setFont(4, QFont(MONOSPACE_FONT)) utxo_item.setData(0, Qt.UserRole, name) a_frozen = self.wallet.is_frozen(address) c_frozen = x['is_frozen_coin'] if a_frozen and not c_frozen: utxo_item.setBackground(0, QColor('lightblue')) elif c_frozen and not a_frozen: # coin is frozen, address is not frozen utxo_item.setBackground(0, ColorScheme.BLUE.as_color(True)) elif c_frozen and a_frozen: # both coin and address are frozen so color-code it to indicate that. utxo_item.setBackground(0, QColor('lightblue')) utxo_item.setForeground(0, QColor(' # save the address-level-frozen and coin-level-frozen flags to the data item for retrieval later in create_menu() below. utxo_item.setData(0, Qt.UserRole+1, "{}{}".format(("a" if a_frozen else ""), ("c" if c_frozen else ""))) self.addChild(utxo_item) if name in prev_selection: # NB: This needs to be here after the item is added to the widget. See #979. utxo_item.setSelected(True) # restore previous selection def get_selected(self): return { x.data(0, Qt.UserRole) : x.data(0, Qt.UserRole+1) # dict of "name" -> frozen flags string (eg: "ac") for x in self.selectedItems() } def create_menu(self, position): selected = self.get_selected() if not selected: return menu = QMenu() coins = filter(lambda x: self.get_name(x) in selected, self.utxos) spendable_coins = list(filter(lambda x: not selected.get(self.get_name(x), ''), coins)) # Unconditionally add the "Spend" option but leave it disabled if there are no spendable_coins menu.addAction(_("Spend"), lambda: self.parent.spend_coins(spendable_coins)).setEnabled(bool(spendable_coins)) if len(selected) == 1: # single selection, offer them the "Details" option and also coin/address "freeze" status, if any txid = list(selected.keys())[0].split(':')[0] frozen_flags = list(selected.values())[0] tx = self.wallet.transactions.get(txid) if tx: label = self.wallet.get_label(txid) or None menu.addAction(_("Details"), lambda: self.parent.show_transaction(tx, label)) act = None needsep = True if 'c' in frozen_flags: menu.addSeparator() menu.addAction(_("Coin is frozen"), lambda: None).setEnabled(False) menu.addAction(_("Unfreeze Coin"), lambda: self.set_frozen_coins(list(selected.keys()), False)) menu.addSeparator() needsep = False else: menu.addAction(_("Freeze Coin"), lambda: self.set_frozen_coins(list(selected.keys()), True)) if 'a' in frozen_flags: if needsep: menu.addSeparator() menu.addAction(_("Address is frozen"), lambda: None).setEnabled(False) menu.addAction(_("Unfreeze Address"), lambda: self.set_frozen_addresses_for_coins(list(selected.keys()), False)) else: menu.addAction(_("Freeze Address"), lambda: self.set_frozen_addresses_for_coins(list(selected.keys()), True)) else: # multi-selection menu.addSeparator() if any(['c' not in flags for flags in selected.values()]): # they have some coin-level non-frozen in the selection, so add the menu action "Freeze coins" menu.addAction(_("Freeze Coins"), lambda: self.set_frozen_coins(list(selected.keys()), True)) if any(['c' in flags for flags in selected.values()]): # they have some coin-level frozen in the selection, so add the menu action "Unfreeze coins" menu.addAction(_("Unfreeze Coins"), lambda: self.set_frozen_coins(list(selected.keys()), False)) if any(['a' not in flags for flags in selected.values()]): # they have some address-level non-frozen in the selection, so add the menu action "Freeze addresses" menu.addAction(_("Freeze Addresses"), lambda: self.set_frozen_addresses_for_coins(list(selected.keys()), True)) if any(['a' in flags for flags in selected.values()]): # they have some address-level frozen in the selection, so add the menu action "Unfreeze addresses" menu.addAction(_("Unfreeze Addresses"), lambda: self.set_frozen_addresses_for_coins(list(selected.keys()), False)) menu.exec_(self.viewport().mapToGlobal(position)) def on_permit_edit(self, item, column): # disable editing fields in this tab (labels) return False def set_frozen_coins(self, coins, b): if self.parent: self.parent.set_frozen_coin_state(coins, b) def set_frozen_addresses_for_coins(self, coins, b): if not self.parent: return addrs = set() for utxo in self.utxos: name = self.get_name(utxo) if name in coins: addrs.add(utxo['address']) if addrs: self.parent.set_frozen_state(list(addrs), b)
true
true
f72597acf84a319c1cde2a9c2a80f3c7b7cfc2a4
984
py
Python
src/platform/avr/pmfeatures.py
ArtemovSA/PyMite
a22fbae773b285ccf4993905a46dd396cb762f69
[ "OLDAP-2.6", "Python-2.0" ]
51
2015-03-24T07:53:03.000Z
2021-08-06T12:55:53.000Z
src/platform/avr/pmfeatures.py
ArtemovSA/PyMite
a22fbae773b285ccf4993905a46dd396cb762f69
[ "OLDAP-2.6", "Python-2.0" ]
null
null
null
src/platform/avr/pmfeatures.py
ArtemovSA/PyMite
a22fbae773b285ccf4993905a46dd396cb762f69
[ "OLDAP-2.6", "Python-2.0" ]
15
2015-04-09T14:17:27.000Z
2022-01-26T02:42:47.000Z
# This file is Copyright 2010 Dean Hall. # # This file is part of the Python-on-a-Chip program. # Python-on-a-Chip is free software: you can redistribute it and/or modify # it under the terms of the GNU LESSER GENERAL PUBLIC LICENSE Version 2.1. # # Python-on-a-Chip is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # A copy of the GNU LESSER GENERAL PUBLIC LICENSE Version 2.1 # is seen in the file COPYING up one directory from this. PM_FEATURES = { "HAVE_PRINT": True, "HAVE_GC": True, "HAVE_FLOAT": False, "HAVE_DEL": True, "HAVE_IMPORTS": True, "HAVE_DEFAULTARGS": True, "HAVE_REPLICATION": True, "HAVE_CLASSES": False, "HAVE_ASSERT": False, "HAVE_GENERATORS": False, "HAVE_BACKTICK": True, "HAVE_STRING_FORMAT": True, "HAVE_CLOSURES": False, "HAVE_BYTEARRAY": False, "HAVE_DEBUG_INFO": False, }
32.8
74
0.707317
PM_FEATURES = { "HAVE_PRINT": True, "HAVE_GC": True, "HAVE_FLOAT": False, "HAVE_DEL": True, "HAVE_IMPORTS": True, "HAVE_DEFAULTARGS": True, "HAVE_REPLICATION": True, "HAVE_CLASSES": False, "HAVE_ASSERT": False, "HAVE_GENERATORS": False, "HAVE_BACKTICK": True, "HAVE_STRING_FORMAT": True, "HAVE_CLOSURES": False, "HAVE_BYTEARRAY": False, "HAVE_DEBUG_INFO": False, }
true
true
f7259813b4e802d256d946467bf98359af8d5554
2,970
py
Python
ally/Order/tests/PricingConstruction.py
jpwatt/PyAlly
463ac0ad22df7dd79456c58ab8da4d378427983c
[ "MIT" ]
2
2021-02-28T22:02:38.000Z
2021-12-20T19:00:25.000Z
ally/Order/tests/PricingConstruction.py
jpwatt/PyAlly
463ac0ad22df7dd79456c58ab8da4d378427983c
[ "MIT" ]
null
null
null
ally/Order/tests/PricingConstruction.py
jpwatt/PyAlly
463ac0ad22df7dd79456c58ab8da4d378427983c
[ "MIT" ]
null
null
null
# MIT License # # Copyright (c) 2020 Brett Graves # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import xml.etree.ElementTree as ET import unittest from ..classes import * from .classes import * from ..order import Order class TestPricingConstruction(unittest.TestCase): def test_market_construction(self): p = Market() self.assertEqual( p.attributes, {'Typ':'1'}, "Should have type 1" ) def test_limit_construction(self): p = Limit(limpx=10.51) self.assertEqual( p.attributes, {'Typ':'2', 'Px':'10.51'}, "Should have type 2, with Px included" ) p = Limit(limpx=10.51141) self.assertEqual( p.attributes, {'Typ':'2', 'Px':'10.51'}, "Should have type 2, with Px included" ) def test_stop_construction(self): p = Stop(stoppx=10.51) self.assertEqual( p.attributes, { 'Typ':"3", 'StopPx':"10.51"}, "Should have typ 3, with StopPx included" ) p = Stop(stoppx=10.5112312) self.assertEqual( p.attributes, { 'Typ':"3", 'StopPx':"10.51"}, "Should have typ 3, with StopPx included" ) def test_stoplimit_construction(self): p = StopLimit(limpx = 10.1, stoppx = 10.51) self.assertEqual( p.attributes, { 'Typ':"4", 'Px': '10.1', 'StopPx':"10.51" }, "Should have typ 3, with StopPx included" ) def test_trailingstop_construction(self): p = TrailingStop( use_pct = True, offset = 1.12 ) self.assertEqual( p.attributes, { 'Typ':"P"}, "Should have typ P" ) self.assertEqual( p.fixml, { 'PegInstr': { 'OfstTyp': 1, 'PegPxTyp': 1, 'OfstVal': 1.12 } }, "Should include tag with peginstr" ) p = TrailingStop( use_pct = False, offset = 5.69 ) self.assertEqual( p.attributes, { 'Typ':"P"}, "Should have typ P" ) self.assertEqual( p.fixml, { 'PegInstr': { 'OfstTyp': 0, 'PegPxTyp': 1, 'OfstVal': 5.69 } }, "Should include tag with peginstr" )
23.385827
80
0.66835
import xml.etree.ElementTree as ET import unittest from ..classes import * from .classes import * from ..order import Order class TestPricingConstruction(unittest.TestCase): def test_market_construction(self): p = Market() self.assertEqual( p.attributes, {'Typ':'1'}, "Should have type 1" ) def test_limit_construction(self): p = Limit(limpx=10.51) self.assertEqual( p.attributes, {'Typ':'2', 'Px':'10.51'}, "Should have type 2, with Px included" ) p = Limit(limpx=10.51141) self.assertEqual( p.attributes, {'Typ':'2', 'Px':'10.51'}, "Should have type 2, with Px included" ) def test_stop_construction(self): p = Stop(stoppx=10.51) self.assertEqual( p.attributes, { 'Typ':"3", 'StopPx':"10.51"}, "Should have typ 3, with StopPx included" ) p = Stop(stoppx=10.5112312) self.assertEqual( p.attributes, { 'Typ':"3", 'StopPx':"10.51"}, "Should have typ 3, with StopPx included" ) def test_stoplimit_construction(self): p = StopLimit(limpx = 10.1, stoppx = 10.51) self.assertEqual( p.attributes, { 'Typ':"4", 'Px': '10.1', 'StopPx':"10.51" }, "Should have typ 3, with StopPx included" ) def test_trailingstop_construction(self): p = TrailingStop( use_pct = True, offset = 1.12 ) self.assertEqual( p.attributes, { 'Typ':"P"}, "Should have typ P" ) self.assertEqual( p.fixml, { 'PegInstr': { 'OfstTyp': 1, 'PegPxTyp': 1, 'OfstVal': 1.12 } }, "Should include tag with peginstr" ) p = TrailingStop( use_pct = False, offset = 5.69 ) self.assertEqual( p.attributes, { 'Typ':"P"}, "Should have typ P" ) self.assertEqual( p.fixml, { 'PegInstr': { 'OfstTyp': 0, 'PegPxTyp': 1, 'OfstVal': 5.69 } }, "Should include tag with peginstr" )
true
true
f72598b7fb1cec8183f6a3b3b326c48b968194b9
2,843
py
Python
starvine/bvcopula/tests/test_freeze_params.py
wgurecky/StarVine
b952a88eeaff476484ba6a26420cfe4ef575d162
[ "BSD-3-Clause" ]
12
2018-10-04T06:15:13.000Z
2020-01-08T03:32:30.000Z
starvine/bvcopula/tests/test_freeze_params.py
wgurecky/StarVine
b952a88eeaff476484ba6a26420cfe4ef575d162
[ "BSD-3-Clause" ]
25
2017-08-29T06:28:37.000Z
2020-10-16T23:56:57.000Z
starvine/bvcopula/tests/test_freeze_params.py
wgurecky/StarVine
b952a88eeaff476484ba6a26420cfe4ef575d162
[ "BSD-3-Clause" ]
3
2017-04-08T20:19:09.000Z
2020-01-09T20:01:02.000Z
## # \brief Test ability to determine best fit copula via AIC from __future__ import print_function, division from starvine.bvcopula.pc_base import PairCopula import unittest import numpy as np import os pwd_ = os.getcwd() dataDir = pwd_ + "/tests/data/" np.random.seed(123) class TestGaussFrozen(unittest.TestCase): @classmethod def setUpClass(self): np.random.seed(123) def testGaussFrozen(self): # Load matlab data set stocks = np.loadtxt(dataDir + 'stocks.csv', delimiter=',') x = stocks[:, 0] y = stocks[:, 1] stockModel = PairCopula(x, y) # Try to fit all copula stockModel.copulaTournament(verbosity=0) # Ensure that the gaussian copula was chosen as the best fit self.assertTrue(stockModel.copulaModel.name == "gauss") self.assertTrue(stockModel.copulaParams[0] == "gauss") # Check gaussian copula parameters for correctness self.assertAlmostEqual(stockModel.copulaParams[1][0], 0.73874003, 4) # Eval the frozen model frzU, frzV = stockModel.copulaModel.sample(40000) # Eval a model with specified params setU, setV = stockModel.copulaModel.sample(40000, (0.73874003,)) # Ensure both frozen model and specified param model produce same result frzModel = PairCopula(frzU, frzV) setModel = PairCopula(setU, setV) frzKtau, fp = frzModel.empKTau() setKtau, sp = setModel.empKTau() self.assertAlmostEqual(frzKtau, setKtau, delta=0.02) self.assertAlmostEqual(fp, sp, delta=0.02) # Eval a model with different specified params setU2, setV2 = stockModel.copulaModel.sample(20000, (0.3,)) setModel2 = PairCopula(setU2, setV2) setKtau2, sp2 = setModel2.empKTau() self.assertTrue(setKtau2 != setKtau) self.assertTrue(abs(setKtau2 - setKtau) > 0.2) def testFrankFrozen(self): np.random.seed(123) # Load matlab data set stocks = np.loadtxt(dataDir + 'stocks.csv', delimiter=',') x = stocks[:, 0] y = stocks[:, 1] stockModel = PairCopula(x, y, family={'frank': 0, }) # Try to fit all copula stockModel.copulaTournament(verbosity=0) # Eval the frozen model frzU, frzV = stockModel.copulaModel.sample(40000) # Eval a model with specified params setU, setV = stockModel.copulaModel.sample(40000, *stockModel.copulaParams[1]) # Ensure both frozen model and specified param model produce same result frzModel = PairCopula(frzU, frzV) setModel = PairCopula(setU, setV) frzKtau, fp = frzModel.empKTau() setKtau, sp = setModel.empKTau() self.assertAlmostEqual(frzKtau, setKtau, delta=0.02) self.assertAlmostEqual(fp, sp, delta=0.02)
35.098765
86
0.651425
from __future__ import print_function, division from starvine.bvcopula.pc_base import PairCopula import unittest import numpy as np import os pwd_ = os.getcwd() dataDir = pwd_ + "/tests/data/" np.random.seed(123) class TestGaussFrozen(unittest.TestCase): @classmethod def setUpClass(self): np.random.seed(123) def testGaussFrozen(self): stocks = np.loadtxt(dataDir + 'stocks.csv', delimiter=',') x = stocks[:, 0] y = stocks[:, 1] stockModel = PairCopula(x, y) stockModel.copulaTournament(verbosity=0) self.assertTrue(stockModel.copulaModel.name == "gauss") self.assertTrue(stockModel.copulaParams[0] == "gauss") self.assertAlmostEqual(stockModel.copulaParams[1][0], 0.73874003, 4) frzU, frzV = stockModel.copulaModel.sample(40000) setU, setV = stockModel.copulaModel.sample(40000, (0.73874003,)) frzModel = PairCopula(frzU, frzV) setModel = PairCopula(setU, setV) frzKtau, fp = frzModel.empKTau() setKtau, sp = setModel.empKTau() self.assertAlmostEqual(frzKtau, setKtau, delta=0.02) self.assertAlmostEqual(fp, sp, delta=0.02) setU2, setV2 = stockModel.copulaModel.sample(20000, (0.3,)) setModel2 = PairCopula(setU2, setV2) setKtau2, sp2 = setModel2.empKTau() self.assertTrue(setKtau2 != setKtau) self.assertTrue(abs(setKtau2 - setKtau) > 0.2) def testFrankFrozen(self): np.random.seed(123) stocks = np.loadtxt(dataDir + 'stocks.csv', delimiter=',') x = stocks[:, 0] y = stocks[:, 1] stockModel = PairCopula(x, y, family={'frank': 0, }) stockModel.copulaTournament(verbosity=0) frzU, frzV = stockModel.copulaModel.sample(40000) setU, setV = stockModel.copulaModel.sample(40000, *stockModel.copulaParams[1]) frzModel = PairCopula(frzU, frzV) setModel = PairCopula(setU, setV) frzKtau, fp = frzModel.empKTau() setKtau, sp = setModel.empKTau() self.assertAlmostEqual(frzKtau, setKtau, delta=0.02) self.assertAlmostEqual(fp, sp, delta=0.02)
true
true
f7259984a8976fd2deb189a6e90d3aaeabfca3d9
1,402
py
Python
source/appModules/totalcmd.py
oleguldberg/nvda
05f55ff146ef8ba481a2de4f1bcf187200474cea
[ "bzip2-1.0.6" ]
1,592
2015-11-10T12:05:44.000Z
2022-03-31T11:50:40.000Z
source/appModules/totalcmd.py
oleguldberg/nvda
05f55ff146ef8ba481a2de4f1bcf187200474cea
[ "bzip2-1.0.6" ]
9,479
2015-11-10T20:56:48.000Z
2022-03-31T23:51:30.000Z
source/appModules/totalcmd.py
oleguldberg/nvda
05f55ff146ef8ba481a2de4f1bcf187200474cea
[ "bzip2-1.0.6" ]
682
2015-11-10T11:19:23.000Z
2022-03-31T07:51:29.000Z
#appModules/totalcmd.py #A part of NonVisual Desktop Access (NVDA) #Copyright (C) 2006-2012 NVDA Contributors #This file is covered by the GNU General Public License. #See the file COPYING for more details. import appModuleHandler from NVDAObjects.IAccessible import IAccessible import speech import controlTypes import ui oldActivePannel=0 class AppModule(appModuleHandler.AppModule): def chooseNVDAObjectOverlayClasses(self, obj, clsList): if obj.windowClassName in ("TMyListBox", "TMyListBox.UnicodeClass"): clsList.insert(0, TCList) class TCList(IAccessible): def event_gainFocus(self): global oldActivePannel if oldActivePannel !=self.windowControlID: oldActivePannel=self.windowControlID obj=self while obj and obj.parent and obj.parent.windowClassName!="TTOTAL_CMD": obj=obj.parent counter=0 while obj and obj.previous and obj.windowClassName!="TPanel": obj=obj.previous if obj.windowClassName!="TDrivePanel": counter+=1 if counter==2: ui.message(_("left")) else: ui.message(_("right")) super(TCList,self).event_gainFocus() def reportFocus(self): if self.name: speakList=[] if controlTypes.State.SELECTED in self.states: speakList.append(controlTypes.State.SELECTED.displayString) speakList.append(self.name.split("\\")[-1]) speech.speakMessage(" ".join(speakList)) else: super(TCList,self).reportFocus()
28.04
73
0.752496
import appModuleHandler from NVDAObjects.IAccessible import IAccessible import speech import controlTypes import ui oldActivePannel=0 class AppModule(appModuleHandler.AppModule): def chooseNVDAObjectOverlayClasses(self, obj, clsList): if obj.windowClassName in ("TMyListBox", "TMyListBox.UnicodeClass"): clsList.insert(0, TCList) class TCList(IAccessible): def event_gainFocus(self): global oldActivePannel if oldActivePannel !=self.windowControlID: oldActivePannel=self.windowControlID obj=self while obj and obj.parent and obj.parent.windowClassName!="TTOTAL_CMD": obj=obj.parent counter=0 while obj and obj.previous and obj.windowClassName!="TPanel": obj=obj.previous if obj.windowClassName!="TDrivePanel": counter+=1 if counter==2: ui.message(_("left")) else: ui.message(_("right")) super(TCList,self).event_gainFocus() def reportFocus(self): if self.name: speakList=[] if controlTypes.State.SELECTED in self.states: speakList.append(controlTypes.State.SELECTED.displayString) speakList.append(self.name.split("\\")[-1]) speech.speakMessage(" ".join(speakList)) else: super(TCList,self).reportFocus()
true
true
f7259a6ab0d551d886b30961db6d5aff508bdecb
772
py
Python
scripts/plotting/reprocessed_kccg_samples_pca/main.py
populationgenomics/ancestry
faf6fd4bc3a1f8b2a2adb7e59cf584d4bfdf79e6
[ "MIT" ]
null
null
null
scripts/plotting/reprocessed_kccg_samples_pca/main.py
populationgenomics/ancestry
faf6fd4bc3a1f8b2a2adb7e59cf584d4bfdf79e6
[ "MIT" ]
21
2021-03-09T06:35:59.000Z
2022-02-21T22:56:15.000Z
scripts/plotting/reprocessed_kccg_samples_pca/main.py
populationgenomics/ancestry
faf6fd4bc3a1f8b2a2adb7e59cf584d4bfdf79e6
[ "MIT" ]
null
null
null
"""Entry point for the analysis runner.""" import os import sys import hail as hl import hailtop.batch as hb from analysis_runner import dataproc OUTPUT = os.getenv('OUTPUT') assert OUTPUT hl.init(default_reference='GRCh38') POP = sys.argv[1] if len(sys.argv) > 1 else 'nfe' service_backend = hb.ServiceBackend( billing_project=os.getenv('HAIL_BILLING_PROJECT'), bucket=os.getenv('HAIL_BUCKET') ) batch = hb.Batch(name=f'{POP} kccg-reprocessed', backend=service_backend) dataproc.hail_dataproc_job( batch, f'project_reprocessed_kccg_samples.py --output={OUTPUT} --pop {POP}', max_age='5h', packages=['click', 'selenium'], init=['gs://cpg-reference/hail_dataproc/install_phantomjs.sh'], job_name=f'{POP}-kccg-reprocessed', ) batch.run()
24.125
86
0.727979
import os import sys import hail as hl import hailtop.batch as hb from analysis_runner import dataproc OUTPUT = os.getenv('OUTPUT') assert OUTPUT hl.init(default_reference='GRCh38') POP = sys.argv[1] if len(sys.argv) > 1 else 'nfe' service_backend = hb.ServiceBackend( billing_project=os.getenv('HAIL_BILLING_PROJECT'), bucket=os.getenv('HAIL_BUCKET') ) batch = hb.Batch(name=f'{POP} kccg-reprocessed', backend=service_backend) dataproc.hail_dataproc_job( batch, f'project_reprocessed_kccg_samples.py --output={OUTPUT} --pop {POP}', max_age='5h', packages=['click', 'selenium'], init=['gs://cpg-reference/hail_dataproc/install_phantomjs.sh'], job_name=f'{POP}-kccg-reprocessed', ) batch.run()
true
true
f7259b305c1ad5cae4a9beae16737854d8e966c3
7,804
py
Python
botstory/ast/story_context/__init__.py
botstory/bot-story
9c5b2fc7f7a14dbd467d70f60d5ba855ef89dac3
[ "MIT" ]
5
2017-01-14T13:42:13.000Z
2021-07-27T21:52:04.000Z
botstory/ast/story_context/__init__.py
botstory/bot-story
9c5b2fc7f7a14dbd467d70f60d5ba855ef89dac3
[ "MIT" ]
235
2016-11-07T23:33:28.000Z
2018-03-13T11:27:33.000Z
botstory/ast/story_context/__init__.py
hyzhak/bot-story
9c5b2fc7f7a14dbd467d70f60d5ba855ef89dac3
[ "MIT" ]
5
2017-01-14T13:42:14.000Z
2020-11-06T08:33:20.000Z
from botstory import matchers, utils from botstory.ast import callable, forking, loop from botstory.ast.story_context import reducers from botstory.utils import advanced_json_encoder import numbers import logging import uuid logger = logging.getLogger(__name__) class MissedStoryPart(Exception): pass class StoryContext: def __init__(self, message, library, matched=False, waiting_for=None, parent_uid=None): self.uid = str(uuid.uuid4()) self.parent_uid = parent_uid self.library = library # whether message was passed validation and was matched one story self.matched = matched self.message = message self.waiting_for = waiting_for def clone(self): return StoryContext(library=self.library, matched=self.matched, message=self.message, parent_uid=self.uid, waiting_for=self.waiting_for, ) def compiled_story(self): if self.is_empty_stack(): return self.library.get_global_story(self.message) else: return self.library.get_story_by_topic(self.stack_tail()['topic'], stack=self.stack()[:-1]) def could_scope_out(self): """ could bubble up from current scope :return: """ return not self.waiting_for or \ isinstance(self.waiting_for, callable.EndOfStory) or \ self.is_breaking_a_loop() def current_step(self): return self.stack_tail()['step'] def does_it_match_any_story(self): return self.compiled_story() is not None and not self.matched def get_child_story(self): logger.debug('# get_child_story') """ try child story that match message and get scope of it :return: """ story_loop = self.compiled_story() if hasattr(story_loop, 'children_matcher') and not self.matched: return self.get_story_scope_child(story_loop) story_part = self.get_current_story_part() if not hasattr(story_part, 'get_child_by_validation_result'): logger.debug('# does not have get_child_by_validation_result') return None if isinstance(self.waiting_for, forking.SwitchOnValue): logger.debug('# switch on value') return story_part.get_child_by_validation_result(self.waiting_for.value) # for some base classes we could try validate result direct child_story = story_part.get_child_by_validation_result(self.waiting_for) if child_story: logger.debug('# child_story') logger.debug(child_story) return child_story stack_tail = self.stack_tail() if stack_tail['data'] is not None and not self.matched: validator = matchers.deserialize(stack_tail['data']) logger.debug('# validator') logger.debug(validator) logger.debug('# self.message') logger.debug(self.message) validation_result = validator.validate(self.message) logger.debug('# validation_result') logger.debug(validation_result) res = story_part.get_child_by_validation_result(validation_result) logger.debug('# res') logger.debug(res) # or we validate message # but can't find right child story # maybe we should use independent validators for each story here if res is None: return self.get_story_scope_child(story_part) else: return res return None def get_story_scope_child(self, story_part): logger.debug('# get_story_scope_child') validator = story_part.children_matcher() logger.debug('# validator') logger.debug(validator) logger.debug('# self.message') logger.debug(self.message) topic = validator.validate(self.message) # if topic == None: # we inside story loop scope # but got message that doesn't match # any local stories logger.debug('# topic {}'.format(topic)) return story_part.by_topic(topic) def get_current_story_part(self): compiled_story = self.compiled_story() if not compiled_story: return None try: return compiled_story.story_line[self.current_step()] except IndexError: return None def get_user_data(self): return get_user_data(self.message) def has_child_story(self): return self.get_child_story() is not None def is_breaking_a_loop(self): return isinstance(self.waiting_for, loop.BreakLoop) def is_empty_stack(self): return len(self.stack()) == 0 def is_end_of_story(self): compiled_story = self.compiled_story() if not compiled_story: return True return self.current_step() >= len(compiled_story.story_line) def is_scope_level(self): return isinstance(self.compiled_story(), loop.StoriesLoopNode) def is_scope_level_part(self): return isinstance(self.get_current_story_part(), loop.StoriesLoopNode) def is_tail_of_story(self): compiled_story = self.compiled_story() if not compiled_story: return True return self.current_step() >= len(compiled_story.story_line) - 1 def is_waiting_for_input(self): """ could make one step further :return: """ return self.waiting_for and \ not isinstance(self.waiting_for, forking.SwitchOnValue) and \ not is_base_type(self.waiting_for) def stack(self): return self.message['session']['stack'] def stack_tail(self): stack = self.stack() if len(stack) == 0: raise MissedStoryPart() return stack[-1] def to_json(self): return { 'uid': self.uid, 'parent_uid': self.parent_uid, 'matched': self.matched, 'message': self.message, 'waiting_for': str(self.waiting_for), } def user(self): return self.message['user'] def __repr__(self): try: return advanced_json_encoder.AdvancedJSONEncoder().encode(self.to_json()) except Exception as err: logger.warn(err) logger.warn('fail to dump json of message {} ' 'waiting for {}'.format(str(self.message), str(self.waiting_for))) def is_base_type(value): return isinstance(value, str) or isinstance(value, numbers.Number) def clean_message_data(ctx): return utils.safe_set(ctx, 'session', 'data', 'message', {}) def get_user_data(ctx): return ctx['session']['data'] def get_message_data(ctx, *args, **kwargs): return utils.safe_get(get_user_data(ctx)['message'], *args, **kwargs) def get_message_attachment(ctx, attachment_type): logger.debug('# get_message_data(ctx)') logger.debug(get_message_data(ctx)) attachment_list = get_message_data(ctx, 'attachments') if attachment_list is None or len(attachment_list) == 0: return None attachment_list_of_type = [a for a in attachment_list if a['type'] == attachment_type] if attachment_list_of_type is None or len(attachment_list_of_type) == 0: return None return attachment_list_of_type[0] def set_user_data(ctx, data): ctx['session']['data'] = { **get_user_data(ctx), **data, } return ctx def set_message_data(ctx, *args): return utils.safe_set(ctx, 'session', 'data', 'message', *args) __all__ = [get_user_data, reducers, set_user_data, StoryContext]
32.381743
103
0.631471
from botstory import matchers, utils from botstory.ast import callable, forking, loop from botstory.ast.story_context import reducers from botstory.utils import advanced_json_encoder import numbers import logging import uuid logger = logging.getLogger(__name__) class MissedStoryPart(Exception): pass class StoryContext: def __init__(self, message, library, matched=False, waiting_for=None, parent_uid=None): self.uid = str(uuid.uuid4()) self.parent_uid = parent_uid self.library = library self.matched = matched self.message = message self.waiting_for = waiting_for def clone(self): return StoryContext(library=self.library, matched=self.matched, message=self.message, parent_uid=self.uid, waiting_for=self.waiting_for, ) def compiled_story(self): if self.is_empty_stack(): return self.library.get_global_story(self.message) else: return self.library.get_story_by_topic(self.stack_tail()['topic'], stack=self.stack()[:-1]) def could_scope_out(self): return not self.waiting_for or \ isinstance(self.waiting_for, callable.EndOfStory) or \ self.is_breaking_a_loop() def current_step(self): return self.stack_tail()['step'] def does_it_match_any_story(self): return self.compiled_story() is not None and not self.matched def get_child_story(self): logger.debug('# get_child_story') story_loop = self.compiled_story() if hasattr(story_loop, 'children_matcher') and not self.matched: return self.get_story_scope_child(story_loop) story_part = self.get_current_story_part() if not hasattr(story_part, 'get_child_by_validation_result'): logger.debug('# does not have get_child_by_validation_result') return None if isinstance(self.waiting_for, forking.SwitchOnValue): logger.debug('# switch on value') return story_part.get_child_by_validation_result(self.waiting_for.value) child_story = story_part.get_child_by_validation_result(self.waiting_for) if child_story: logger.debug('# child_story') logger.debug(child_story) return child_story stack_tail = self.stack_tail() if stack_tail['data'] is not None and not self.matched: validator = matchers.deserialize(stack_tail['data']) logger.debug('# validator') logger.debug(validator) logger.debug('# self.message') logger.debug(self.message) validation_result = validator.validate(self.message) logger.debug('# validation_result') logger.debug(validation_result) res = story_part.get_child_by_validation_result(validation_result) logger.debug('# res') logger.debug(res) # maybe we should use independent validators for each story here if res is None: return self.get_story_scope_child(story_part) else: return res return None def get_story_scope_child(self, story_part): logger.debug(' validator = story_part.children_matcher() logger.debug(' logger.debug(validator) logger.debug(' logger.debug(self.message) topic = validator.validate(self.message) # if topic == None: # we inside story loop scope # but got message that doesn't match logger.debug('# topic {}'.format(topic)) return story_part.by_topic(topic) def get_current_story_part(self): compiled_story = self.compiled_story() if not compiled_story: return None try: return compiled_story.story_line[self.current_step()] except IndexError: return None def get_user_data(self): return get_user_data(self.message) def has_child_story(self): return self.get_child_story() is not None def is_breaking_a_loop(self): return isinstance(self.waiting_for, loop.BreakLoop) def is_empty_stack(self): return len(self.stack()) == 0 def is_end_of_story(self): compiled_story = self.compiled_story() if not compiled_story: return True return self.current_step() >= len(compiled_story.story_line) def is_scope_level(self): return isinstance(self.compiled_story(), loop.StoriesLoopNode) def is_scope_level_part(self): return isinstance(self.get_current_story_part(), loop.StoriesLoopNode) def is_tail_of_story(self): compiled_story = self.compiled_story() if not compiled_story: return True return self.current_step() >= len(compiled_story.story_line) - 1 def is_waiting_for_input(self): return self.waiting_for and \ not isinstance(self.waiting_for, forking.SwitchOnValue) and \ not is_base_type(self.waiting_for) def stack(self): return self.message['session']['stack'] def stack_tail(self): stack = self.stack() if len(stack) == 0: raise MissedStoryPart() return stack[-1] def to_json(self): return { 'uid': self.uid, 'parent_uid': self.parent_uid, 'matched': self.matched, 'message': self.message, 'waiting_for': str(self.waiting_for), } def user(self): return self.message['user'] def __repr__(self): try: return advanced_json_encoder.AdvancedJSONEncoder().encode(self.to_json()) except Exception as err: logger.warn(err) logger.warn('fail to dump json of message {} ' 'waiting for {}'.format(str(self.message), str(self.waiting_for))) def is_base_type(value): return isinstance(value, str) or isinstance(value, numbers.Number) def clean_message_data(ctx): return utils.safe_set(ctx, 'session', 'data', 'message', {}) def get_user_data(ctx): return ctx['session']['data'] def get_message_data(ctx, *args, **kwargs): return utils.safe_get(get_user_data(ctx)['message'], *args, **kwargs) def get_message_attachment(ctx, attachment_type): logger.debug('# get_message_data(ctx)') logger.debug(get_message_data(ctx)) attachment_list = get_message_data(ctx, 'attachments') if attachment_list is None or len(attachment_list) == 0: return None attachment_list_of_type = [a for a in attachment_list if a['type'] == attachment_type] if attachment_list_of_type is None or len(attachment_list_of_type) == 0: return None return attachment_list_of_type[0] def set_user_data(ctx, data): ctx['session']['data'] = { **get_user_data(ctx), **data, } return ctx def set_message_data(ctx, *args): return utils.safe_set(ctx, 'session', 'data', 'message', *args) __all__ = [get_user_data, reducers, set_user_data, StoryContext]
true
true
f7259b4e1f74cc2b78fa2fe6a806234b94c86cc1
6,467
py
Python
scd_manager.py
gavinlive/scd-data-manager
570b67bacb4bf17f0b49c5875933f233ddd76e6c
[ "MIT" ]
null
null
null
scd_manager.py
gavinlive/scd-data-manager
570b67bacb4bf17f0b49c5875933f233ddd76e6c
[ "MIT" ]
1
2020-06-09T08:48:01.000Z
2020-06-09T09:23:07.000Z
scd_manager.py
gavinlive/scd-data-manager
570b67bacb4bf17f0b49c5875933f233ddd76e6c
[ "MIT" ]
null
null
null
import os, sys import pydicom as pyd import matplotlib.pyplot as plt import collections import pandas as pd PatientRecord = collections.namedtuple('PatientRecord', ['patient_id', 'image_folder', 'original_id', 'gender', 'age', 'pathology', 'all_scans', 'scans', 'scans_list', 'scans_total']) PatientScans = collections.namedtuple('PatientScans', ['files', 'prefixes', 'suffixes', 'total_number']) DataRecord = collections.namedtuple('DataRecord', ['dicom_path', 'contour_path']) class DataManager(object): def __config__(self): self.path = '.' self.patient_info_path = self.path + '/scd_patientdata.csv' self.meta_data_path = self.path + '/scd_patientdata.csv' self.images_path = self.path + '/SCD_DeidentifiedImages/' self.segmentations_path = self.path + '/SCD_ManualContours/' def __init__(self): self.__config__() self.__load_patient_info() self._patients = next(os.walk(self.images_path))[1] print(self._patients) self.__get_patient_images() if(self.__verify_scan_sets()==True): print("verified all scan sets") if(self.__verify_scan_numbers()==True): print("verified all scan numbers") def __import_contours(self, patient, suffixes, files): path = self.segmentations_path + patient + '/contours-manual/IRCCI-expert/' records_list=[] numbers_list = [] for file in os.listdir(path): if file.endswith(".txt"): f=file.split("-") scan_number = int(f[2]) f=f[3] if((f=="icontour") and (scan_number in suffixes)): contour_filepath = path +'/' + file indx = suffixes.index(scan_number) dicom_filepath = files[indx] records_list.append(DataRecord(dicom_filepath, contour_filepath)) numbers_list.append(scan_number) return records_list,numbers_list,len(records_list) def __load_patient_info(self): self.patient_info = pd.read_csv(self.patient_info_path) def __get_patient_info(self, patient): this = self.patient_info[self.patient_info['OriginalID']==patient].values.tolist()[0] print(this) cols = self.patient_info.columns.values.tolist() toget = ['Gender', 'Age', 'PathologyID', 'Pathology'] toreturn=[] for t in toget: indx = cols.index(t) toreturn.append(this[indx]) return toreturn def depre__import_contours(self): for patient in self._patients: path = self.segmentations_path + patient + '/contours-manual/IRCCI-expert/' records_list=[] numbers_list = [] for file in os.listdir(path): if file.endswith(".txt"): f=file.split("-") scan_number = f[2] f=f[3] if((f=="icontour") and (scan_number in self.patient[patient].all_scans.suffixes)): contour_filepath = path +'/' + file indx = self.patient[patient].all_scans.suffixes.indx(scan_number) dicom_filepath = self.patient[patient].all_scans.files[indx] records_list.append(DataRecord(dicom_filepath, contour_filepath)) numbers_list.append(scan_number) self.patient[patient].scans=records_list self.patient[patient].scans_list=numbers_list self.patient[patient].scans_total = len(records_list) def __verify_scan_sets(self): for patient in self._patients: prefix_list = self.patient[patient].all_scans.prefixes b = [(x==1) for x in prefix_list] if False in b: print('Fault for patient: %s' % patient) return False return True def __verify_scan_numbers(self): for patient in self._patients: prefix_list = self.patient[patient].all_scans.suffixes b = [(prefix_list.count(x)==1) for x in prefix_list] if False in b: print('Fault for patient: %s' % patient) return False return True def __get_patient_images(self): self.patient = {} for patient in self._patients: #list_of_image_folders_for_patient = next(os.walk(self.images_path + patient))[1] #list_of_image_folders_for_patient_full_path = [self.images_path + patient + '/' + x for x in list_of_image_folders_for_patient] #self.patient[patient] = {"patient_id": patient, "images": list_of_image_folders_for_patient, "original_id": "", #"gender": "", "age": 0, "pathology": "" } def get_files(list_of_folders): file_list = [] for folder in list_of_folders: for file in os.listdir(folder): if file.endswith(".dcm"): file_list.append(folder +'/' + file) return file_list def get_prefix_suffix(files): prefixes = [] suffixes = [] for file in files: f=file.split("-") f=f[-2::] f[1] = f[1].split(".")[0] prefixes.append(int(f[0])) suffixes.append(int(f[1])) return prefixes, suffixes files = get_files([self.images_path+patient+'/DICOM']) prefixes, suffixes = get_prefix_suffix(files) this_patient_scan_set = PatientScans(files, prefixes, suffixes, len(files)) scans, scans_list, scans_total = self.__import_contours(patient, suffixes, files) gender, age, pathologyID, _ = self.__get_patient_info(patient) this_patient_record = PatientRecord(patient_id=patient, image_folder=self.images_path + patient, original_id="", gender=gender, age=age, pathology=pathologyID, all_scans=this_patient_scan_set, scans=scans, scans_list=scans_list, scans_total=scans_total) self.patient[patient] = this_patient_record def total_examples(self): count=0 for patient in self._patients: count += self.patient[patient].scans_total return count def __call__(self, patient,scan_number): return self.patient[patient].all_scans.files[scan_number]
44.6
183
0.598113
import os, sys import pydicom as pyd import matplotlib.pyplot as plt import collections import pandas as pd PatientRecord = collections.namedtuple('PatientRecord', ['patient_id', 'image_folder', 'original_id', 'gender', 'age', 'pathology', 'all_scans', 'scans', 'scans_list', 'scans_total']) PatientScans = collections.namedtuple('PatientScans', ['files', 'prefixes', 'suffixes', 'total_number']) DataRecord = collections.namedtuple('DataRecord', ['dicom_path', 'contour_path']) class DataManager(object): def __config__(self): self.path = '.' self.patient_info_path = self.path + '/scd_patientdata.csv' self.meta_data_path = self.path + '/scd_patientdata.csv' self.images_path = self.path + '/SCD_DeidentifiedImages/' self.segmentations_path = self.path + '/SCD_ManualContours/' def __init__(self): self.__config__() self.__load_patient_info() self._patients = next(os.walk(self.images_path))[1] print(self._patients) self.__get_patient_images() if(self.__verify_scan_sets()==True): print("verified all scan sets") if(self.__verify_scan_numbers()==True): print("verified all scan numbers") def __import_contours(self, patient, suffixes, files): path = self.segmentations_path + patient + '/contours-manual/IRCCI-expert/' records_list=[] numbers_list = [] for file in os.listdir(path): if file.endswith(".txt"): f=file.split("-") scan_number = int(f[2]) f=f[3] if((f=="icontour") and (scan_number in suffixes)): contour_filepath = path +'/' + file indx = suffixes.index(scan_number) dicom_filepath = files[indx] records_list.append(DataRecord(dicom_filepath, contour_filepath)) numbers_list.append(scan_number) return records_list,numbers_list,len(records_list) def __load_patient_info(self): self.patient_info = pd.read_csv(self.patient_info_path) def __get_patient_info(self, patient): this = self.patient_info[self.patient_info['OriginalID']==patient].values.tolist()[0] print(this) cols = self.patient_info.columns.values.tolist() toget = ['Gender', 'Age', 'PathologyID', 'Pathology'] toreturn=[] for t in toget: indx = cols.index(t) toreturn.append(this[indx]) return toreturn def depre__import_contours(self): for patient in self._patients: path = self.segmentations_path + patient + '/contours-manual/IRCCI-expert/' records_list=[] numbers_list = [] for file in os.listdir(path): if file.endswith(".txt"): f=file.split("-") scan_number = f[2] f=f[3] if((f=="icontour") and (scan_number in self.patient[patient].all_scans.suffixes)): contour_filepath = path +'/' + file indx = self.patient[patient].all_scans.suffixes.indx(scan_number) dicom_filepath = self.patient[patient].all_scans.files[indx] records_list.append(DataRecord(dicom_filepath, contour_filepath)) numbers_list.append(scan_number) self.patient[patient].scans=records_list self.patient[patient].scans_list=numbers_list self.patient[patient].scans_total = len(records_list) def __verify_scan_sets(self): for patient in self._patients: prefix_list = self.patient[patient].all_scans.prefixes b = [(x==1) for x in prefix_list] if False in b: print('Fault for patient: %s' % patient) return False return True def __verify_scan_numbers(self): for patient in self._patients: prefix_list = self.patient[patient].all_scans.suffixes b = [(prefix_list.count(x)==1) for x in prefix_list] if False in b: print('Fault for patient: %s' % patient) return False return True def __get_patient_images(self): self.patient = {} for patient in self._patients: def get_files(list_of_folders): file_list = [] for folder in list_of_folders: for file in os.listdir(folder): if file.endswith(".dcm"): file_list.append(folder +'/' + file) return file_list def get_prefix_suffix(files): prefixes = [] suffixes = [] for file in files: f=file.split("-") f=f[-2::] f[1] = f[1].split(".")[0] prefixes.append(int(f[0])) suffixes.append(int(f[1])) return prefixes, suffixes files = get_files([self.images_path+patient+'/DICOM']) prefixes, suffixes = get_prefix_suffix(files) this_patient_scan_set = PatientScans(files, prefixes, suffixes, len(files)) scans, scans_list, scans_total = self.__import_contours(patient, suffixes, files) gender, age, pathologyID, _ = self.__get_patient_info(patient) this_patient_record = PatientRecord(patient_id=patient, image_folder=self.images_path + patient, original_id="", gender=gender, age=age, pathology=pathologyID, all_scans=this_patient_scan_set, scans=scans, scans_list=scans_list, scans_total=scans_total) self.patient[patient] = this_patient_record def total_examples(self): count=0 for patient in self._patients: count += self.patient[patient].scans_total return count def __call__(self, patient,scan_number): return self.patient[patient].all_scans.files[scan_number]
true
true
f7259c70b3269cebc23b86955129c52126b5c426
587
py
Python
Python1/python1Homework/input_counter1.py
ceeblet/OST_PythonCertificationTrack
042e0ce964bc88b3f4132dcbd7e06c5f504eae34
[ "MIT" ]
null
null
null
Python1/python1Homework/input_counter1.py
ceeblet/OST_PythonCertificationTrack
042e0ce964bc88b3f4132dcbd7e06c5f504eae34
[ "MIT" ]
null
null
null
Python1/python1Homework/input_counter1.py
ceeblet/OST_PythonCertificationTrack
042e0ce964bc88b3f4132dcbd7e06c5f504eae34
[ "MIT" ]
null
null
null
#!/usr/local/bin/python3 """input_counter.py""" myset = set() mydict = {} mysetlength = len(myset) while True: text = input("Enter a line (or Enter to quit): ") if not text: break for punc in ",?;.": text = text.replace(punc, "") textwords = (text.lower().split()) for word in textwords: myset.add(word) newsetlength = len(myset) if newsetlength > mysetlength: mydict[word] = newsetlength mysetlength = newsetlength for word in (mydict.keys()): print(word, mydict[word]) print("Finished")
26.681818
53
0.584327
myset = set() mydict = {} mysetlength = len(myset) while True: text = input("Enter a line (or Enter to quit): ") if not text: break for punc in ",?;.": text = text.replace(punc, "") textwords = (text.lower().split()) for word in textwords: myset.add(word) newsetlength = len(myset) if newsetlength > mysetlength: mydict[word] = newsetlength mysetlength = newsetlength for word in (mydict.keys()): print(word, mydict[word]) print("Finished")
true
true
f7259ef31d09ee215158684c34454fabb4e5926d
614
py
Python
aws-auth0-auth/helloWorld.py
skarlekar/ms-auth-tutorials
0de172817e54533be93700de19028cfa8757861f
[ "MIT" ]
null
null
null
aws-auth0-auth/helloWorld.py
skarlekar/ms-auth-tutorials
0de172817e54533be93700de19028cfa8757861f
[ "MIT" ]
1
2021-06-01T21:41:36.000Z
2021-06-01T21:41:36.000Z
aws-auth0-auth/helloWorld.py
skarlekar/ms-auth-tutorials
0de172817e54533be93700de19028cfa8757861f
[ "MIT" ]
1
2017-10-26T15:08:40.000Z
2017-10-26T15:08:40.000Z
"""Simple helloWorld service.""" import json def sayHello(event, context): """Return a message in the response body.""" print('Event is: {}'.format(json.dumps(event))) body = { "message": "Hello! Your Auth0 authorized function executed successfully!" } response = { "statusCode": 200, "body": json.dumps(body) } return response # Use this code if you don't use the http event with the LAMBDA-PROXY # integration """ return { "message": "Go Serverless v1.0! Your function executed successfully!", "event": event } """
22.740741
81
0.599349
import json def sayHello(event, context): print('Event is: {}'.format(json.dumps(event))) body = { "message": "Hello! Your Auth0 authorized function executed successfully!" } response = { "statusCode": 200, "body": json.dumps(body) } return response # integration
true
true
f7259f1cbf5a3448b4489597dc832795cc8d1b52
9,120
py
Python
fuji_server/models/data_provenance.py
vemonet/fuji
92aabcb58d76a58981c677bcf0da8e57309c6096
[ "MIT" ]
null
null
null
fuji_server/models/data_provenance.py
vemonet/fuji
92aabcb58d76a58981c677bcf0da8e57309c6096
[ "MIT" ]
null
null
null
fuji_server/models/data_provenance.py
vemonet/fuji
92aabcb58d76a58981c677bcf0da8e57309c6096
[ "MIT" ]
null
null
null
# coding: utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from fuji_server.models.base_model_ import Model from fuji_server.models.data_provenance_output import DataProvenanceOutput # noqa: F401,E501 from fuji_server.models.debug import Debug # noqa: F401,E501 from fuji_server.models.fair_result_common import FAIRResultCommon # noqa: F401,E501 from fuji_server.models.fair_result_common_score import FAIRResultCommonScore # noqa: F401,E501 from fuji_server.models.fair_result_evaluation_criterium import FAIRResultEvaluationCriterium # noqa: F401,E501 from fuji_server import util class DataProvenance(Model): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self, id: int=None, metric_identifier: str=None, metric_name: str=None, metric_tests: Dict[str, FAIRResultEvaluationCriterium]=None, test_status: str='fail', score: FAIRResultCommonScore=None, maturity: str='incomplete', output: DataProvenanceOutput=None, test_debug: Debug=None): # noqa: E501 """DataProvenance - a model defined in Swagger :param id: The id of this DataProvenance. # noqa: E501 :type id: int :param metric_identifier: The metric_identifier of this DataProvenance. # noqa: E501 :type metric_identifier: str :param metric_name: The metric_name of this DataProvenance. # noqa: E501 :type metric_name: str :param metric_tests: The metric_tests of this DataProvenance. # noqa: E501 :type metric_tests: Dict[str, FAIRResultEvaluationCriterium] :param test_status: The test_status of this DataProvenance. # noqa: E501 :type test_status: str :param score: The score of this DataProvenance. # noqa: E501 :type score: FAIRResultCommonScore :param maturity: The maturity of this DataProvenance. # noqa: E501 :type maturity: str :param output: The output of this DataProvenance. # noqa: E501 :type output: DataProvenanceOutput :param test_debug: The test_debug of this DataProvenance. # noqa: E501 :type test_debug: Debug """ self.swagger_types = { 'id': int, 'metric_identifier': str, 'metric_name': str, 'metric_tests': Dict[str, FAIRResultEvaluationCriterium], 'test_status': str, 'score': FAIRResultCommonScore, 'maturity': str, 'output': DataProvenanceOutput, 'test_debug': Debug } self.attribute_map = { 'id': 'id', 'metric_identifier': 'metric_identifier', 'metric_name': 'metric_name', 'metric_tests': 'metric_tests', 'test_status': 'test_status', 'score': 'score', 'maturity': 'maturity', 'output': 'output', 'test_debug': 'test_debug' } self._id = id self._metric_identifier = metric_identifier self._metric_name = metric_name self._metric_tests = metric_tests self._test_status = test_status self._score = score self._maturity = maturity self._output = output self._test_debug = test_debug @classmethod def from_dict(cls, dikt) -> 'DataProvenance': """Returns the dict as a model :param dikt: A dict. :type: dict :return: The DataProvenance of this DataProvenance. # noqa: E501 :rtype: DataProvenance """ return util.deserialize_model(dikt, cls) @property def id(self) -> int: """Gets the id of this DataProvenance. :return: The id of this DataProvenance. :rtype: int """ return self._id @id.setter def id(self, id: int): """Sets the id of this DataProvenance. :param id: The id of this DataProvenance. :type id: int """ if id is None: raise ValueError("Invalid value for `id`, must not be `None`") # noqa: E501 self._id = id @property def metric_identifier(self) -> str: """Gets the metric_identifier of this DataProvenance. :return: The metric_identifier of this DataProvenance. :rtype: str """ return self._metric_identifier @metric_identifier.setter def metric_identifier(self, metric_identifier: str): """Sets the metric_identifier of this DataProvenance. :param metric_identifier: The metric_identifier of this DataProvenance. :type metric_identifier: str """ if metric_identifier is None: raise ValueError("Invalid value for `metric_identifier`, must not be `None`") # noqa: E501 self._metric_identifier = metric_identifier @property def metric_name(self) -> str: """Gets the metric_name of this DataProvenance. :return: The metric_name of this DataProvenance. :rtype: str """ return self._metric_name @metric_name.setter def metric_name(self, metric_name: str): """Sets the metric_name of this DataProvenance. :param metric_name: The metric_name of this DataProvenance. :type metric_name: str """ if metric_name is None: raise ValueError("Invalid value for `metric_name`, must not be `None`") # noqa: E501 self._metric_name = metric_name @property def metric_tests(self) -> Dict[str, FAIRResultEvaluationCriterium]: """Gets the metric_tests of this DataProvenance. :return: The metric_tests of this DataProvenance. :rtype: Dict[str, FAIRResultEvaluationCriterium] """ return self._metric_tests @metric_tests.setter def metric_tests(self, metric_tests: Dict[str, FAIRResultEvaluationCriterium]): """Sets the metric_tests of this DataProvenance. :param metric_tests: The metric_tests of this DataProvenance. :type metric_tests: Dict[str, FAIRResultEvaluationCriterium] """ self._metric_tests = metric_tests @property def test_status(self) -> str: """Gets the test_status of this DataProvenance. :return: The test_status of this DataProvenance. :rtype: str """ return self._test_status @test_status.setter def test_status(self, test_status: str): """Sets the test_status of this DataProvenance. :param test_status: The test_status of this DataProvenance. :type test_status: str """ allowed_values = ["pass", "fail", "indeterminate"] # noqa: E501 if test_status not in allowed_values: raise ValueError( "Invalid value for `test_status` ({0}), must be one of {1}" .format(test_status, allowed_values) ) self._test_status = test_status @property def score(self) -> FAIRResultCommonScore: """Gets the score of this DataProvenance. :return: The score of this DataProvenance. :rtype: FAIRResultCommonScore """ return self._score @score.setter def score(self, score: FAIRResultCommonScore): """Sets the score of this DataProvenance. :param score: The score of this DataProvenance. :type score: FAIRResultCommonScore """ if score is None: raise ValueError("Invalid value for `score`, must not be `None`") # noqa: E501 self._score = score @property def maturity(self) -> str: """Gets the maturity of this DataProvenance. :return: The maturity of this DataProvenance. :rtype: str """ return self._maturity @maturity.setter def maturity(self, maturity: int): """Sets the maturity of this Uniqueness. :param maturity: The maturity of this Uniqueness. :type maturity: int """ self._maturity = maturity @property def output(self) -> DataProvenanceOutput: """Gets the output of this DataProvenance. :return: The output of this DataProvenance. :rtype: DataProvenanceOutput """ return self._output @output.setter def output(self, output: DataProvenanceOutput): """Sets the output of this DataProvenance. :param output: The output of this DataProvenance. :type output: DataProvenanceOutput """ self._output = output @property def test_debug(self) -> Debug: """Gets the test_debug of this DataProvenance. :return: The test_debug of this DataProvenance. :rtype: Debug """ return self._test_debug @test_debug.setter def test_debug(self, test_debug: Debug): """Sets the test_debug of this DataProvenance. :param test_debug: The test_debug of this DataProvenance. :type test_debug: Debug """ self._test_debug = test_debug
31.448276
311
0.639035
from __future__ import absolute_import from datetime import date, datetime from typing import List, Dict from fuji_server.models.base_model_ import Model from fuji_server.models.data_provenance_output import DataProvenanceOutput from fuji_server.models.debug import Debug from fuji_server.models.fair_result_common import FAIRResultCommon from fuji_server.models.fair_result_common_score import FAIRResultCommonScore from fuji_server.models.fair_result_evaluation_criterium import FAIRResultEvaluationCriterium from fuji_server import util class DataProvenance(Model): def __init__(self, id: int=None, metric_identifier: str=None, metric_name: str=None, metric_tests: Dict[str, FAIRResultEvaluationCriterium]=None, test_status: str='fail', score: FAIRResultCommonScore=None, maturity: str='incomplete', output: DataProvenanceOutput=None, test_debug: Debug=None): self.swagger_types = { 'id': int, 'metric_identifier': str, 'metric_name': str, 'metric_tests': Dict[str, FAIRResultEvaluationCriterium], 'test_status': str, 'score': FAIRResultCommonScore, 'maturity': str, 'output': DataProvenanceOutput, 'test_debug': Debug } self.attribute_map = { 'id': 'id', 'metric_identifier': 'metric_identifier', 'metric_name': 'metric_name', 'metric_tests': 'metric_tests', 'test_status': 'test_status', 'score': 'score', 'maturity': 'maturity', 'output': 'output', 'test_debug': 'test_debug' } self._id = id self._metric_identifier = metric_identifier self._metric_name = metric_name self._metric_tests = metric_tests self._test_status = test_status self._score = score self._maturity = maturity self._output = output self._test_debug = test_debug @classmethod def from_dict(cls, dikt) -> 'DataProvenance': return util.deserialize_model(dikt, cls) @property def id(self) -> int: return self._id @id.setter def id(self, id: int): if id is None: raise ValueError("Invalid value for `id`, must not be `None`") self._id = id @property def metric_identifier(self) -> str: return self._metric_identifier @metric_identifier.setter def metric_identifier(self, metric_identifier: str): if metric_identifier is None: raise ValueError("Invalid value for `metric_identifier`, must not be `None`") self._metric_identifier = metric_identifier @property def metric_name(self) -> str: return self._metric_name @metric_name.setter def metric_name(self, metric_name: str): if metric_name is None: raise ValueError("Invalid value for `metric_name`, must not be `None`") self._metric_name = metric_name @property def metric_tests(self) -> Dict[str, FAIRResultEvaluationCriterium]: return self._metric_tests @metric_tests.setter def metric_tests(self, metric_tests: Dict[str, FAIRResultEvaluationCriterium]): self._metric_tests = metric_tests @property def test_status(self) -> str: return self._test_status @test_status.setter def test_status(self, test_status: str): allowed_values = ["pass", "fail", "indeterminate"] if test_status not in allowed_values: raise ValueError( "Invalid value for `test_status` ({0}), must be one of {1}" .format(test_status, allowed_values) ) self._test_status = test_status @property def score(self) -> FAIRResultCommonScore: return self._score @score.setter def score(self, score: FAIRResultCommonScore): if score is None: raise ValueError("Invalid value for `score`, must not be `None`") self._score = score @property def maturity(self) -> str: return self._maturity @maturity.setter def maturity(self, maturity: int): self._maturity = maturity @property def output(self) -> DataProvenanceOutput: return self._output @output.setter def output(self, output: DataProvenanceOutput): self._output = output @property def test_debug(self) -> Debug: return self._test_debug @test_debug.setter def test_debug(self, test_debug: Debug): self._test_debug = test_debug
true
true
f725a0d77d7b829ac919d0eaca76f246b6e73be7
43,643
py
Python
dbaas/maintenance/migrations/0030_auto__add_field_maintenance_disable_alarms.py
didindinn/database-as-a-service
747de31ff8546f7874ddd654af860e130afd17a0
[ "BSD-3-Clause" ]
303
2015-01-08T10:35:54.000Z
2022-02-28T08:54:06.000Z
dbaas/maintenance/migrations/0030_auto__add_field_maintenance_disable_alarms.py
nouraellm/database-as-a-service
5e655c9347bea991b7218a01549f5e44f161d7be
[ "BSD-3-Clause" ]
124
2015-01-14T12:56:15.000Z
2022-03-22T20:45:11.000Z
dbaas/maintenance/migrations/0030_auto__add_field_maintenance_disable_alarms.py
nouraellm/database-as-a-service
5e655c9347bea991b7218a01549f5e44f161d7be
[ "BSD-3-Clause" ]
110
2015-01-02T11:59:48.000Z
2022-02-28T08:54:06.000Z
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Maintenance.disable_alarms' db.add_column(u'maintenance_maintenance', 'disable_alarms', self.gf('django.db.models.fields.BooleanField')(default=False), keep_default=False) def backwards(self, orm): # Deleting field 'Maintenance.disable_alarms' db.delete_column(u'maintenance_maintenance', 'disable_alarms') models = { u'account.team': { 'Meta': {'ordering': "[u'name']", 'object_name': 'Team'}, 'contacts': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'database_alocation_limit': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '2'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'role': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.Group']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'users': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.User']", 'symmetrical': 'False'}) }, u'auth.group': { 'Meta': {'object_name': 'Group'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, u'backup.backupgroup': { 'Meta': {'object_name': 'BackupGroup'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'logical.database': { 'Meta': {'ordering': "(u'name',)", 'unique_together': "((u'name', u'environment'),)", 'object_name': 'Database'}, 'backup_path': ('django.db.models.fields.CharField', [], {'max_length': '300', 'null': 'True', 'blank': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'databaseinfra': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databases'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.DatabaseInfra']"}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'disk_auto_resize': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'environment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databases'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.Environment']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_in_quarantine': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_protected': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'db_index': 'True'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'databases'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['logical.Project']"}), 'quarantine_dt': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'quarantine_user': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'databases_quarantine'", 'null': 'True', 'to': u"orm['auth.User']"}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '2'}), 'subscribe_to_email_events': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'team': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'databases'", 'null': 'True', 'to': u"orm['account.Team']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'used_size_in_bytes': ('django.db.models.fields.FloatField', [], {'default': '0.0'}) }, u'logical.project': { 'Meta': {'ordering': "[u'name']", 'object_name': 'Project'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'maintenance.databasechangeparameter': { 'Meta': {'object_name': 'DatabaseChangeParameter'}, 'can_do_retry': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'current_step': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}), 'database': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'change_parameters'", 'to': u"orm['logical.Database']"}), 'finished_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'started_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'task': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'database_change_parameters'", 'to': u"orm['notification.TaskHistory']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'maintenance.databasecreate': { 'Meta': {'object_name': 'DatabaseCreate'}, 'can_do_retry': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'current_step': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}), 'database': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'databases_create'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['logical.Database']"}), 'description': ('django.db.models.fields.TextField', [], {}), 'environment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databases_create'", 'to': u"orm['physical.Environment']"}), 'finished_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'infra': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databases_create'", 'to': u"orm['physical.DatabaseInfra']"}), 'is_protected': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'plan': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'databases_create'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Plan']"}), 'plan_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'databases_create'", 'null': 'True', 'to': u"orm['logical.Project']"}), 'started_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'subscribe_to_email_events': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'task': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'create_database'", 'to': u"orm['notification.TaskHistory']"}), 'team': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databases_create'", 'to': u"orm['account.Team']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, u'maintenance.databasereinstallvm': { 'Meta': {'object_name': 'DatabaseReinstallVM'}, 'can_do_retry': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'current_step': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}), 'database': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'reinstall_vm'", 'to': u"orm['logical.Database']"}), 'finished_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'instance': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'database_reinstall_vm'", 'to': u"orm['physical.Instance']"}), 'started_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'task': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'database_reinsgtall_vm'", 'to': u"orm['notification.TaskHistory']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'maintenance.databaseresize': { 'Meta': {'object_name': 'DatabaseResize'}, 'can_do_retry': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'current_step': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}), 'database': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'resizes'", 'to': u"orm['logical.Database']"}), 'finished_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'source_offer': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'database_resizes_source'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Offering']"}), 'source_offer_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'started_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'target_offer': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'database_resizes_target'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Offering']"}), 'target_offer_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'task': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'database_resizes'", 'to': u"orm['notification.TaskHistory']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'maintenance.databaserestore': { 'Meta': {'object_name': 'DatabaseRestore'}, 'can_do_retry': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'current_step': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}), 'database': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'database_restore'", 'to': u"orm['logical.Database']"}), 'finished_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'group': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'database_restore'", 'to': u"orm['backup.BackupGroup']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'new_group': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'database_restore_new'", 'null': 'True', 'to': u"orm['backup.BackupGroup']"}), 'started_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'task': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'database_restore'", 'to': u"orm['notification.TaskHistory']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'maintenance.databaserestoreinstancepair': { 'Meta': {'unique_together': "((u'master', u'slave', u'restore'),)", 'object_name': 'DatabaseRestoreInstancePair'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'master': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'restore_master'", 'to': u"orm['physical.Instance']"}), 'restore': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'restore_instances'", 'to': u"orm['maintenance.DatabaseRestore']"}), 'slave': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'restore_slave'", 'to': u"orm['physical.Instance']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'maintenance.databaseupgrade': { 'Meta': {'object_name': 'DatabaseUpgrade'}, 'can_do_retry': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'current_step': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}), 'database': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'upgrades'", 'to': u"orm['logical.Database']"}), 'finished_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'source_plan': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'database_upgrades_source'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Plan']"}), 'source_plan_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'started_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'target_plan': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'database_upgrades_target'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Plan']"}), 'target_plan_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'task': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'database_upgrades'", 'to': u"orm['notification.TaskHistory']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'maintenance.hostmaintenance': { 'Meta': {'unique_together': "((u'host', u'maintenance'),)", 'object_name': 'HostMaintenance', 'index_together': "[[u'host', u'maintenance']]"}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'finished_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'host': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'host_maintenance'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Host']"}), 'hostname': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '255'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'main_log': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'maintenance': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'maintenance'", 'to': u"orm['maintenance.Maintenance']"}), 'rollback_log': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'started_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '4'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'maintenance.maintenance': { 'Meta': {'object_name': 'Maintenance'}, 'affected_hosts': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'celery_task_id': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'created_by': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.CharField', [], {'max_length': '500'}), 'disable_alarms': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'finished_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'hostsid': ('django.db.models.fields.CommaSeparatedIntegerField', [], {'max_length': '10000'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'main_script': ('django.db.models.fields.TextField', [], {}), 'maximum_workers': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '1'}), 'revoked_by': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'rollback_script': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'scheduled_for': ('django.db.models.fields.DateTimeField', [], {'unique': 'True'}), 'started_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'maintenance.maintenanceparameters': { 'Meta': {'object_name': 'MaintenanceParameters'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'function_name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'maintenance': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'maintenance_params'", 'to': u"orm['maintenance.Maintenance']"}), 'parameter_name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'notification.taskhistory': { 'Meta': {'object_name': 'TaskHistory'}, 'arguments': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'context': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'database_name': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '255', 'null': 'True', 'blank': 'True'}), 'db_id': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'details': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'ended_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object_class': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'object_id': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'task_id': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'task_name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'task_status': ('django.db.models.fields.CharField', [], {'default': "u'WAITING'", 'max_length': '100', 'db_index': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '255', 'null': 'True', 'blank': 'True'}) }, u'physical.databaseinfra': { 'Meta': {'object_name': 'DatabaseInfra'}, 'capacity': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'database_key': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'disk_offering': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databaseinfras'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['physical.DiskOffering']"}), 'endpoint': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'endpoint_dns': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'engine': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databaseinfras'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.Engine']"}), 'environment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databaseinfras'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.Environment']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_vm_created': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'name_prefix': ('django.db.models.fields.CharField', [], {'max_length': '10', 'null': 'True', 'blank': 'True'}), 'name_stamp': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '406', 'blank': 'True'}), 'per_database_size_mbytes': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'plan': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databaseinfras'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.Plan']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}) }, u'physical.diskoffering': { 'Meta': {'object_name': 'DiskOffering'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), 'size_kb': ('django.db.models.fields.PositiveIntegerField', [], {}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.engine': { 'Meta': {'ordering': "(u'engine_type__name', u'version')", 'unique_together': "((u'version', u'engine_type'),)", 'object_name': 'Engine'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'engine_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'engines'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.EngineType']"}), 'engine_upgrade_option': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'backwards_engine'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Engine']"}), 'has_users': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'read_node_description': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '100', 'null': 'True', 'blank': 'True'}), 'template_name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user_data_script': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'version': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'write_node_description': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '100', 'null': 'True', 'blank': 'True'}) }, u'physical.enginetype': { 'Meta': {'ordering': "(u'name',)", 'object_name': 'EngineType'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_in_memory': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.environment': { 'Meta': {'object_name': 'Environment'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'migrate_environment': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'migrate_to'", 'null': 'True', 'to': u"orm['physical.Environment']"}), 'min_of_zones': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.host': { 'Meta': {'object_name': 'Host'}, 'address': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'future_host': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['physical.Host']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}), 'hostname': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'identifier': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '255'}), 'monitor_url': ('django.db.models.fields.URLField', [], {'max_length': '500', 'null': 'True', 'blank': 'True'}), 'offering': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['physical.Offering']", 'null': 'True'}), 'os_description': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '406', 'null': 'True', 'blank': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}) }, u'physical.instance': { 'Meta': {'unique_together': "((u'address', u'port'),)", 'object_name': 'Instance'}, 'address': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'databaseinfra': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'instances'", 'to': u"orm['physical.DatabaseInfra']"}), 'dns': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'future_instance': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['physical.Instance']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}), 'hostname': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'instances'", 'to': u"orm['physical.Host']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'instance_type': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'port': ('django.db.models.fields.IntegerField', [], {}), 'read_only': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'shard': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '2'}), 'total_size_in_bytes': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'used_size_in_bytes': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}) }, u'physical.offering': { 'Meta': {'object_name': 'Offering'}, 'cpus': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'environments': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "u'offerings'", 'symmetrical': 'False', 'to': u"orm['physical.Environment']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'memory_size_mb': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.parameter': { 'Meta': {'ordering': "(u'engine_type__name', u'name')", 'unique_together': "((u'name', u'engine_type'),)", 'object_name': 'Parameter'}, 'allowed_values': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '200', 'null': 'True', 'blank': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'custom_method': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'dynamic': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'engine_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'enginetype'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.EngineType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'parameter_type': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '100'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.plan': { 'Meta': {'object_name': 'Plan'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'disk_offering': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'plans'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['physical.DiskOffering']"}), 'engine': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'plans'", 'to': u"orm['physical.Engine']"}), 'engine_equivalent_plan': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'backwards_plan'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Plan']"}), 'environments': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "u'plans'", 'symmetrical': 'False', 'to': u"orm['physical.Environment']"}), 'has_persistence': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_ha': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'max_db_size': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'migrate_plan': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'migrate_to'", 'null': 'True', 'to': u"orm['physical.Plan']"}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'provider': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'replication_topology': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'replication_topology'", 'null': 'True', 'to': u"orm['physical.ReplicationTopology']"}), 'stronger_offering': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'main_offerings'", 'null': 'True', 'to': u"orm['physical.Offering']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'weaker_offering': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'weaker_offerings'", 'null': 'True', 'to': u"orm['physical.Offering']"}) }, u'physical.replicationtopology': { 'Meta': {'object_name': 'ReplicationTopology'}, 'can_change_parameters': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_clone_db': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_reinstall_vm': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_resize_vm': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_switch_master': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_upgrade_db': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'class_path': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'details': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'engine': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "u'replication_topologies'", 'symmetrical': 'False', 'to': u"orm['physical.Engine']"}), 'has_horizontal_scalability': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'parameter': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'replication_topologies'", 'blank': 'True', 'to': u"orm['physical.Parameter']"}), 'script': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'replication_topologies'", 'null': 'True', 'to': u"orm['physical.Script']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.script': { 'Meta': {'object_name': 'Script'}, 'configuration': ('django.db.models.fields.CharField', [], {'max_length': '300'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'initialization': ('django.db.models.fields.CharField', [], {'max_length': '300'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'start_database': ('django.db.models.fields.CharField', [], {'max_length': '300'}), 'start_replication': ('django.db.models.fields.CharField', [], {'max_length': '300', 'null': 'True', 'blank': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) } } complete_apps = ['maintenance']
97.200445
227
0.578512
from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): db.add_column(u'maintenance_maintenance', 'disable_alarms', self.gf('django.db.models.fields.BooleanField')(default=False), keep_default=False) def backwards(self, orm): db.delete_column(u'maintenance_maintenance', 'disable_alarms') models = { u'account.team': { 'Meta': {'ordering': "[u'name']", 'object_name': 'Team'}, 'contacts': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'database_alocation_limit': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '2'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'role': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.Group']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'users': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.User']", 'symmetrical': 'False'}) }, u'auth.group': { 'Meta': {'object_name': 'Group'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, u'backup.backupgroup': { 'Meta': {'object_name': 'BackupGroup'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'logical.database': { 'Meta': {'ordering': "(u'name',)", 'unique_together': "((u'name', u'environment'),)", 'object_name': 'Database'}, 'backup_path': ('django.db.models.fields.CharField', [], {'max_length': '300', 'null': 'True', 'blank': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'databaseinfra': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databases'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.DatabaseInfra']"}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'disk_auto_resize': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'environment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databases'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.Environment']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_in_quarantine': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_protected': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'db_index': 'True'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'databases'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['logical.Project']"}), 'quarantine_dt': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'quarantine_user': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'databases_quarantine'", 'null': 'True', 'to': u"orm['auth.User']"}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '2'}), 'subscribe_to_email_events': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'team': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'databases'", 'null': 'True', 'to': u"orm['account.Team']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'used_size_in_bytes': ('django.db.models.fields.FloatField', [], {'default': '0.0'}) }, u'logical.project': { 'Meta': {'ordering': "[u'name']", 'object_name': 'Project'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'maintenance.databasechangeparameter': { 'Meta': {'object_name': 'DatabaseChangeParameter'}, 'can_do_retry': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'current_step': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}), 'database': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'change_parameters'", 'to': u"orm['logical.Database']"}), 'finished_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'started_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'task': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'database_change_parameters'", 'to': u"orm['notification.TaskHistory']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'maintenance.databasecreate': { 'Meta': {'object_name': 'DatabaseCreate'}, 'can_do_retry': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'current_step': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}), 'database': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'databases_create'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['logical.Database']"}), 'description': ('django.db.models.fields.TextField', [], {}), 'environment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databases_create'", 'to': u"orm['physical.Environment']"}), 'finished_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'infra': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databases_create'", 'to': u"orm['physical.DatabaseInfra']"}), 'is_protected': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'plan': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'databases_create'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Plan']"}), 'plan_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'databases_create'", 'null': 'True', 'to': u"orm['logical.Project']"}), 'started_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'subscribe_to_email_events': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'task': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'create_database'", 'to': u"orm['notification.TaskHistory']"}), 'team': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databases_create'", 'to': u"orm['account.Team']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, u'maintenance.databasereinstallvm': { 'Meta': {'object_name': 'DatabaseReinstallVM'}, 'can_do_retry': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'current_step': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}), 'database': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'reinstall_vm'", 'to': u"orm['logical.Database']"}), 'finished_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'instance': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'database_reinstall_vm'", 'to': u"orm['physical.Instance']"}), 'started_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'task': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'database_reinsgtall_vm'", 'to': u"orm['notification.TaskHistory']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'maintenance.databaseresize': { 'Meta': {'object_name': 'DatabaseResize'}, 'can_do_retry': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'current_step': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}), 'database': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'resizes'", 'to': u"orm['logical.Database']"}), 'finished_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'source_offer': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'database_resizes_source'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Offering']"}), 'source_offer_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'started_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'target_offer': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'database_resizes_target'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Offering']"}), 'target_offer_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'task': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'database_resizes'", 'to': u"orm['notification.TaskHistory']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'maintenance.databaserestore': { 'Meta': {'object_name': 'DatabaseRestore'}, 'can_do_retry': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'current_step': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}), 'database': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'database_restore'", 'to': u"orm['logical.Database']"}), 'finished_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'group': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'database_restore'", 'to': u"orm['backup.BackupGroup']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'new_group': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'database_restore_new'", 'null': 'True', 'to': u"orm['backup.BackupGroup']"}), 'started_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'task': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'database_restore'", 'to': u"orm['notification.TaskHistory']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'maintenance.databaserestoreinstancepair': { 'Meta': {'unique_together': "((u'master', u'slave', u'restore'),)", 'object_name': 'DatabaseRestoreInstancePair'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'master': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'restore_master'", 'to': u"orm['physical.Instance']"}), 'restore': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'restore_instances'", 'to': u"orm['maintenance.DatabaseRestore']"}), 'slave': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'restore_slave'", 'to': u"orm['physical.Instance']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'maintenance.databaseupgrade': { 'Meta': {'object_name': 'DatabaseUpgrade'}, 'can_do_retry': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'current_step': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}), 'database': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'upgrades'", 'to': u"orm['logical.Database']"}), 'finished_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'source_plan': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'database_upgrades_source'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Plan']"}), 'source_plan_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'started_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'target_plan': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'database_upgrades_target'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Plan']"}), 'target_plan_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'task': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'database_upgrades'", 'to': u"orm['notification.TaskHistory']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'maintenance.hostmaintenance': { 'Meta': {'unique_together': "((u'host', u'maintenance'),)", 'object_name': 'HostMaintenance', 'index_together': "[[u'host', u'maintenance']]"}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'finished_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'host': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'host_maintenance'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Host']"}), 'hostname': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '255'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'main_log': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'maintenance': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'maintenance'", 'to': u"orm['maintenance.Maintenance']"}), 'rollback_log': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'started_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '4'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'maintenance.maintenance': { 'Meta': {'object_name': 'Maintenance'}, 'affected_hosts': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'celery_task_id': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'created_by': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.CharField', [], {'max_length': '500'}), 'disable_alarms': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'finished_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'hostsid': ('django.db.models.fields.CommaSeparatedIntegerField', [], {'max_length': '10000'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'main_script': ('django.db.models.fields.TextField', [], {}), 'maximum_workers': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '1'}), 'revoked_by': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'rollback_script': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'scheduled_for': ('django.db.models.fields.DateTimeField', [], {'unique': 'True'}), 'started_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'maintenance.maintenanceparameters': { 'Meta': {'object_name': 'MaintenanceParameters'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'function_name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'maintenance': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'maintenance_params'", 'to': u"orm['maintenance.Maintenance']"}), 'parameter_name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'notification.taskhistory': { 'Meta': {'object_name': 'TaskHistory'}, 'arguments': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'context': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'database_name': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '255', 'null': 'True', 'blank': 'True'}), 'db_id': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'details': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'ended_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object_class': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'object_id': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'task_id': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'task_name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'task_status': ('django.db.models.fields.CharField', [], {'default': "u'WAITING'", 'max_length': '100', 'db_index': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '255', 'null': 'True', 'blank': 'True'}) }, u'physical.databaseinfra': { 'Meta': {'object_name': 'DatabaseInfra'}, 'capacity': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'database_key': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'disk_offering': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databaseinfras'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['physical.DiskOffering']"}), 'endpoint': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'endpoint_dns': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'engine': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databaseinfras'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.Engine']"}), 'environment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databaseinfras'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.Environment']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_vm_created': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'name_prefix': ('django.db.models.fields.CharField', [], {'max_length': '10', 'null': 'True', 'blank': 'True'}), 'name_stamp': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '406', 'blank': 'True'}), 'per_database_size_mbytes': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'plan': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databaseinfras'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.Plan']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}) }, u'physical.diskoffering': { 'Meta': {'object_name': 'DiskOffering'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), 'size_kb': ('django.db.models.fields.PositiveIntegerField', [], {}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.engine': { 'Meta': {'ordering': "(u'engine_type__name', u'version')", 'unique_together': "((u'version', u'engine_type'),)", 'object_name': 'Engine'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'engine_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'engines'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.EngineType']"}), 'engine_upgrade_option': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'backwards_engine'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Engine']"}), 'has_users': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'read_node_description': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '100', 'null': 'True', 'blank': 'True'}), 'template_name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user_data_script': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'version': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'write_node_description': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '100', 'null': 'True', 'blank': 'True'}) }, u'physical.enginetype': { 'Meta': {'ordering': "(u'name',)", 'object_name': 'EngineType'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_in_memory': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.environment': { 'Meta': {'object_name': 'Environment'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'migrate_environment': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'migrate_to'", 'null': 'True', 'to': u"orm['physical.Environment']"}), 'min_of_zones': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.host': { 'Meta': {'object_name': 'Host'}, 'address': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'future_host': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['physical.Host']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}), 'hostname': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'identifier': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '255'}), 'monitor_url': ('django.db.models.fields.URLField', [], {'max_length': '500', 'null': 'True', 'blank': 'True'}), 'offering': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['physical.Offering']", 'null': 'True'}), 'os_description': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '406', 'null': 'True', 'blank': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}) }, u'physical.instance': { 'Meta': {'unique_together': "((u'address', u'port'),)", 'object_name': 'Instance'}, 'address': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'databaseinfra': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'instances'", 'to': u"orm['physical.DatabaseInfra']"}), 'dns': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'future_instance': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['physical.Instance']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}), 'hostname': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'instances'", 'to': u"orm['physical.Host']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'instance_type': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'port': ('django.db.models.fields.IntegerField', [], {}), 'read_only': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'shard': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '2'}), 'total_size_in_bytes': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'used_size_in_bytes': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}) }, u'physical.offering': { 'Meta': {'object_name': 'Offering'}, 'cpus': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'environments': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "u'offerings'", 'symmetrical': 'False', 'to': u"orm['physical.Environment']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'memory_size_mb': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.parameter': { 'Meta': {'ordering': "(u'engine_type__name', u'name')", 'unique_together': "((u'name', u'engine_type'),)", 'object_name': 'Parameter'}, 'allowed_values': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '200', 'null': 'True', 'blank': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'custom_method': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'dynamic': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'engine_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'enginetype'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.EngineType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'parameter_type': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '100'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.plan': { 'Meta': {'object_name': 'Plan'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'disk_offering': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'plans'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['physical.DiskOffering']"}), 'engine': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'plans'", 'to': u"orm['physical.Engine']"}), 'engine_equivalent_plan': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'backwards_plan'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Plan']"}), 'environments': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "u'plans'", 'symmetrical': 'False', 'to': u"orm['physical.Environment']"}), 'has_persistence': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_ha': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'max_db_size': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'migrate_plan': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'migrate_to'", 'null': 'True', 'to': u"orm['physical.Plan']"}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'provider': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'replication_topology': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'replication_topology'", 'null': 'True', 'to': u"orm['physical.ReplicationTopology']"}), 'stronger_offering': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'main_offerings'", 'null': 'True', 'to': u"orm['physical.Offering']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'weaker_offering': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'weaker_offerings'", 'null': 'True', 'to': u"orm['physical.Offering']"}) }, u'physical.replicationtopology': { 'Meta': {'object_name': 'ReplicationTopology'}, 'can_change_parameters': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_clone_db': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_reinstall_vm': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_resize_vm': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_switch_master': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_upgrade_db': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'class_path': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'details': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'engine': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "u'replication_topologies'", 'symmetrical': 'False', 'to': u"orm['physical.Engine']"}), 'has_horizontal_scalability': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'parameter': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'replication_topologies'", 'blank': 'True', 'to': u"orm['physical.Parameter']"}), 'script': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'replication_topologies'", 'null': 'True', 'to': u"orm['physical.Script']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.script': { 'Meta': {'object_name': 'Script'}, 'configuration': ('django.db.models.fields.CharField', [], {'max_length': '300'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'initialization': ('django.db.models.fields.CharField', [], {'max_length': '300'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'start_database': ('django.db.models.fields.CharField', [], {'max_length': '300'}), 'start_replication': ('django.db.models.fields.CharField', [], {'max_length': '300', 'null': 'True', 'blank': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) } } complete_apps = ['maintenance']
true
true
f725a15222a68089d26599b0bfbcfc3a016ae93b
1,466
py
Python
_action_files/nb2post.py
inc0/fastpages
28603b7c6f38f83eea715ab12d71895078dbff9a
[ "Apache-2.0" ]
null
null
null
_action_files/nb2post.py
inc0/fastpages
28603b7c6f38f83eea715ab12d71895078dbff9a
[ "Apache-2.0" ]
null
null
null
_action_files/nb2post.py
inc0/fastpages
28603b7c6f38f83eea715ab12d71895078dbff9a
[ "Apache-2.0" ]
null
null
null
"""Converts Jupyter Notebooks to Jekyll compliant blog posts""" from datetime import datetime import re, os, logging from nbdev import export2html from nbdev.export2html import Config, Path, _re_digits, _to_html, _re_block_notes from fast_template import rename_for_jekyll warnings = set() # Modify the naming process such that destination files get named properly for Jekyll _posts def _nb2htmlfname(nb_path, dest=None): fname = rename_for_jekyll(nb_path, warnings=warnings) if dest is None: dest = Config().doc_path return Path(dest)/fname # Add embedded links for youtube and twitter def add_embedded_links(cell): "Convert block quotes to embedded links in `cell`" _styles = ['youtube', 'twitter'] def _inner(m): title,text = m.groups() if title.lower() not in _styles: return f"> {m.groups()[0]}: {m.groups()[1]}" return '{% include '+title.lower()+".html content=\'`"+_to_html(text)+"`\' %}" if cell['cell_type'] == 'markdown': cell['source'] = _re_block_notes.sub(_inner, cell['source']) return cell # TODO: Open a GitHub Issue in addition to printing warnings for original, new in warnings: print(f'{original} has been renamed to {new} to be complaint with Jekyll naming conventions.\n') ## apply monkey patches export2html._nb2htmlfname = _nb2htmlfname export2html.process_cell.append(add_embedded_links) export2html.notebook2html(fname='_notebooks/*.ipynb', dest='_posts/')
39.621622
100
0.723056
from datetime import datetime import re, os, logging from nbdev import export2html from nbdev.export2html import Config, Path, _re_digits, _to_html, _re_block_notes from fast_template import rename_for_jekyll warnings = set() def _nb2htmlfname(nb_path, dest=None): fname = rename_for_jekyll(nb_path, warnings=warnings) if dest is None: dest = Config().doc_path return Path(dest)/fname def add_embedded_links(cell): _styles = ['youtube', 'twitter'] def _inner(m): title,text = m.groups() if title.lower() not in _styles: return f"> {m.groups()[0]}: {m.groups()[1]}" return '{% include '+title.lower()+".html content=\'`"+_to_html(text)+"`\' %}" if cell['cell_type'] == 'markdown': cell['source'] = _re_block_notes.sub(_inner, cell['source']) return cell for original, new in warnings: print(f'{original} has been renamed to {new} to be complaint with Jekyll naming conventions.\n') name = _nb2htmlfname export2html.process_cell.append(add_embedded_links) export2html.notebook2html(fname='_notebooks/*.ipynb', dest='_posts/')
true
true
f725a1d093a3821295e1aa148bb4213f8b3be699
7,204
py
Python
Chapter05/stock_trading_visual_continuous_env.py
harinipsamy/Tensorflow-2-Reinforcement-Learning-Cookbook
b8858554e4c819c96de10c100f8213ab41561c69
[ "MIT" ]
null
null
null
Chapter05/stock_trading_visual_continuous_env.py
harinipsamy/Tensorflow-2-Reinforcement-Learning-Cookbook
b8858554e4c819c96de10c100f8213ab41561c69
[ "MIT" ]
null
null
null
Chapter05/stock_trading_visual_continuous_env.py
harinipsamy/Tensorflow-2-Reinforcement-Learning-Cookbook
b8858554e4c819c96de10c100f8213ab41561c69
[ "MIT" ]
1
2021-03-27T18:35:14.000Z
2021-03-27T18:35:14.000Z
#!/usr/bin/env python # Visual stock/share trading RL environment with continuous trade actions # Chapter 5, TensorFlow 2 Reinforcement Learning Cookbook | Praveen Palanisamy import os import random from typing import Dict import cv2 import gym import numpy as np import pandas as pd from gym import spaces from trading_utils import TradeVisualizer env_config = { "ticker": "MSFT", "opening_account_balance": 1000, # Number of steps (days) of data provided to the agent in one observation "observation_horizon_sequence_length": 30, } class StockTradingVisualContinuousEnv(gym.Env): def __init__(self, env_config: Dict = env_config): """Stock trading environment for RL agents with continuous action space Args: ticker (str, optional): Ticker symbol for the stock. Defaults to "MSFT". env_config (Dict): Env configuration values """ super(StockTradingVisualContinuousEnv, self).__init__() self.ticker = env_config.get("ticker", "MSFT") data_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "data") self.ticker_file_stream = os.path.join(f"{data_dir}", f"{self.ticker}.csv") assert os.path.isfile( self.ticker_file_stream ), f"Historical stock data file stream not found at: data/{self.ticker}.csv" # Stock market data stream. An offline file stream is used. Alternatively, a web # API can be used to pull live data. # Data-Frame: Date Open High Low Close Adj-Close Volume self.ohlcv_df = pd.read_csv(self.ticker_file_stream) self.opening_account_balance = env_config["opening_account_balance"] # Action: 1-dim value indicating a fraction amount of shares to Buy (0 to 1) or # sell (-1 to 0). The fraction is taken on the allowable number of # shares that can be bought or sold based on the account balance (no margin). self.action_space = spaces.Box( low=np.array([-1]), high=np.array([1]), dtype=np.float ) self.observation_features = [ "Open", "High", "Low", "Close", "Adj Close", "Volume", ] self.obs_width, self.obs_height = 128, 128 self.horizon = env_config.get("observation_horizon_sequence_length") self.observation_space = spaces.Box( low=0, high=255, shape=(128, 128, 3), dtype=np.uint8, ) self.viz = None # Visualizer def step(self, action): # Execute one step within the environment self.execute_trade_action(action) self.current_step += 1 reward = self.account_value - self.opening_account_balance # Profit (loss) done = self.account_value <= 0 or self.current_step >= len( self.ohlcv_df.loc[:, "Open"].values ) obs = self.get_observation() return obs, reward, done, {} def reset(self): # Reset the state of the environment to an initial state self.cash_balance = self.opening_account_balance self.account_value = self.opening_account_balance self.num_shares_held = 0 self.cost_basis = 0 self.current_step = 0 self.trades = [] if self.viz is None: self.viz = TradeVisualizer( self.ticker, self.ticker_file_stream, "TFRL-Cookbook Ch4-StockTradingVisualContinuousEnv", ) return self.get_observation() def render(self, **kwargs): # Render the environment to the screen if self.current_step > self.horizon: self.viz.render( self.current_step, self.account_value, self.trades, window_size=self.horizon, ) def close(self): if self.viz is not None: self.viz.close() self.viz = None def get_observation(self): """Return a view of the Ticker price chart as image observation Returns: img_observation (np.ndarray): Image of ticker candle stick plot with volume bars as observation """ img_observation = self.viz.render_image_observation( self.current_step, self.horizon ) img_observation = cv2.resize( img_observation, dsize=(128, 128), interpolation=cv2.INTER_CUBIC ) return img_observation def execute_trade_action(self, action): if action == 0: # Indicates "Hold" action # Hold position; No trade to be executed return order_type = "buy" if action > 0 else "sell" order_fraction_of_allowable_shares = abs(action) # Stochastically determine the current stock price based on Market Open & Close current_price = random.uniform( self.ohlcv_df.loc[self.current_step, "Open"], self.ohlcv_df.loc[self.current_step, "Close"], ) if order_type == "buy": allowable_shares = int(self.cash_balance / current_price) # Simulate a BUY order and execute it at current_price num_shares_bought = int( allowable_shares * order_fraction_of_allowable_shares ) current_cost = self.cost_basis * self.num_shares_held additional_cost = num_shares_bought * current_price self.cash_balance -= additional_cost self.cost_basis = (current_cost + additional_cost) / ( self.num_shares_held + num_shares_bought ) self.num_shares_held += num_shares_bought if num_shares_bought > 0: self.trades.append( { "type": "buy", "step": self.current_step, "shares": num_shares_bought, "proceeds": additional_cost, } ) elif order_type == "sell": # Simulate a SELL order and execute it at current_price num_shares_sold = int( self.num_shares_held * order_fraction_of_allowable_shares ) self.cash_balance += num_shares_sold * current_price self.num_shares_held -= num_shares_sold sale_proceeds = num_shares_sold * current_price if num_shares_sold > 0: self.trades.append( { "type": "sell", "step": self.current_step, "shares": num_shares_sold, "proceeds": sale_proceeds, } ) if self.num_shares_held == 0: self.cost_basis = 0 # Update account value self.account_value = self.cash_balance + self.num_shares_held * current_price if __name__ == "__main__": env = StockTradingVisualContinuousEnv() obs = env.reset() for _ in range(600): action = env.action_space.sample() next_obs, reward, done, _ = env.step(action) env.render()
35.141463
88
0.593282
import os import random from typing import Dict import cv2 import gym import numpy as np import pandas as pd from gym import spaces from trading_utils import TradeVisualizer env_config = { "ticker": "MSFT", "opening_account_balance": 1000, "observation_horizon_sequence_length": 30, } class StockTradingVisualContinuousEnv(gym.Env): def __init__(self, env_config: Dict = env_config): super(StockTradingVisualContinuousEnv, self).__init__() self.ticker = env_config.get("ticker", "MSFT") data_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "data") self.ticker_file_stream = os.path.join(f"{data_dir}", f"{self.ticker}.csv") assert os.path.isfile( self.ticker_file_stream ), f"Historical stock data file stream not found at: data/{self.ticker}.csv" self.ohlcv_df = pd.read_csv(self.ticker_file_stream) self.opening_account_balance = env_config["opening_account_balance"] self.action_space = spaces.Box( low=np.array([-1]), high=np.array([1]), dtype=np.float ) self.observation_features = [ "Open", "High", "Low", "Close", "Adj Close", "Volume", ] self.obs_width, self.obs_height = 128, 128 self.horizon = env_config.get("observation_horizon_sequence_length") self.observation_space = spaces.Box( low=0, high=255, shape=(128, 128, 3), dtype=np.uint8, ) self.viz = None def step(self, action): self.execute_trade_action(action) self.current_step += 1 reward = self.account_value - self.opening_account_balance done = self.account_value <= 0 or self.current_step >= len( self.ohlcv_df.loc[:, "Open"].values ) obs = self.get_observation() return obs, reward, done, {} def reset(self): self.cash_balance = self.opening_account_balance self.account_value = self.opening_account_balance self.num_shares_held = 0 self.cost_basis = 0 self.current_step = 0 self.trades = [] if self.viz is None: self.viz = TradeVisualizer( self.ticker, self.ticker_file_stream, "TFRL-Cookbook Ch4-StockTradingVisualContinuousEnv", ) return self.get_observation() def render(self, **kwargs): if self.current_step > self.horizon: self.viz.render( self.current_step, self.account_value, self.trades, window_size=self.horizon, ) def close(self): if self.viz is not None: self.viz.close() self.viz = None def get_observation(self): img_observation = self.viz.render_image_observation( self.current_step, self.horizon ) img_observation = cv2.resize( img_observation, dsize=(128, 128), interpolation=cv2.INTER_CUBIC ) return img_observation def execute_trade_action(self, action): if action == 0: return order_type = "buy" if action > 0 else "sell" order_fraction_of_allowable_shares = abs(action) current_price = random.uniform( self.ohlcv_df.loc[self.current_step, "Open"], self.ohlcv_df.loc[self.current_step, "Close"], ) if order_type == "buy": allowable_shares = int(self.cash_balance / current_price) num_shares_bought = int( allowable_shares * order_fraction_of_allowable_shares ) current_cost = self.cost_basis * self.num_shares_held additional_cost = num_shares_bought * current_price self.cash_balance -= additional_cost self.cost_basis = (current_cost + additional_cost) / ( self.num_shares_held + num_shares_bought ) self.num_shares_held += num_shares_bought if num_shares_bought > 0: self.trades.append( { "type": "buy", "step": self.current_step, "shares": num_shares_bought, "proceeds": additional_cost, } ) elif order_type == "sell": num_shares_sold = int( self.num_shares_held * order_fraction_of_allowable_shares ) self.cash_balance += num_shares_sold * current_price self.num_shares_held -= num_shares_sold sale_proceeds = num_shares_sold * current_price if num_shares_sold > 0: self.trades.append( { "type": "sell", "step": self.current_step, "shares": num_shares_sold, "proceeds": sale_proceeds, } ) if self.num_shares_held == 0: self.cost_basis = 0 self.account_value = self.cash_balance + self.num_shares_held * current_price if __name__ == "__main__": env = StockTradingVisualContinuousEnv() obs = env.reset() for _ in range(600): action = env.action_space.sample() next_obs, reward, done, _ = env.step(action) env.render()
true
true
f725a200284daaaded9eadc2048d2708f4206809
109,449
py
Python
olfactorybulb/slices/CoronalSlice/TC4_0.py
fameshpatel/olfactorybulb
8d7a644b4560309ef177c0590ff73ed4c2432604
[ "MIT" ]
null
null
null
olfactorybulb/slices/CoronalSlice/TC4_0.py
fameshpatel/olfactorybulb
8d7a644b4560309ef177c0590ff73ed4c2432604
[ "MIT" ]
null
null
null
olfactorybulb/slices/CoronalSlice/TC4_0.py
fameshpatel/olfactorybulb
8d7a644b4560309ef177c0590ff73ed4c2432604
[ "MIT" ]
null
null
null
from neuron import h class TransformTC4: def __init__(self): # Create a section lookup by section name # Note: this assumes each section has a unique name self.name2section = { sec.name(): sec for sec in h.allsec() } # This will store the new section coordinates self.section_coords = { } def set_coords(self, sec_name): # Lookup the section nrn_section = self.name2section[sec_name] # Lookup its new coords new_coords = self.section_coords[sec_name] # Use 3D points as section L and diam sources h.pt3dconst(1, sec=nrn_section) # Clear the existing points - and allocate room for the incoming points h.pt3dclear(len(new_coords["diam"]), sec=nrn_section) # Use vectorization to add the points to section xvec = h.Vector(new_coords["x"]) yvec = h.Vector(new_coords["y"]) zvec = h.Vector(new_coords["z"]) dvec = h.Vector(new_coords["diam"]) h.pt3dadd(xvec, yvec, zvec, dvec, sec=nrn_section) def set_all(self): for sec_name in self.section_coords.keys(): self.set_coords(sec_name) @staticmethod def apply_on(prefix): t = TransformTC4() t.define_coords(prefix) t.set_all() @staticmethod def apply(): t = TransformTC4() t.define_coords() t.set_all() def define_coords(self, prefix = 'TC4[0]'): if prefix != '': prefix += '.' self.section_coords = { prefix + 'apic[68]': { 'x':[-401.322,-402.235,-402.958,-401.756], 'y':[743.117,744.267,743.755,747.357], 'z':[-23.836,-21.982,-21.153,-19.972], 'diam':[0.264,0.264,0.264,0.264] }, prefix + 'apic[100]': { 'x':[-368.650,-369.977,-371.475,-372.161,-372.512,-373.361,-373.937,-374.711,-375.289,-375.521,-375.522,-376.265,-375.041,-375.495,-375.517,-374.957,-374.165,-373.673,-372.672,-371.700], 'y':[721.906,722.984,723.293,723.815,724.044,724.948,725.556,726.107,726.840,727.356,728.641,728.811,731.930,731.927,732.329,732.519,732.126,732.122,732.931,732.884], 'z':[-26.366,-25.829,-24.064,-23.086,-21.692,-20.685,-20.100,-19.668,-18.622,-17.585,-16.403,-13.942,-13.605,-11.861,-10.119,-8.762,-7.375,-6.275,-5.944,-4.515], 'diam':[0.613,0.442,0.442,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[113]': { 'x':[-383.489,-383.890,-383.410,-381.081,-380.535], 'y':[724.129,724.331,723.344,724.340,723.080], 'z':[-44.607,-43.031,-41.923,-41.646,-40.779], 'diam':[0.613,0.264,0.264,0.264,0.264] }, prefix + 'apic[37]': { 'x':[-375.585,-375.040,-374.570,-372.798,-371.266], 'y':[726.541,727.069,727.549,727.462,727.211], 'z':[-37.841,-35.655,-33.710,-32.052,-30.669], 'diam':[0.613,0.706,0.706,0.792,0.792] }, prefix + 'dend[2]': { 'x':[-305.424,-306.149,-306.972,-307.633,-307.203,-306.701,-307.338,-308.001,-307.992,-308.743,-309.466,-310.076,-309.901,-309.758,-310.736,-310.876,-311.714,-311.679,-312.585,-313.265,-314.333,-315.285,-316.729,-317.738,-318.707,-319.653,-320.304,-321.717,-323.098,-323.748,-323.829,-324.387,-325.403,-325.801,-326.171,-327.007,-326.773,-326.650,-327.482,-327.738,-328.016,-328.723,-328.947,-329.713,-330.844,-331.091,-331.111,-332.015,-332.114,-332.743,-333.113,-334.087,-334.663,-335.558,-336.136,-336.693,-337.237,-337.555,-337.335,-337.787,-338.119,-339.486,-340.852,-341.635,-342.410,-343.707,-345.556,-346.546,-347.430,-347.788,-348.533,-350.674,-351.546,-352.687,-353.566,-355.548,-356.503,-358.427,-359.864,-360.664,-361.856,-363.812,-364.870,-365.902,-367.369,-368.292,-368.764,-369.440,-370.536,-369.616,-370.027,-370.562,-369.958,-371.540,-372.116,-372.849,-373.095,-373.288,-373.202,-373.851,-374.295,-374.686,-374.293,-374.813,-375.303,-375.578,-376.148,-376.218,-377.242,-377.452,-377.267,-377.331,-377.443,-377.591,-377.441,-377.731,-378.310,-378.240,-378.158,-379.308,-379.335,-379.848,-380.406,-380.797,-380.513,-380.372,-380.032,-379.849,-379.917,-379.376,-378.853,-379.067,-378.944,-379.432,-379.750,-381.569,-381.330,-381.775,-382.134,-382.884,-383.706,-384.466,-384.231,-383.911,-385.008,-385.241,-385.364,-385.829,-386.448,-386.579,-386.330,-384.136,-387.079,-387.052,-386.854,-387.056,-387.134,-386.899,-387.208,-387.344,-387.404,-388.023,-387.858,-388.750,-389.583,-389.749,-390.293,-390.904,-391.807,-392.082,-393.498,-394.299,-395.083,-396.237,-397.409,-398.536,-398.992,-399.711,-400.673,-401.799,-401.981,-402.645,-402.713,-403.474,-404.364,-404.557,-405.328,-406.310,-406.915,-406.661,-407.622,-408.540,-408.281,-408.601,-409.468,-410.498,-411.801,-412.336,-413.417,-414.658,-415.811,-417.025,-417.416,-418.083,-418.578,-418.893,-419.861,-419.442,-420.697,-420.904,-421.188,-421.585,-422.166,-421.938,-421.805,-421.925,-422.798,-423.851,-424.795], 'y':[657.846,655.817,654.383,653.371,652.356,651.413,650.015,649.378,647.780,646.618,645.949,644.136,642.224,640.841,639.570,637.857,636.189,635.102,634.031,633.678,632.205,631.336,631.200,630.695,628.655,627.457,626.996,626.050,625.432,624.547,623.001,621.427,620.541,619.190,617.529,616.051,614.099,613.047,612.730,611.830,610.882,610.074,608.913,607.579,606.409,605.188,603.234,602.723,601.681,600.729,599.748,598.653,597.857,597.572,596.367,594.512,593.448,591.688,590.399,589.428,587.989,587.069,585.854,585.221,584.161,583.198,580.883,581.289,582.894,584.788,583.671,583.680,584.025,584.415,583.736,583.322,583.894,582.830,582.608,583.592,582.619,582.818,582.532,583.399,583.482,583.227,581.977,580.616,579.303,578.936,577.589,576.747,575.455,573.755,572.849,571.127,569.857,568.450,567.149,565.861,564.832,563.384,562.328,559.544,558.447,557.437,556.355,554.987,553.428,552.117,550.812,549.716,546.844,545.215,542.425,541.523,539.703,538.178,536.442,534.657,532.485,531.476,530.006,528.892,526.795,525.742,524.451,521.642,519.838,518.634,516.972,514.884,513.827,511.941,511.025,508.376,506.818,505.672,504.514,503.805,502.764,502.042,500.095,498.508,497.199,495.989,494.709,493.780,492.397,490.989,490.029,489.595,487.717,485.106,484.052,482.960,481.577,479.617,478.870,477.803,476.740,474.906,473.845,473.536,473.042,471.747,470.879,470.946,470.850,469.999,468.585,467.704,467.859,467.609,467.765,466.920,465.363,464.453,464.173,463.719,462.390,461.857,461.112,459.863,459.303,458.068,457.058,455.924,454.394,453.021,452.240,452.244,451.172,450.056,449.408,449.081,449.179,448.412,446.642,445.859,444.628,444.020,442.960,442.026,441.460,440.411,439.813,438.771,437.936,436.800,435.005,434.026,432.869,431.080,429.895,428.409,426.955,426.013,425.250], 'z':[-86.353,-87.989,-88.761,-88.939,-88.680,-88.000,-88.761,-89.898,-89.692,-89.536,-90.332,-90.940,-91.312,-91.513,-92.119,-92.179,-92.385,-92.720,-93.485,-94.379,-96.344,-98.222,-99.345,-100.621,-101.779,-102.844,-103.498,-105.342,-106.480,-106.656,-107.169,-107.746,-108.364,-109.480,-109.473,-110.100,-110.682,-111.082,-112.447,-113.092,-113.890,-115.204,-115.781,-117.054,-117.343,-117.169,-117.852,-119.066,-119.581,-119.313,-119.441,-119.837,-120.587,-121.746,-122.672,-123.778,-124.385,-125.363,-124.846,-125.350,-126.532,-127.184,-127.755,-128.331,-129.353,-130.216,-130.395,-130.526,-130.866,-130.201,-130.487,-130.377,-130.020,-130.195,-130.095,-129.484,-129.739,-130.273,-129.503,-128.554,-128.446,-128.139,-128.708,-129.447,-129.267,-129.626,-128.220,-129.090,-128.702,-127.449,-127.936,-128.480,-128.426,-128.490,-128.582,-129.206,-128.592,-127.909,-128.036,-127.543,-128.534,-129.986,-129.992,-130.331,-130.234,-130.883,-131.173,-131.188,-131.680,-131.871,-132.231,-132.626,-133.187,-134.125,-134.815,-135.144,-136.072,-136.551,-136.788,-137.401,-138.135,-138.287,-139.150,-139.579,-140.098,-140.192,-140.236,-141.162,-141.916,-142.092,-142.369,-142.775,-143.167,-144.192,-145.113,-145.094,-145.724,-146.425,-146.455,-146.475,-147.001,-147.326,-147.918,-148.456,-148.977,-149.126,-149.373,-149.399,-149.570,-150.616,-150.866,-152.262,-150.603,-151.171,-151.544,-151.308,-152.278,-153.162,-153.967,-154.817,-155.295,-155.630,-155.975,-156.965,-156.694,-157.271,-158.206,-159.039,-160.278,-161.103,-161.318,-162.349,-163.169,-162.746,-163.119,-164.759,-164.727,-165.663,-166.734,-167.411,-167.563,-168.462,-169.395,-169.037,-169.627,-170.025,-170.360,-171.438,-171.585,-172.070,-173.092,-174.290,-174.577,-175.730,-176.070,-176.351,-177.666,-178.886,-180.318,-180.816,-182.097,-182.728,-183.377,-184.530,-185.581,-186.584,-186.938,-186.899,-187.257,-187.614,-188.210,-188.098,-187.870,-188.570,-188.928,-189.297,-189.777,-189.732,-189.137], 'diam':[0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[123]': { 'x':[-388.217,-387.909,-388.043,-388.419,-388.477,-388.170,-388.968,-389.566,-390.968,-391.192,-392.156,-392.402,-392.782,-393.483,-393.249,-393.743], 'y':[750.404,751.127,751.354,751.752,752.328,752.722,753.615,754.306,754.648,754.734,755.681,757.866,758.125,758.138,761.297,762.410], 'z':[-11.011,-8.893,-6.999,-6.000,-4.675,-3.202,-0.731,0.335,2.959,4.058,5.472,7.517,8.479,9.546,10.264,10.996], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[137]': { 'x':[-406.717,-408.041,-408.660], 'y':[739.828,738.773,737.771], 'z':[-42.726,-43.717,-44.083], 'diam':[0.264,0.264,0.264] }, prefix + 'apic[87]': { 'x':[-383.728,-383.712,-383.710,-384.757,-384.819,-384.736,-384.132,-383.222,-383.501,-383.637,-383.721], 'y':[729.654,730.154,730.665,731.362,732.288,733.530,733.810,734.566,736.049,736.656,737.408], 'z':[-36.522,-35.245,-33.983,-32.367,-30.814,-29.637,-28.144,-26.853,-24.876,-24.069,-23.133], 'diam':[0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[107]': { 'x':[-402.452,-402.181,-402.512,-403.510,-404.990,-407.221,-407.770,-408.463,-409.672,-410.454,-411.101,-411.695,-411.789], 'y':[733.848,735.891,736.974,738.379,738.467,740.361,741.079,741.936,743.547,744.308,744.920,746.146,747.115], 'z':[-36.376,-35.862,-35.126,-34.206,-33.382,-31.205,-30.321,-29.313,-27.433,-26.810,-26.317,-25.184,-24.501], 'diam':[0.349,0.349,0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[45]': { 'x':[-366.165,-366.313,-366.835], 'y':[732.626,733.106,733.993], 'z':[-4.049,-3.108,-1.770], 'diam':[0.349,0.349,0.349] }, prefix + 'apic[35]': { 'x':[-375.082,-376.135,-376.999,-377.821], 'y':[723.155,724.325,724.617,725.564], 'z':[-47.527,-44.332,-42.503,-41.334], 'diam':[1.234,0.792,0.792,0.792] }, prefix + 'apic[38]': { 'x':[-371.266,-371.908], 'y':[727.211,728.584], 'z':[-30.669,-28.319], 'diam':[0.792,0.528] }, prefix + 'apic[33]': { 'x':[-374.024,-375.311,-377.581,-378.871,-380.203,-381.533,-382.323,-383.122,-384.607,-385.543,-385.955,-385.374,-384.843,-384.505,-384.329,-384.884,-385.583,-386.239,-387.042], 'y':[715.198,716.497,717.045,717.621,716.615,718.152,718.867,719.520,720.476,721.465,723.395,724.035,724.041,723.880,724.005,724.978,725.181,725.388,726.011], 'z':[-38.925,-37.785,-37.421,-37.312,-36.767,-35.118,-34.480,-34.154,-33.048,-31.047,-27.090,-24.605,-23.094,-21.588,-20.360,-18.534,-17.451,-14.734,-12.598], 'diam':[0.877,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[4]': { 'x':[-372.673,-370.268,-368.721,-367.836,-366.480,-365.724,-364.489,-364.000,-364.098], 'y':[717.133,716.035,716.542,716.517,716.592,716.446,716.739,717.539,717.234], 'z':[-46.593,-45.274,-45.463,-44.560,-43.284,-42.583,-42.087,-41.024,-39.614], 'diam':[1.320,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706] }, prefix + 'apic[73]': { 'x':[-382.134,-384.144,-385.221,-385.503,-386.609,-388.356,-389.217,-389.277], 'y':[726.717,727.360,728.561,729.123,729.959,730.043,731.161,731.679], 'z':[-40.431,-37.713,-36.462,-35.538,-34.327,-31.762,-30.401,-29.218], 'diam':[0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706] }, prefix + 'apic[27]': { 'x':[-356.857,-356.708,-357.203,-357.340], 'y':[702.880,703.299,703.826,703.884], 'z':[-29.899,-28.605,-27.042,-25.850], 'diam':[0.442,0.442,0.442,0.442] }, prefix + 'apic[23]': { 'x':[-362.344,-361.072,-360.172,-360.559,-359.839], 'y':[708.536,708.312,707.816,707.671,708.648], 'z':[-29.530,-28.825,-28.610,-27.247,-26.957], 'diam':[0.528,0.264,0.264,0.264,0.264] }, prefix + 'apic[120]': { 'x':[-394.546,-395.049,-395.217,-395.218], 'y':[737.443,738.429,739.655,740.049], 'z':[-41.888,-40.244,-37.510,-36.531], 'diam':[0.528,0.528,0.613,0.613] }, prefix + 'apic[80]': { 'x':[-396.249,-396.770,-398.279,-400.340,-401.841,-402.934,-404.005,-403.900,-405.902], 'y':[731.890,731.769,733.115,732.914,733.113,733.800,733.330,734.782,732.221], 'z':[-29.596,-30.740,-31.656,-31.900,-31.798,-31.216,-30.988,-32.214,-32.098], 'diam':[0.442,0.528,0.528,0.349,0.349,0.349,0.349,0.349,0.264] }, prefix + 'apic[125]': { 'x':[-396.161,-396.692,-397.460,-397.899,-398.619], 'y':[740.635,741.256,742.070,742.393,742.819], 'z':[-35.501,-33.897,-33.109,-32.098,-31.263], 'diam':[0.528,0.528,0.528,0.528,0.528] }, prefix + 'apic[140]': { 'x':[-392.313,-393.520,-394.433,-396.215,-397.872,-398.268,-400.003,-400.972,-401.942,-403.022,-403.964,-405.032,-405.625,-405.135,-405.528], 'y':[732.909,733.465,733.906,733.127,733.614,735.331,735.090,735.531,736.857,737.613,738.345,738.197,737.888,740.515,741.655], 'z':[-53.049,-53.616,-53.980,-53.947,-53.513,-53.518,-53.593,-54.213,-53.589,-53.466,-53.172,-52.276,-51.350,-51.238,-49.825], 'diam':[0.442,0.349,0.349,0.349,0.349,0.442,0.442,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[28]': { 'x':[-356.857,-356.919,-356.761], 'y':[702.880,701.549,701.058], 'z':[-29.899,-30.956,-32.674], 'diam':[0.442,0.442,0.442] }, prefix + 'apic[79]': { 'x':[-389.277,-392.355,-393.562,-395.216,-396.249], 'y':[731.679,731.891,732.249,732.656,731.890], 'z':[-29.218,-29.900,-30.475,-29.766,-29.596], 'diam':[0.706,0.442,0.442,0.442,0.442] }, prefix + 'apic[6]': { 'x':[-362.553,-361.157], 'y':[717.930,717.776], 'z':[-39.618,-40.571], 'diam':[0.442,0.264] }, prefix + 'apic[58]': { 'x':[-368.533,-367.127,-367.500,-367.990,-366.772,-364.813,-363.144,-361.999,-360.753,-360.087,-359.239,-358.460,-356.936,-355.972], 'y':[725.556,724.702,725.159,725.813,725.501,724.931,724.064,723.631,723.152,723.091,721.588,721.156,720.129,718.758], 'z':[-29.616,-28.522,-27.381,-26.560,-25.220,-23.497,-21.118,-19.723,-18.596,-17.662,-17.243,-16.599,-16.381,-16.184], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[116]': { 'x':[-407.931,-408.947,-409.732,-410.750,-412.326,-413.177], 'y':[734.348,735.025,735.733,735.467,735.552,735.258], 'z':[-37.540,-37.480,-37.005,-36.943,-36.793,-37.324], 'diam':[0.179,0.179,0.179,0.179,0.179,0.179] }, prefix + 'apic[40]': { 'x':[-372.570,-372.849,-373.328], 'y':[730.628,731.242,731.957], 'z':[-21.545,-20.472,-19.495], 'diam':[0.528,0.349,0.349] }, prefix + 'apic[74]': { 'x':[-389.277,-389.302,-389.392,-389.856,-389.686,-389.242], 'y':[731.679,732.541,733.801,735.468,736.410,737.183], 'z':[-29.218,-27.141,-24.164,-20.790,-18.228,-16.218], 'diam':[0.706,0.528,0.613,0.613,0.613,0.613] }, prefix + 'apic[112]': { 'x':[-393.081,-394.111,-395.147], 'y':[723.019,724.029,723.597], 'z':[-41.593,-40.711,-39.279], 'diam':[0.349,0.349,0.349] }, prefix + 'dend[6]': { 'x':[-316.649,-316.983,-317.001,-316.991,-318.052,-319.144,-320.229,-320.690,-320.721,-320.971,-321.537,-323.054,-323.926,-325.276,-327.635,-326.904,-327.275,-328.221,-328.880,-329.401,-329.713,-330.354,-331.563,-332.397,-332.869,-333.901,-334.766,-336.052,-337.195,-338.096,-338.652,-339.383,-339.641,-339.814,-339.943,-339.773,-340.698,-341.420,-342.074,-343.010,-343.509,-344.218,-345.016,-345.544,-345.947,-346.366,-346.623,-346.994,-348.169,-349.116,-350.655,-351.823,-352.929,-354.289,-355.540,-356.724,-358.809,-360.180,-361.545,-363.034,-364.550,-366.090,-368.226,-370.293,-371.230,-372.645,-373.711,-374.577,-376.534,-377.696,-378.902,-379.974,-380.897,-382.571,-384.229,-386.551,-386.744,-387.056,-388.525,-388.441,-388.860,-390.513,-391.655,-392.346,-393.119,-394.626,-396.507,-397.421,-398.495,-399.628,-400.393,-401.059,-400.775,-400.778,-402.156,-402.780,-403.163,-403.496,-403.410,-403.824,-403.804,-404.479,-405.193,-406.114,-405.251,-405.872,-407.220,-407.017,-407.361,-408.038,-408.831,-409.900,-409.459,-410.673,-411.358,-411.926,-412.272,-412.908,-413.529,-414.666,-415.458,-416.558,-417.888,-419.097,-419.184,-420.554,-421.509,-422.694,-423.226,-423.698,-424.487,-425.051,-426.607,-427.473,-428.605,-429.542,-431.626,-433.594,-434.985,-435.229,-435.324,-435.402,-435.347,-434.879,-434.224,-434.166,-434.772,-435.318,-435.951,-436.312,-436.963,-437.227,-437.313,-437.152,-437.569,-438.780,-440.223,-441.081,-441.657,-442.116,-443.317,-444.559,-446.245,-447.687], 'y':[714.484,714.221,715.057,716.820,716.696,716.724,716.798,717.294,717.360,717.687,718.119,718.775,718.794,718.806,719.070,719.804,719.978,720.201,720.189,720.071,720.724,721.468,721.636,721.968,722.043,722.759,722.716,723.242,723.542,723.505,723.461,724.344,724.482,724.358,724.307,724.258,724.339,724.578,724.602,724.640,725.008,725.341,725.094,724.889,724.749,725.711,726.235,727.135,727.474,727.264,728.507,729.042,729.031,728.949,728.793,728.703,728.929,728.849,728.824,729.236,729.066,728.853,730.052,729.783,729.616,729.516,729.532,729.442,729.475,729.328,729.244,729.123,728.956,728.750,728.624,730.111,729.933,731.110,731.107,731.188,731.421,731.550,731.448,731.394,731.317,731.061,730.824,731.181,731.345,731.293,731.604,731.442,731.303,731.175,733.338,733.942,734.276,734.242,734.418,734.992,735.434,735.902,736.442,736.800,736.761,737.061,737.474,737.508,738.166,739.026,739.582,739.321,739.225,739.208,739.967,739.972,740.377,740.793,740.775,740.865,741.357,741.737,741.558,741.439,741.470,742.032,742.406,742.088,738.975,738.371,738.149,737.385,737.046,736.909,736.754,736.588,735.994,735.937,735.640,735.058,734.900,735.510,736.036,735.937,735.919,735.807,735.770,735.918,736.277,736.113,735.849,735.755,735.553,735.454,735.173,734.910,734.628,734.484,734.347,734.210,733.492,733.964,734.527,734.769], 'z':[-111.225,-114.063,-116.672,-117.876,-118.327,-118.778,-119.829,-120.661,-121.710,-122.946,-123.788,-125.324,-126.776,-127.648,-128.862,-130.491,-131.624,-132.882,-134.193,-135.688,-136.718,-137.379,-139.032,-140.858,-142.578,-143.834,-144.717,-146.181,-148.760,-150.107,-151.384,-152.760,-153.873,-155.288,-156.354,-158.299,-160.121,-161.333,-162.173,-164.462,-165.634,-166.386,-169.205,-171.164,-172.511,-173.835,-175.081,-176.608,-178.738,-180.321,-181.422,-182.288,-182.632,-183.390,-184.101,-183.996,-185.383,-186.128,-186.892,-187.802,-188.348,-189.358,-189.816,-190.464,-191.580,-191.995,-192.570,-193.437,-194.785,-195.363,-195.728,-196.188,-197.307,-198.222,-198.673,-199.755,-201.642,-202.367,-202.093,-203.128,-204.036,-205.216,-205.904,-207.091,-207.836,-209.536,-210.497,-211.413,-211.993,-213.273,-214.849,-216.140,-217.461,-219.082,-220.175,-221.973,-223.114,-224.928,-225.964,-227.718,-229.134,-230.704,-232.044,-232.848,-233.580,-234.790,-236.957,-237.958,-238.881,-240.012,-241.024,-243.092,-244.631,-246.152,-246.583,-247.862,-249.239,-251.487,-253.017,-254.423,-257.443,-259.092,-260.520,-262.041,-263.933,-264.954,-266.800,-267.720,-268.800,-269.669,-270.867,-272.910,-274.841,-275.713,-276.408,-277.523,-280.140,-281.939,-284.192,-286.187,-287.933,-289.034,-290.688,-292.907,-293.812,-295.181,-296.226,-297.638,-298.721,-299.720,-301.587,-302.552,-304.882,-306.234,-309.215,-311.194,-312.640,-313.513,-314.663,-315.795,-317.907,-319.477,-320.685,-321.816], 'diam':[1.056,0.877,0.877,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.613,0.613,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.264,0.264,0.264,0.264] }, prefix + 'apic[48]': { 'x':[-369.377,-368.868,-369.001], 'y':[728.596,728.853,729.446], 'z':[-20.031,-18.610,-17.351], 'diam':[0.349,0.264,0.264] }, prefix + 'apic[90]': { 'x':[-380.344,-377.873,-376.028,-375.083,-374.022,-371.998,-371.004,-369.502,-367.979,-368.221,-367.901,-368.675,-367.791,-368.599,-368.650], 'y':[724.015,722.870,724.168,722.390,722.279,721.505,720.499,721.433,721.332,722.116,722.974,721.697,722.709,721.204,721.906], 'z':[-44.355,-43.085,-41.437,-39.030,-38.067,-36.429,-34.992,-34.486,-33.082,-31.540,-30.933,-29.551,-29.546,-28.180,-26.366], 'diam':[0.613,0.613,0.613,0.613,0.528,0.528,0.528,0.528,0.613,0.613,0.613,0.613,0.613,0.613,0.613] }, prefix + 'apic[34]': { 'x':[-371.406,-373.446,-374.045,-375.082], 'y':[719.126,720.902,722.725,723.155], 'z':[-51.397,-50.313,-48.625,-47.527], 'diam':[1.933,1.234,1.234,1.234] }, prefix + 'soma': { 'x':[-297.841,-296.129,-294.417], 'y':[712.070,707.901,703.732], 'z':[-90.454,-89.770,-89.086], 'diam':[9.117,9.117,9.117] }, prefix + 'apic[44]': { 'x':[-365.089,-365.966,-366.538,-366.585,-366.373,-365.923], 'y':[732.271,732.384,732.702,732.198,732.093,731.595], 'z':[-3.214,-0.623,1.276,2.750,4.070,5.421], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'dend[7]': { 'x':[-300.796,-300.629,-299.381,-298.107,-296.935,-295.815,-297.338,-296.883,-295.403,-294.246,-293.197,-294.411,-295.384], 'y':[716.093,716.461,718.499,719.941,720.652,722.212,722.700,723.818,725.076,725.606,726.013,727.292,727.861], 'z':[-93.880,-97.054,-98.171,-97.995,-97.600,-97.415,-98.277,-100.250,-100.297,-100.731,-101.787,-103.411,-103.483], 'diam':[2.639,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847] }, prefix + 'apic[51]': { 'x':[-371.266,-370.307,-369.473], 'y':[727.211,726.650,726.158], 'z':[-30.669,-30.517,-29.787], 'diam':[0.792,0.442,0.442] }, prefix + 'dend[1]': { 'x':[-305.424,-304.042,-302.853,-301.401,-301.475,-300.185,-299.370,-298.648,-297.367,-296.733,-296.589,-296.564,-295.410,-294.247,-293.738,-293.850,-292.744,-292.152,-291.235,-291.015,-290.358,-290.719,-290.732,-289.687,-289.078,-288.530,-288.398,-288.768,-289.694,-291.113,-291.647,-290.869,-289.664,-289.045,-289.208,-289.575,-288.697,-287.855,-287.774,-287.870,-288.258,-287.918,-288.898,-289.985,-291.039,-290.634,-289.983,-289.708,-289.081,-288.893,-288.390,-288.861,-288.311,-289.781,-289.462,-289.582,-288.727,-287.871,-286.490,-286.391,-286.640,-286.069,-285.657,-286.066,-285.516,-284.870,-284.029,-283.113,-282.856,-282.601,-283.255,-282.010,-281.988,-281.796,-281.050,-281.154,-280.658,-279.152,-276.654,-275.812,-275.296,-275.576,-275.747,-274.804,-274.308,-273.451,-273.500,-274.257,-274.079,-273.230,-271.422,-270.993,-271.541,-271.849,-271.412,-271.399,-272.308,-272.909,-272.324,-271.094,-270.359,-270.459,-270.600,-269.870,-268.826,-267.621,-266.871,-265.858,-264.683,-264.741,-264.610,-263.893,-262.818,-262.468,-262.149,-261.449,-260.954,-260.040,-259.115,-257.052,-257.087,-256.522,-256.485,-256.763,-257.396,-257.902,-257.965,-257.688,-257.164], 'y':[657.846,657.791,657.893,657.814,657.019,656.482,656.563,655.737,654.890,654.083,653.043,651.499,651.047,650.917,649.724,648.757,647.762,646.524,645.859,645.206,644.845,645.449,645.536,645.856,645.241,645.518,645.860,646.617,645.696,645.313,644.061,643.927,643.242,642.669,641.119,639.853,638.957,638.146,636.354,635.362,635.940,635.534,634.786,633.929,632.889,632.434,632.389,631.401,630.361,628.448,627.315,625.868,625.358,623.596,622.671,622.106,620.987,619.894,618.554,617.114,615.494,614.186,612.488,611.281,610.310,609.927,610.067,608.745,607.589,606.562,604.617,604.482,603.054,602.084,602.371,600.515,599.739,600.062,600.860,600.380,599.933,598.475,597.205,596.701,595.451,594.543,593.467,591.978,592.247,590.802,590.391,589.646,588.469,588.695,587.992,587.962,587.366,585.678,584.292,583.218,582.187,581.145,579.203,578.520,578.122,577.192,576.552,576.048,576.075,575.140,574.006,573.708,574.957,575.148,575.296,575.967,576.599,576.663,576.532,576.820,576.110,576.379,576.314,575.493,574.309,573.159,572.010,571.139,568.656], 'z':[-86.353,-85.529,-85.081,-85.081,-84.108,-83.038,-82.162,-82.382,-82.418,-82.809,-82.436,-82.485,-82.104,-81.102,-80.896,-81.498,-81.182,-80.628,-80.760,-78.686,-77.214,-76.173,-74.987,-73.858,-72.479,-71.627,-70.503,-69.472,-69.583,-68.837,-67.928,-67.179,-66.627,-65.977,-66.335,-66.195,-65.980,-65.711,-65.095,-64.514,-63.447,-62.578,-61.868,-62.631,-62.426,-61.430,-60.244,-59.620,-58.465,-58.266,-56.615,-56.255,-55.507,-54.016,-53.469,-52.455,-51.468,-51.645,-50.379,-50.081,-47.948,-46.420,-45.712,-45.465,-44.915,-44.095,-43.288,-43.068,-43.100,-42.232,-41.208,-40.582,-39.689,-39.174,-38.423,-36.285,-35.165,-34.167,-33.331,-32.431,-31.376,-30.655,-30.141,-29.144,-28.431,-28.655,-28.135,-27.252,-25.953,-25.375,-25.486,-24.248,-22.363,-21.133,-20.396,-19.227,-18.697,-18.745,-18.398,-18.727,-19.260,-19.073,-18.625,-18.097,-17.512,-16.403,-16.166,-15.700,-14.756,-13.758,-14.177,-12.613,-9.986,-8.810,-7.134,-6.015,-4.744,-3.132,-2.168,-1.488,-0.362,0.628,1.713,3.046,2.575,1.905,1.594,1.117,0.154], 'diam':[0.706,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[89]': { 'x':[-379.163,-380.344], 'y':[723.461,724.015], 'z':[-44.007,-44.355], 'diam':[0.877,0.613] }, prefix + 'apic[47]': { 'x':[-372.570,-371.402,-370.112,-369.377], 'y':[730.628,729.969,729.136,728.596], 'z':[-21.545,-21.283,-21.133,-20.031], 'diam':[0.528,0.349,0.349,0.349] }, prefix + 'apic[135]': { 'x':[-403.344,-404.833,-405.705,-406.717], 'y':[738.048,739.098,739.762,739.828], 'z':[-43.286,-43.078,-42.839,-42.726], 'diam':[0.442,0.264,0.264,0.264] }, prefix + 'apic[91]': { 'x':[-368.650,-367.768,-366.866,-366.207,-366.046], 'y':[721.906,721.405,720.902,720.854,719.602], 'z':[-26.366,-26.208,-25.987,-24.898,-24.003], 'diam':[0.613,0.613,0.613,0.613,0.613] }, prefix + 'apic[5]': { 'x':[-364.098,-362.553], 'y':[717.234,717.930], 'z':[-39.614,-39.618], 'diam':[0.706,0.442] }, prefix + 'apic[75]': { 'x':[-389.242,-388.895,-388.210,-388.241,-388.144,-387.602,-387.273,-387.188,-386.756,-386.127,-385.543,-385.309,-385.814], 'y':[737.183,738.243,739.209,739.894,741.103,741.980,742.475,743.913,744.573,745.087,745.377,745.847,746.839], 'z':[-16.218,-12.900,-9.258,-7.620,-5.404,-3.018,-1.408,0.555,2.090,4.370,6.626,8.162,9.799], 'diam':[0.613,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528] }, prefix + 'apic[134]': { 'x':[-403.344,-402.905,-403.123,-403.736,-403.761,-404.028,-404.588,-405.416,-406.891,-407.591,-408.446,-409.223,-410.226,-411.601,-412.837], 'y':[738.048,738.367,738.915,738.747,739.105,739.715,740.437,741.376,741.669,742.078,741.766,742.791,742.719,742.498,741.671], 'z':[-43.286,-41.803,-40.778,-39.230,-38.238,-37.158,-36.282,-35.290,-34.281,-33.621,-32.949,-31.983,-31.129,-30.446,-29.820], 'diam':[0.442,0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[59]': { 'x':[-369.473,-370.332,-370.901,-371.241,-371.721,-372.168,-372.791,-373.585,-375.066,-375.746,-377.356,-378.685,-380.662,-381.393,-382.332], 'y':[726.158,726.320,727.055,727.076,727.030,727.498,728.226,728.932,730.561,730.807,731.445,731.398,732.496,733.263,734.055], 'z':[-29.787,-28.427,-27.366,-26.320,-25.163,-24.110,-23.312,-22.837,-21.048,-19.973,-19.261,-19.341,-18.252,-17.209,-15.994], 'diam':[0.442,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[129]': { 'x':[-398.619,-398.144,-396.833,-395.620,-394.129,-393.195,-391.656], 'y':[742.819,744.039,744.242,744.354,744.977,745.242,745.878], 'z':[-31.263,-30.283,-29.397,-29.496,-29.474,-29.020,-28.572], 'diam':[0.528,0.442,0.442,0.349,0.349,0.349,0.349] }, prefix + 'apic[121]': { 'x':[-395.218,-394.442,-392.681,-392.662,-392.284,-391.833,-391.694,-391.831,-391.358,-390.996,-390.826,-390.616,-390.174,-389.856,-389.471,-389.975,-389.094,-388.217], 'y':[740.049,740.470,742.068,742.957,743.347,744.253,744.763,745.305,746.466,746.931,747.742,748.447,749.095,749.411,749.985,751.045,751.172,750.404], 'z':[-36.531,-34.248,-32.785,-30.706,-29.154,-28.049,-26.876,-25.779,-24.940,-23.069,-22.177,-20.901,-18.759,-17.774,-16.807,-15.021,-13.488,-11.011], 'diam':[0.613,0.528,0.528,0.528,0.528,0.528,0.442,0.442,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[110]': { 'x':[-385.468,-387.572,-389.788,-391.006,-392.106,-393.081], 'y':[724.833,724.673,724.627,724.242,723.925,723.019], 'z':[-44.329,-45.429,-45.203,-43.626,-42.591,-41.593], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[106]': { 'x':[-402.452,-403.941,-404.936,-406.279,-407.311,-408.710,-410.147,-411.321,-412.445,-414.348,-415.722,-416.569,-417.334,-418.375], 'y':[733.848,734.898,734.288,735.318,736.342,736.824,737.289,737.867,738.070,738.011,738.010,738.637,738.109,737.668], 'z':[-36.376,-36.168,-36.322,-35.927,-35.044,-34.549,-34.458,-34.444,-34.199,-34.411,-33.981,-33.486,-32.905,-32.090], 'diam':[0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[84]': { 'x':[-399.225,-400.103,-401.110,-401.373,-401.164,-401.370,-402.264,-403.218,-403.813,-404.231,-404.721,-405.639,-406.121,-406.493], 'y':[733.084,733.197,733.796,734.209,734.694,735.575,736.320,736.465,737.091,736.996,737.832,737.431,737.661,737.447], 'z':[-25.820,-24.007,-23.049,-22.161,-21.072,-19.401,-18.681,-17.993,-17.246,-15.982,-14.545,-12.813,-11.146,-10.109], 'diam':[0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[138]': { 'x':[-395.800,-395.965,-396.134,-396.609,-397.328,-398.070,-399.140], 'y':[733.524,732.992,732.306,731.152,730.447,729.318,729.053], 'z':[-49.182,-50.780,-51.807,-53.077,-54.235,-54.980,-55.770], 'diam':[0.528,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[71]': { 'x':[-376.862,-378.454,-379.163], 'y':[723.172,723.508,723.461], 'z':[-46.307,-44.748,-44.007], 'diam':[0.706,0.877,0.877] }, prefix + 'apic[46]': { 'x':[-373.328,-374.274,-375.465], 'y':[731.957,734.034,733.094], 'z':[-19.495,-19.446,-19.025], 'diam':[0.349,0.349,0.349] }, prefix + 'apic[67]': { 'x':[-401.322,-403.370,-405.274,-406.226,-407.264,-408.568,-409.344,-409.866], 'y':[743.117,744.299,744.453,744.789,745.350,745.594,745.888,746.372], 'z':[-23.836,-23.740,-23.604,-22.887,-21.930,-21.080,-20.374,-19.399], 'diam':[0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[119]': { 'x':[-390.228,-390.976,-392.517,-393.740,-394.546], 'y':[733.473,734.446,735.745,736.353,737.443], 'z':[-48.183,-46.963,-44.675,-42.952,-41.888], 'diam':[0.792,0.613,0.613,0.613,0.528] }, prefix + 'apic[72]': { 'x':[-379.163,-380.181,-381.890,-382.134], 'y':[723.461,724.379,725.773,726.717], 'z':[-44.007,-42.596,-40.784,-40.431], 'diam':[0.877,0.613,0.706,0.706] }, prefix + 'dend[11]': { 'x':[-294.791,-293.140,-292.783,-290.713,-290.655,-290.188,-288.506,-287.280,-286.090,-284.912,-285.133,-283.721,-282.796,-282.623,-282.502], 'y':[710.004,713.461,715.652,716.458,716.473,716.604,717.441,717.570,718.762,718.895,719.742,719.885,720.735,721.054,721.731], 'z':[-86.422,-85.845,-85.220,-83.665,-82.255,-81.122,-81.177,-80.922,-80.404,-79.352,-78.063,-77.651,-76.237,-74.944,-73.572], 'diam':[1.056,0.970,0.792,0.792,0.792,0.706,0.706,0.706,0.613,0.613,0.613,0.613,0.613,0.613,0.613] }, prefix + 'apic[122]': { 'x':[-388.217,-386.515,-385.184,-383.909,-382.779], 'y':[750.404,748.284,748.026,747.797,747.609], 'z':[-11.011,-11.024,-12.036,-12.709,-13.393], 'diam':[0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[49]': { 'x':[-369.377,-368.228,-367.476,-366.543], 'y':[728.596,727.114,725.964,725.221], 'z':[-20.031,-20.326,-19.765,-18.258], 'diam':[0.349,0.264,0.264,0.264] }, prefix + 'dend[5]': { 'x':[-316.649,-318.958,-318.981,-319.333,-320.244,-321.413,-322.842,-324.481,-325.669,-326.839,-328.090,-329.139,-330.198,-331.295,-333.278,-332.747,-331.998,-332.347,-332.276,-332.415,-332.778,-333.568,-333.965,-333.579,-332.436,-332.341,-332.329,-333.431,-333.684,-334.871,-335.965,-336.832,-337.691,-337.277,-336.875,-336.846,-337.515,-337.397,-338.426,-339.039,-339.107,-339.004,-339.427,-340.204,-340.455,-341.852,-342.206,-342.441,-343.182,-344.209,-343.085,-342.254,-344.055,-344.947,-344.602,-343.618,-343.279,-342.908,-343.759,-345.362,-346.787,-347.350,-346.364,-347.149,-347.365,-347.640,-348.724,-349.710,-351.060,-350.389,-350.014,-351.023,-352.021,-351.911,-353.296,-354.248,-354.893,-356.258,-357.746,-358.774,-359.466,-359.599,-361.041,-362.928,-364.470,-365.607,-366.839,-367.907,-369.602,-371.029,-372.248,-372.467,-372.430,-374.338,-375.407,-376.527,-377.433,-378.730,-379.878,-380.990,-381.925,-383.621,-384.549,-386.062,-386.751,-387.244,-388.160,-389.073,-390.029,-390.853,-391.545,-392.577,-393.437,-393.721,-395.070,-396.529,-397.119,-397.932,-398.996,-399.741,-401.409,-402.944,-404.120,-404.359,-405.317,-406.802,-407.860,-409.152,-410.414,-411.510,-412.517,-413.068,-413.433,-413.952,-414.417,-414.571,-414.548,-414.383], 'y':[714.484,716.593,718.184,716.186,717.644,718.233,719.091,719.448,719.313,719.418,720.599,721.048,721.170,721.395,721.354,722.579,723.203,723.854,724.553,724.896,725.306,725.287,725.570,725.498,726.193,727.513,728.054,728.854,729.625,729.489,731.018,731.739,732.271,732.529,734.471,736.637,737.154,738.074,738.658,739.201,739.808,742.433,743.500,743.371,744.331,744.318,744.245,745.964,746.608,747.151,747.645,748.057,749.000,750.458,751.448,752.148,753.193,754.235,755.250,755.168,754.970,756.855,757.453,757.620,757.751,758.042,758.596,758.589,759.962,760.707,761.837,762.908,763.340,763.650,764.305,765.202,766.530,768.380,769.992,770.601,771.804,772.282,772.908,773.040,773.002,772.898,772.962,772.991,773.544,773.667,773.671,774.578,775.392,775.525,775.479,776.353,776.592,776.886,776.758,776.634,777.459,778.340,778.455,779.689,780.327,780.651,780.483,780.313,781.298,781.902,783.166,783.597,784.795,784.952,784.832,784.678,784.742,785.722,786.506,786.587,787.436,788.051,788.074,787.471,788.881,789.500,789.952,790.847,791.594,791.883,791.638,791.490,792.315,793.171,793.332,794.332,794.514,795.050], 'z':[-111.225,-112.096,-112.778,-112.952,-112.086,-112.363,-112.727,-112.864,-113.338,-113.360,-113.583,-113.837,-114.419,-114.901,-115.908,-116.220,-117.276,-118.195,-118.920,-120.715,-121.987,-122.726,-123.758,-125.640,-127.540,-128.067,-129.492,-130.248,-131.623,-132.098,-132.665,-133.357,-134.616,-135.596,-135.639,-135.664,-136.645,-135.985,-135.773,-136.517,-137.608,-138.234,-138.390,-139.128,-140.062,-140.115,-141.237,-142.085,-143.330,-144.870,-145.470,-146.247,-147.042,-148.025,-148.484,-149.022,-150.634,-151.207,-153.307,-153.989,-154.985,-155.852,-156.962,-157.833,-159.045,-160.161,-160.904,-161.222,-162.184,-162.331,-163.013,-163.759,-164.807,-166.084,-167.110,-166.909,-166.093,-166.035,-165.757,-165.335,-165.266,-164.286,-164.368,-164.008,-164.724,-164.839,-165.324,-165.097,-165.881,-166.721,-167.310,-168.314,-169.388,-170.169,-170.854,-172.060,-172.520,-173.703,-174.731,-175.178,-175.785,-176.946,-178.194,-179.466,-180.153,-181.245,-182.477,-183.588,-185.357,-185.715,-186.803,-187.278,-189.062,-191.056,-193.691,-194.063,-195.156,-197.145,-197.544,-199.456,-200.944,-202.405,-203.334,-204.265,-205.276,-206.048,-206.190,-206.854,-207.607,-208.433,-209.774,-211.073,-212.885,-214.262,-216.731,-219.673,-221.165,-222.107], 'diam':[1.056,0.792,0.792,0.792,0.792,0.792,0.792,0.613,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[97]': { 'x':[-362.285,-362.051,-362.069,-362.465,-362.054], 'y':[721.533,722.002,722.743,722.616,725.244], 'z':[-9.374,-7.838,-6.037,-4.512,-3.277], 'diam':[0.442,0.349,0.349,0.349,0.349] }, prefix + 'dend[9]': { 'x':[-294.830,-295.019,-296.705,-298.463,-299.485,-300.396,-300.541,-300.711,-300.967,-301.287,-302.167,-303.836,-304.771,-305.265,-305.334,-304.783,-304.938,-306.477,-306.579,-306.605,-306.689,-307.224,-308.364,-309.162,-309.453,-309.910,-311.716,-313.958,-314.448,-313.862,-313.425,-314.097,-315.684,-317.108,-317.128,-317.402,-317.895,-319.382,-320.558,-320.194,-321.449,-322.181,-323.190,-323.992,-325.336,-326.664,-328.158,-329.705,-330.207,-330.231,-329.519,-328.997,-329.664,-330.116,-329.647,-328.969,-328.500,-330.009,-330.995,-331.880,-332.206,-330.894,-330.321,-330.754,-331.398,-330.727,-330.165,-329.455,-329.211,-329.932,-330.788,-331.039,-330.200,-329.123,-330.442,-331.822,-332.370,-332.965,-333.966,-335.342,-336.305,-337.337,-338.062,-337.802,-336.979,-337.241,-337.839,-337.862,-337.650,-339.262,-340.757,-340.760,-339.830,-340.562,-341.519,-342.628,-343.668,-343.146,-343.413,-345.207,-345.814,-346.727,-348.098,-349.362,-350.359,-350.885,-350.409,-350.328,-350.100,-350.166,-351.863,-352.672,-352.830,-351.990,-351.964,-352.901,-353.631,-354.191,-353.962,-353.052,-352.448,-352.575,-352.585,-352.488,-352.743,-353.489,-352.411,-351.461,-351.838,-353.632,-354.914,-356.387,-357.193,-358.372,-359.149,-360.096,-360.043,-359.621,-359.522,-359.528,-359.507,-359.366,-358.791,-357.691,-358.258,-359.288,-360.272,-362.296,-361.057,-361.591,-360.769,-359.677,-359.492,-360.772,-362.029,-363.020,-362.052,-362.053,-362.828,-364.067,-365.062,-366.401,-368.134,-369.346,-370.330,-370.535,-371.044,-371.190,-371.517,-373.030,-374.155,-376.178,-377.205,-379.135,-379.908,-379.591,-381.050,-382.671,-384.904,-385.771,-386.850,-387.624,-389.130,-390.054,-390.873,-389.911,-390.880,-392.670,-393.909,-395.051,-394.087,-393.367,-394.004,-394.952,-395.290,-394.891,-394.160,-393.017,-391.815,-391.271,-392.436,-393.456,-393.611,-392.471,-392.044,-392.390,-392.691,-393.166,-395.432,-394.087,-392.539,-391.980,-391.454,-391.349,-393.052,-394.609,-394.727,-394.135,-392.862,-391.741,-391.197,-392.902,-394.211,-394.537,-395.048,-393.304,-393.007,-393.454,-394.327,-395.345,-395.379,-394.668,-393.616,-392.766,-391.684,-391.898,-393.057,-393.293,-392.370,-393.288,-395.177,-395.728,-394.366,-394.033,-395.375,-396.420,-397.630,-399.400,-400.338,-401.494,-402.032,-402.541,-402.933,-404.294,-405.208,-406.295,-407.326,-408.671,-409.401,-411.009,-410.883,-411.841,-414.295,-415.304,-416.806,-417.313,-417.892,-419.029,-420.457,-420.779,-420.403,-421.253,-422.369,-421.540,-421.434,-421.200,-420.936,-421.233,-422.947,-424.726,-425.650,-426.884,-426.475,-426.529,-427.484,-428.742,-429.364,-429.870,-430.119,-428.618,-430.383,-431.852,-432.922,-433.970,-433.098,-432.312,-431.996,-431.601,-432.153,-431.739,-433.528,-432.767,-431.738,-432.515,-432.570,-433.421,-433.545,-432.803,-432.798,-433.210,-433.374,-432.580,-433.241,-433.819,-434.415,-434.811,-434.381,-434.951,-437.417,-438.549,-439.545,-440.883,-441.895,-443.236,-443.498,-444.618,-445.658,-447.702,-448.539,-449.584,-451.291,-452.933,-454.340,-456.504,-459.001,-460.314,-461.831,-463.193,-465.030,-466.279,-468.057,-469.173,-470.487,-471.485,-472.819,-473.561,-474.700,-475.830,-475.782,-476.661,-477.651,-478.943,-479.486,-480.410,-479.879,-480.702,-481.437,-480.497,-480.641,-480.652,-482.521,-483.324,-484.395,-485.971,-486.452], 'y':[745.482,744.352,743.219,743.800,744.449,746.007,746.859,747.858,749.656,750.480,751.048,753.750,754.930,756.068,756.744,758.140,759.155,760.524,761.354,762.503,763.005,763.440,763.998,764.570,764.898,764.869,764.346,764.319,765.107,766.001,767.422,769.417,769.880,770.429,771.439,772.813,775.088,776.363,777.119,779.079,779.481,780.412,780.724,781.609,781.305,779.904,782.475,783.082,783.100,784.517,785.215,786.928,787.447,787.683,788.110,788.990,789.803,789.930,790.079,790.062,790.946,791.931,793.595,793.963,794.357,795.361,796.090,796.402,796.803,797.787,798.493,799.800,800.938,801.769,802.525,802.648,802.886,802.852,803.499,804.297,804.842,805.280,806.123,807.350,807.879,808.693,809.383,810.764,811.272,811.338,811.427,811.822,812.431,813.547,814.073,814.577,815.709,816.688,817.727,819.067,819.690,819.794,817.293,818.399,818.671,820.298,822.874,823.842,824.717,825.499,825.296,825.238,826.200,826.766,827.593,827.854,828.093,828.450,829.209,830.051,830.441,831.215,831.978,832.821,833.120,834.227,835.383,836.194,836.766,837.168,836.616,837.484,838.267,838.488,838.633,839.115,840.373,841.928,843.574,844.835,846.355,847.361,848.759,850.050,850.851,852.153,852.547,853.898,855.096,855.972,856.997,857.214,857.943,857.957,858.348,858.326,860.524,861.790,862.292,862.392,862.175,862.586,862.080,861.735,861.481,862.462,864.487,865.461,866.392,867.722,868.078,868.574,868.716,868.865,869.618,869.901,870.340,870.872,870.916,872.019,872.045,873.016,873.280,873.350,873.508,874.412,875.846,876.039,876.271,877.669,878.962,879.867,880.266,880.881,881.525,883.278,884.233,884.794,885.859,887.392,887.771,888.566,889.325,890.103,890.860,891.566,892.443,892.672,893.165,894.595,895.287,896.465,896.900,898.008,899.305,900.586,900.818,901.506,902.470,902.988,904.741,905.246,906.312,908.023,908.740,910.493,911.581,912.613,912.874,913.624,915.199,916.316,916.536,916.706,917.052,918.717,919.789,920.528,921.368,921.923,922.993,923.102,923.804,924.601,924.933,924.925,925.005,925.497,925.938,926.734,927.705,928.522,928.871,929.140,929.739,929.885,929.840,929.580,930.295,930.619,930.764,931.272,931.176,931.755,931.502,932.505,933.405,933.900,934.629,935.894,937.165,937.775,939.299,940.168,941.640,943.283,944.239,946.413,946.528,946.015,945.659,947.900,948.609,949.588,949.989,949.789,949.972,950.591,950.699,952.564,952.515,953.117,953.166,953.969,955.103,956.117,957.570,959.134,960.239,961.239,961.663,962.324,963.749,963.905,961.947,962.811,964.146,965.825,966.270,966.956,967.559,968.192,968.472,968.900,970.231,970.887,971.103,971.058,971.829,972.074,971.811,972.336,973.337,975.128,976.087,976.664,976.993,976.606,976.604,977.364,977.966,979.931,980.712,980.760,981.149,982.842,983.566,984.157,984.343,984.565,984.960,984.705,984.286,984.373,984.471,984.652,984.938,984.708,985.375,985.914,985.511,986.685,988.974,992.202,993.280,994.033,995.336,997.476,998.370,999.680,1001.725,1002.479,1002.545,1004.289,1006.041], 'z':[-106.725,-109.001,-108.739,-108.583,-108.530,-109.027,-110.074,-110.539,-111.014,-111.748,-111.112,-109.931,-109.796,-110.057,-111.248,-111.649,-112.218,-110.520,-109.243,-108.272,-107.280,-106.377,-106.834,-105.948,-104.900,-103.802,-103.701,-104.527,-104.958,-105.431,-105.847,-105.773,-104.451,-104.119,-105.376,-105.796,-106.933,-107.209,-107.178,-107.401,-107.662,-107.640,-107.868,-107.973,-108.780,-111.078,-111.654,-112.237,-113.297,-113.470,-114.266,-114.728,-115.497,-116.532,-117.827,-118.942,-119.958,-120.840,-120.978,-121.715,-122.088,-122.474,-123.397,-125.086,-127.132,-128.463,-128.913,-129.988,-131.190,-131.565,-132.212,-133.454,-133.032,-133.007,-133.891,-134.875,-136.128,-137.427,-138.890,-139.330,-139.656,-140.119,-141.324,-141.272,-140.139,-141.090,-141.841,-143.167,-144.467,-143.976,-143.472,-144.685,-145.027,-145.724,-145.835,-145.715,-146.900,-147.905,-148.020,-146.709,-145.856,-145.334,-146.157,-146.100,-146.461,-146.981,-148.361,-149.509,-150.767,-148.395,-147.469,-146.155,-144.677,-143.876,-142.637,-142.195,-141.415,-140.370,-138.440,-136.463,-135.128,-133.322,-131.525,-129.821,-127.852,-126.957,-126.535,-126.276,-125.204,-124.914,-122.076,-120.340,-119.029,-119.870,-120.930,-122.629,-123.057,-123.305,-122.765,-121.249,-120.840,-121.504,-122.923,-123.271,-121.958,-121.172,-120.607,-119.529,-119.662,-119.014,-118.052,-117.621,-116.620,-115.651,-114.760,-114.241,-113.129,-111.731,-111.145,-110.962,-111.166,-110.723,-110.574,-110.537,-110.832,-111.761,-112.573,-114.296,-115.125,-114.001,-112.972,-113.209,-114.375,-114.555,-113.352,-112.165,-111.832,-112.856,-113.402,-112.279,-110.489,-111.888,-113.526,-114.229,-115.044,-117.066,-117.402,-118.132,-118.265,-117.808,-117.967,-118.300,-119.307,-121.780,-122.981,-123.681,-124.349,-124.124,-123.505,-123.657,-123.993,-124.409,-125.114,-125.915,-126.492,-127.790,-128.509,-129.527,-129.894,-130.940,-131.949,-132.699,-133.438,-134.220,-133.799,-135.302,-136.435,-137.355,-137.192,-136.527,-135.854,-135.750,-136.588,-136.873,-137.603,-137.112,-137.211,-138.369,-138.829,-139.236,-139.855,-139.136,-137.927,-137.191,-136.999,-137.042,-138.456,-139.750,-139.278,-138.564,-137.944,-138.976,-139.081,-140.226,-141.159,-141.426,-141.461,-141.932,-142.262,-142.554,-143.842,-146.616,-147.514,-147.864,-149.089,-149.461,-149.851,-150.039,-150.895,-151.377,-150.339,-148.826,-149.043,-148.904,-148.525,-146.954,-145.606,-144.923,-144.310,-144.874,-144.941,-145.590,-145.796,-145.791,-144.587,-144.171,-145.085,-144.277,-143.979,-143.878,-143.040,-142.802,-143.534,-142.986,-141.908,-141.910,-143.482,-144.777,-146.473,-146.765,-147.099,-147.926,-148.816,-149.406,-149.876,-150.466,-151.011,-151.435,-150.980,-149.861,-149.800,-150.081,-149.384,-148.444,-147.844,-146.951,-148.078,-149.628,-150.950,-151.670,-152.860,-153.838,-154.822,-156.033,-157.488,-159.356,-160.253,-161.386,-162.532,-162.487,-162.628,-162.317,-161.640,-161.902,-162.831,-162.415,-161.915,-161.242,-160.431,-161.141,-161.516,-160.725,-161.089,-160.943,-161.476,-160.734,-160.286,-160.674,-159.941,-160.474,-160.646,-160.657,-160.211,-159.288,-159.365,-160.144,-161.011,-161.364,-160.617,-159.636,-159.971,-159.261,-158.119,-157.558,-157.351,-156.804,-156.222,-155.675,-155.124,-155.682,-157.387,-157.305,-157.856,-157.899,-158.404], 'diam':[1.584,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.141,1.141,1.141,1.056,1.056,1.056,1.056,1.056,1.056,1.056,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,1.141,1.141,1.141,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.706,0.706,0.706,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.528,0.528,0.528,0.528] }, prefix + 'apic[133]': { 'x':[-395.800,-396.659,-398.062,-399.762,-401.076,-401.844,-402.367,-402.802,-403.344], 'y':[733.524,734.243,734.271,734.799,735.448,736.263,736.813,737.474,738.048], 'z':[-49.182,-48.793,-48.810,-47.874,-46.669,-45.895,-45.210,-44.141,-43.286], 'diam':[0.528,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442] }, prefix + 'apic[52]': { 'x':[-369.473,-368.533], 'y':[726.158,725.556], 'z':[-29.787,-29.616], 'diam':[0.442,0.349] }, prefix + 'apic[60]': { 'x':[-375.585,-374.330,-373.399], 'y':[726.541,725.473,724.744], 'z':[-37.841,-38.464,-38.753], 'diam':[0.613,0.349,0.349] }, prefix + 'apic[29]': { 'x':[-363.474,-361.593,-360.236,-356.998,-355.747,-354.171], 'y':[708.950,709.223,709.329,710.767,711.430,711.753], 'z':[-30.479,-31.285,-31.665,-31.946,-31.404,-31.184], 'diam':[0.442,0.442,0.442,0.442,0.442,0.442] }, prefix + 'apic[83]': { 'x':[-396.249,-397.668,-398.580,-399.275,-398.445,-399.225], 'y':[731.890,732.937,732.567,731.888,733.471,733.084], 'z':[-29.596,-29.295,-29.020,-28.390,-27.647,-25.820], 'diam':[0.442,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[141]': { 'x':[-405.528,-407.064,-407.997,-409.379,-410.668,-413.057,-414.735,-415.819], 'y':[741.655,740.806,741.126,741.189,741.166,742.567,742.282,742.290], 'z':[-49.825,-48.485,-47.945,-47.974,-48.236,-47.509,-46.876,-46.560], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[32]': { 'x':[-374.047,-375.377,-376.578,-376.863,-376.698,-376.712,-375.809,-375.324,-373.768,-373.132,-372.237,-370.628,-368.896,-365.873], 'y':[713.597,714.397,714.061,713.488,713.107,711.757,711.765,711.906,711.252,711.417,711.263,710.982,709.197,709.878], 'z':[-36.870,-36.237,-35.099,-34.175,-33.014,-30.618,-29.134,-28.005,-27.161,-25.704,-24.674,-24.485,-24.259,-25.370], 'diam':[1.056,0.613,0.613,0.613,0.613,0.528,0.528,0.528,0.528,0.528,0.528,0.264,0.264,0.264] }, prefix + 'apic[10]': { 'x':[-361.157,-360.269,-359.369,-358.779,-357.548,-356.271], 'y':[717.776,716.766,715.817,715.534,714.767,714.283], 'z':[-40.571,-41.634,-42.525,-43.829,-45.002,-46.011], 'diam':[0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'dend[3]': { 'x':[-298.473,-300.796], 'y':[711.113,716.093], 'z':[-91.333,-93.880], 'diam':[2.111,2.639] }, prefix + 'apic[96]': { 'x':[-356.531,-355.340,-355.120,-355.284,-355.345,-355.552,-355.564,-355.514,-356.372,-356.873,-357.634,-358.764,-359.947,-359.490], 'y':[719.306,718.169,718.525,719.169,719.818,720.428,721.228,721.833,721.206,721.586,722.125,722.048,723.032,725.088], 'z':[-4.255,-4.066,-2.835,-1.689,-0.632,0.534,1.869,2.673,3.478,5.167,6.038,7.003,8.150,8.067], 'diam':[0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[57]': { 'x':[-365.713,-366.883,-367.364,-367.951,-367.590,-366.086,-365.206,-365.642], 'y':[723.216,724.451,724.954,725.173,725.573,726.170,726.953,728.929], 'z':[-29.929,-28.596,-27.811,-26.825,-25.103,-24.034,-21.788,-19.918], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[14]': { 'x':[-349.325,-348.724,-348.591,-347.995,-347.016], 'y':[719.230,719.576,719.953,720.240,720.597], 'z':[-30.168,-28.356,-27.211,-26.319,-25.730], 'diam':[0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[101]': { 'x':[-380.344,-381.313,-383.489], 'y':[724.015,724.347,724.129], 'z':[-44.355,-45.068,-44.607], 'diam':[0.613,0.613,0.613] }, prefix + 'apic[86]': { 'x':[-382.134,-383.162,-383.728], 'y':[726.717,727.850,729.654], 'z':[-40.431,-37.872,-36.522], 'diam':[0.706,0.264,0.264] }, prefix + 'apic[88]': { 'x':[-383.728,-385.207,-385.674,-387.048,-388.106,-388.561,-388.470,-389.568], 'y':[729.654,730.487,731.331,733.054,734.254,735.086,734.935,735.387], 'z':[-36.522,-36.485,-37.028,-36.814,-36.334,-37.654,-39.407,-40.369], 'diam':[0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'dend[10]': { 'x':[-294.830,-295.640,-295.450,-294.694,-294.726,-293.419,-294.203,-295.289,-295.734,-296.180,-295.141,-293.543,-292.051,-290.781,-289.723,-289.378,-288.088,-286.941,-285.542,-284.092,-283.645,-284.772,-285.999,-287.526,-288.461,-287.967,-287.483,-286.755,-286.283,-287.194,-287.998,-287.085,-285.126,-284.878,-285.347,-285.881,-286.782,-287.650,-289.126,-290.105,-289.804,-289.077,-288.715,-287.721,-287.381,-287.442,-288.738,-289.723,-289.561,-288.807,-287.963,-287.514,-286.662,-284.561,-282.570,-281.217,-279.802,-280.861,-279.524,-278.765,-278.790,-278.763,-279.020,-279.999,-281.548,-282.640,-284.015,-284.705,-286.890,-288.634,-289.180,-288.230,-287.276,-287.563,-288.513,-289.974,-290.591,-290.583,-290.845,-292.186,-291.397,-290.192,-288.949,-290.005,-290.912,-291.519,-292.976,-292.787,-291.593,-290.416,-290.066,-290.697,-292.022,-293.006,-294.076,-294.929,-296.013,-294.622,-293.443,-291.774,-290.253,-290.273,-290.721,-290.340,-290.745,-290.617,-290.264,-290.234,-290.235,-290.868,-292.060,-293.410,-292.706,-291.754,-290.734,-291.977,-291.036,-290.427,-291.333,-290.860,-289.640,-289.288,-287.986,-289.078,-289.939,-290.730,-289.432,-288.759,-288.180,-288.007,-288.023,-288.613,-286.807,-285.979,-286.101,-286.037,-285.054,-284.233,-282.866,-281.557,-280.836,-280.910,-281.131,-281.975,-282.513,-282.688,-282.261,-281.770,-280.603,-279.859,-280.361,-282.253,-283.264,-282.732,-282.137,-281.988,-282.627,-283.196,-284.436,-285.389,-284.651,-284.775,-285.236,-286.796,-286.976,-288.348,-289.963,-291.327,-291.775,-293.295,-294.377,-293.032,-292.165,-291.113,-290.569,-291.294,-292.152,-292.846,-293.153,-294.779,-295.386,-296.052,-295.753,-295.155,-295.122,-294.939,-294.601,-293.442,-292.931,-293.528,-294.743,-295.864,-296.547,-295.360,-294.388,-295.357,-295.475,-294.593,-294.070,-293.536,-293.127,-294.477,-296.176,-297.756,-296.429,-296.297,-297.212,-298.384,-299.767,-300.285,-299.916,-299.912,-298.850,-298.943,-299.973,-300.784,-299.826,-297.522,-296.326,-295.507,-295.883,-296.436,-296.757,-296.521,-295.509,-295.312,-294.807,-294.535,-293.400,-292.763,-292.063,-291.696,-291.394,-291.458,-290.967,-290.335,-289.100,-287.852,-286.254,-287.387,-287.607,-286.741,-286.054,-286.971,-287.103,-286.690,-286.365,-285.563,-285.540,-286.532,-285.872,-284.207,-284.595,-285.816,-284.811,-283.500,-282.449,-281.391,-280.330,-279.739,-280.892,-281.820,-281.522,-280.317,-279.438,-279.451,-279.025,-278.612,-277.884,-277.873,-278.237,-279.036,-280.243,-279.809,-280.535,-282.726,-282.178,-281.502,-280.590,-279.864,-280.728,-281.723,-281.630,-279.935,-279.132,-278.168,-278.580,-279.378,-278.334,-277.403,-276.584,-275.921,-275.876,-276.302,-277.218,-277.648,-277.335,-276.456,-274.987,-273.699,-273.814,-273.212,-272.275,-271.599,-271.412,-271.380,-270.604,-270.203,-269.480,-268.753,-268.081,-267.393,-267.292,-266.883,-267.076,-265.014,-264.290,-264.039,-262.618,-261.282,-262.425,-262.780,-263.712,-264.416,-265.944,-265.798,-266.823,-268.222,-268.103,-269.320,-271.102,-271.123,-272.291,-273.089,-273.453,-273.855,-274.027,-274.532,-273.968,-273.611,-273.352,-273.484,-274.913,-275.586,-276.510,-277.437,-278.891,-279.648,-280.840,-281.086], 'y':[745.482,746.323,747.646,748.524,749.509,750.408,750.717,750.473,751.163,751.672,752.517,753.937,754.461,754.845,755.100,755.777,756.626,757.502,758.334,759.625,760.588,761.357,761.442,761.090,760.913,760.945,762.316,762.545,762.904,764.097,764.358,764.552,765.070,766.644,767.398,768.069,769.216,769.587,769.847,770.637,771.453,773.289,774.297,774.342,774.418,774.815,775.468,776.002,776.513,777.358,778.200,778.183,778.263,778.834,779.155,780.377,781.161,781.504,782.205,782.355,783.203,783.838,783.955,783.918,785.194,785.959,785.531,785.061,786.160,786.973,787.759,788.539,788.709,789.764,790.141,790.409,790.725,792.382,794.290,794.376,795.120,796.156,796.591,796.930,797.444,797.650,798.326,800.033,801.091,801.919,802.892,802.836,802.817,802.335,802.608,802.521,802.740,803.561,804.290,804.856,805.304,805.871,807.286,808.349,809.460,810.533,812.071,812.684,814.192,814.926,815.572,815.459,816.363,816.928,818.213,819.281,820.935,821.483,822.190,823.709,824.308,825.288,826.651,827.713,828.176,828.912,829.962,830.335,832.120,833.286,834.188,835.165,836.239,836.385,837.249,838.348,839.166,840.376,841.048,841.790,842.943,843.781,843.652,843.947,844.110,844.899,846.084,847.766,849.226,849.725,850.301,851.091,851.636,853.324,854.041,855.905,856.635,856.565,856.063,856.572,857.087,858.036,858.036,858.056,859.055,859.708,860.245,860.190,859.869,859.759,859.923,860.517,861.216,862.943,864.205,864.936,865.443,865.994,865.909,866.688,867.465,868.476,869.473,870.247,871.910,872.280,873.615,874.409,875.413,876.129,875.783,875.408,876.724,877.666,878.364,879.340,880.762,881.410,882.182,882.953,884.001,884.930,885.758,887.083,888.550,889.544,889.899,889.804,890.602,891.153,893.699,894.523,895.364,896.593,896.473,896.544,897.133,898.282,899.547,899.869,900.375,900.356,901.662,902.902,904.082,906.131,906.871,907.288,908.810,909.763,910.461,912.949,914.172,914.976,915.570,916.028,916.328,917.520,918.260,919.557,920.576,921.229,922.115,922.527,923.203,924.092,925.082,927.253,927.829,928.464,929.980,931.387,932.136,932.684,933.712,934.132,934.658,935.104,935.552,936.227,936.293,936.471,937.334,938.134,938.779,940.212,942.746,943.796,944.968,946.523,946.690,946.777,947.102,948.325,949.385,950.040,950.809,951.698,952.073,953.409,954.081,953.945,953.993,955.051,955.992,956.772,957.517,957.635,958.779,959.302,960.151,960.590,962.092,962.801,963.434,964.650,965.940,966.991,967.431,968.398,970.102,970.935,971.441,972.836,973.836,974.492,976.023,977.468,979.159,980.782,981.800,982.252,982.646,983.729,984.908,986.277,987.098,988.355,989.613,990.823,992.339,993.678,994.871,995.314,996.185,996.949,998.115,998.006,998.924,999.465,999.977,1002.189,1003.349,1004.127,1004.972,1006.830,1007.091,1008.878,1007.774,1008.625,1009.830,1011.138,1013.236,1013.463,1013.742,1014.491,1015.413,1016.021,1018.192,1019.920], 'z':[-106.725,-104.402,-104.064,-105.445,-106.001,-106.473,-104.117,-103.170,-102.444,-101.508,-101.794,-102.603,-103.570,-103.782,-102.764,-101.798,-100.892,-101.175,-100.829,-100.758,-101.246,-102.691,-103.914,-104.208,-103.566,-102.440,-101.815,-100.972,-100.156,-98.965,-97.658,-96.445,-96.068,-93.927,-91.931,-90.748,-90.137,-90.569,-90.075,-89.299,-88.788,-88.856,-89.000,-89.185,-87.971,-86.985,-86.747,-87.989,-89.510,-89.606,-88.312,-86.854,-85.780,-85.595,-85.738,-85.687,-85.357,-83.492,-82.024,-79.331,-77.932,-76.449,-75.302,-74.549,-74.478,-74.313,-73.870,-71.212,-70.170,-69.143,-68.174,-66.429,-65.554,-64.304,-64.075,-64.588,-65.380,-65.188,-64.173,-64.129,-64.564,-65.174,-64.485,-63.024,-62.444,-61.532,-61.997,-61.327,-60.672,-60.399,-59.243,-57.332,-55.693,-53.745,-53.310,-52.796,-53.290,-52.888,-53.648,-54.069,-53.707,-52.611,-51.893,-51.522,-50.270,-49.679,-50.393,-51.238,-50.596,-48.377,-47.794,-46.851,-45.562,-45.900,-45.350,-43.929,-43.680,-42.775,-41.480,-40.714,-40.116,-40.549,-40.557,-39.679,-39.453,-39.636,-38.637,-37.882,-37.865,-38.062,-36.700,-35.705,-36.511,-35.637,-34.191,-33.022,-33.222,-34.066,-34.252,-33.754,-33.343,-32.566,-30.887,-28.946,-27.472,-26.474,-25.632,-27.004,-27.216,-26.436,-25.253,-25.039,-23.424,-22.626,-23.425,-22.851,-20.523,-19.297,-18.398,-17.367,-15.204,-14.075,-12.833,-12.804,-13.841,-13.836,-13.393,-12.565,-10.576,-9.190,-8.195,-7.708,-7.581,-8.690,-9.316,-8.804,-7.427,-6.598,-5.595,-4.446,-4.042,-2.491,-2.252,-3.511,-3.892,-2.930,-2.765,-2.181,-1.357,-0.847,-0.820,-0.324,0.825,0.517,0.975,2.527,3.594,3.823,3.353,2.890,3.022,3.419,2.312,0.806,-0.126,-0.806,-1.147,-0.974,-1.390,-3.061,-2.988,-1.294,-0.937,0.570,0.398,1.515,2.532,2.299,2.493,3.130,4.770,6.001,7.164,7.421,6.901,7.835,9.644,10.954,10.951,11.536,12.329,12.501,13.680,14.802,13.975,13.243,13.209,12.701,12.519,11.419,10.613,9.228,9.590,9.142,8.299,7.389,7.281,7.670,6.708,6.404,6.254,5.790,4.953,4.958,5.346,5.327,5.203,5.285,5.377,4.556,3.731,2.570,1.539,1.672,1.891,3.192,4.060,4.201,4.478,5.106,6.028,7.042,7.709,8.668,9.557,9.323,10.453,10.808,11.682,11.403,12.586,13.792,15.628,16.146,16.291,16.414,17.735,18.413,19.380,19.355,19.484,20.120,21.858,23.521,23.897,25.154,24.176,24.435,24.281,24.012,23.389,21.977,21.220,21.698,22.128,23.446,22.439,23.721,22.972,22.885,22.978,23.583,25.097,24.869,24.064,25.024,24.068,23.733,24.628,23.602,23.076,22.187,21.743,20.545,19.059,18.104,17.099,16.873,15.830,14.866,13.575,13.336,13.575,12.418,11.819,11.885,10.431,10.393,10.053,9.326,8.989,8.659,8.666,10.176,11.015,11.316,11.096,10.590,9.106,9.400], 'diam':[1.584,1.405,1.405,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.056,1.056,1.056,1.056,1.141,1.141,1.141,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,0.877,0.877,0.877,0.877,0.877,0.877,0.970,1.056,1.234,1.234,1.234,1.234,1.234,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.405,1.405,1.141,1.141,1.141,1.056,1.056,1.056,1.056,1.056,1.056,1.056,0.877,0.877,0.877,0.877,0.877,0.877,0.877,0.877,0.877,0.877,0.877,0.877,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,1.056,1.056,1.056,1.056,1.056,1.056,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,1.141,1.141,1.141,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.706,0.706,0.706,0.706,0.613,0.613,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528] }, prefix + 'apic[53]': { 'x':[-368.533,-367.013,-365.713], 'y':[725.556,724.272,723.216], 'z':[-29.616,-30.325,-29.929], 'diam':[0.349,0.349,0.349] }, prefix + 'apic[1]': { 'x':[-307.800,-309.439,-311.572,-313.045,-313.279,-315.185,-316.904,-318.742,-320.373,-321.410,-321.222,-321.668,-323.198,-324.584,-325.879,-326.960,-327.741,-328.353,-328.294,-328.457,-329.281,-330.732,-331.515,-332.332,-333.168,-334.237,-336.066,-337.787,-339.737,-340.831,-341.487,-342.366,-342.826,-343.405,-344.321,-345.188,-346.907,-348.249,-349.687,-351.307,-352.654,-354.178,-355.769,-356.813,-358.275,-359.786,-361.096,-363.107,-364.527,-365.814], 'y':[701.708,701.662,700.645,700.201,700.482,701.080,700.706,700.313,700.961,702.195,702.784,703.712,703.310,704.513,704.891,705.222,704.637,704.477,704.542,704.697,705.028,704.913,704.687,704.686,704.855,705.066,705.481,705.046,704.039,703.520,704.217,705.076,705.891,706.454,707.485,708.339,709.030,709.653,710.322,710.922,710.819,711.232,711.320,711.501,712.310,713.047,714.291,714.824,716.382,717.747], 'z':[-88.086,-90.825,-90.843,-89.633,-88.540,-88.394,-88.943,-89.127,-88.912,-87.526,-85.778,-84.205,-81.907,-81.152,-80.442,-79.474,-78.447,-77.487,-76.303,-74.644,-73.606,-74.331,-75.064,-75.881,-76.500,-77.378,-78.038,-78.291,-77.378,-76.514,-75.711,-74.685,-73.416,-70.455,-68.446,-67.427,-67.078,-67.054,-67.400,-68.040,-67.660,-67.217,-66.905,-66.742,-65.842,-64.732,-63.742,-61.937,-60.204,-58.901], 'diam':[2.111,2.290,1.933,1.762,1.762,1.762,1.762,1.762,1.762,2.111,2.111,2.111,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.847] }, prefix + 'axon': { 'x':[-295.384,-292.833,-291.698,-290.797,-290.500,-290.190,-290.049,-289.817,-289.077,-288.859], 'y':[727.861,726.253,727.784,728.697,729.609,729.827,730.979,731.298,731.819,732.157], 'z':[-103.483,-106.215,-107.317,-107.620,-108.480,-109.789,-111.454,-112.411,-114.434,-116.668], 'diam':[1.847,0.792,0.792,0.792,0.613,0.613,0.613,0.613,0.613,0.613] }, prefix + 'apic[103]': { 'x':[-385.468,-386.636,-387.519], 'y':[724.833,725.405,726.008], 'z':[-44.329,-43.700,-43.616], 'diam':[0.349,0.349,0.442] }, prefix + 'apic[36]': { 'x':[-377.821,-376.611,-375.585], 'y':[725.564,725.842,726.541], 'z':[-41.334,-38.724,-37.841], 'diam':[0.792,0.528,0.613] }, prefix + 'apic[143]': { 'x':[-392.313,-393.149,-393.620,-395.844,-396.906,-397.972], 'y':[732.909,733.729,735.242,733.712,733.360,733.506], 'z':[-53.049,-52.525,-52.809,-51.594,-50.897,-50.708], 'diam':[0.442,0.085,0.085,0.085,0.085,0.085] }, prefix + 'apic[65]': { 'x':[-399.375,-401.214,-402.006,-403.047,-404.055,-405.285,-406.241], 'y':[745.313,746.594,747.718,748.440,748.906,749.265,749.621], 'z':[-22.443,-22.214,-22.578,-22.794,-22.473,-21.685,-21.414], 'diam':[0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[81]': { 'x':[-405.902,-406.027,-406.669], 'y':[732.221,731.166,729.976], 'z':[-32.098,-33.508,-33.897], 'diam':[0.264,0.179,0.179] }, prefix + 'apic[111]': { 'x':[-393.081,-391.578,-390.541,-390.563], 'y':[723.019,723.229,722.316,720.782], 'z':[-41.593,-41.918,-41.138,-40.745], 'diam':[0.349,0.349,0.349,0.349] }, prefix + 'apic[7]': { 'x':[-361.157,-360.532,-359.778,-359.362], 'y':[717.776,716.952,716.330,715.202], 'z':[-40.571,-39.099,-37.884,-36.885], 'diam':[0.264,0.264,0.264,0.264] }, prefix + 'apic[139]': { 'x':[-382.274,-384.558,-385.357,-386.809,-389.189,-390.467,-391.748,-392.313], 'y':[727.857,729.161,729.749,730.364,731.240,731.586,731.815,732.910], 'z':[-51.928,-52.365,-52.188,-52.683,-52.171,-51.808,-51.728,-53.049], 'diam':[0.877,0.442,0.442,0.442,0.442,0.442,0.442,0.442] }, prefix + 'apic[22]': { 'x':[-363.474,-362.344], 'y':[708.950,708.536], 'z':[-30.479,-29.530], 'diam':[0.442,0.528] }, prefix + 'apic[61]': { 'x':[-377.821,-378.506], 'y':[725.564,727.022], 'z':[-41.334,-41.156], 'diam':[0.792,0.349] }, prefix + 'dend[12]': { 'x':[-282.502,-282.951,-283.264,-282.651,-281.742,-281.836,-281.521,-281.167,-280.261,-278.950,-277.874,-277.453,-276.385,-275.693,-276.174,-275.823,-274.889,-275.709,-275.128,-274.394,-273.690,-273.799,-275.126,-274.183,-273.470,-273.059,-272.762,-272.434,-271.538,-270.287,-270.580,-269.918,-268.621,-268.176,-268.772,-268.324,-267.145,-266.008,-265.314,-264.971,-264.444,-264.715,-264.102,-263.089,-262.318,-261.276,-261.048,-260.969,-261.047,-260.995,-260.433,-259.366,-258.657,-257.841,-257.720,-256.785,-254.819,-253.896,-252.407,-251.150,-250.773,-249.012,-247.861,-247.108,-246.989,-246.580,-247.266,-247.012,-247.095,-247.104,-247.176,-245.840,-245.147,-244.552,-243.213,-242.054,-241.056,-240.447,-239.043,-238.465,-238.359,-235.924,-235.064,-233.719,-232.133,-231.126,-230.411,-230.062,-229.061,-228.056,-227.361,-225.939,-224.848,-223.318,-222.018,-221.262,-219.883,-219.418,-218.863,-217.762,-216.335,-215.267,-214.578,-213.499,-212.182,-211.160,-210.388,-210.073,-209.702,-209.145,-208.096,-207.482,-205.906,-204.867,-204.319,-203.235,-200.866,-200.512,-200.397,-200.008,-199.882,-199.628,-199.439,-199.189,-198.568,-197.782,-196.711,-195.691,-194.392,-193.562,-192.465,-191.441,-190.536,-189.684,-189.133,-188.724,-188.509,-188.375,-188.037,-187.356,-187.103,-187.114,-187.182,-186.890,-186.045,-185.187,-184.586,-183.717], 'y':[721.731,723.508,723.561,724.266,724.692,725.009,725.765,726.947,727.081,727.791,729.214,729.553,729.779,730.419,730.667,731.556,731.831,732.378,734.065,734.694,736.106,736.763,737.736,738.712,740.218,740.703,742.478,743.779,744.535,745.910,747.546,748.483,748.466,749.956,750.926,753.573,753.809,753.092,754.314,755.303,757.112,758.114,759.318,759.846,761.132,761.416,762.450,762.994,763.931,764.339,764.522,764.748,765.485,766.124,766.848,767.021,767.323,767.592,767.866,768.377,770.324,771.279,772.052,772.812,773.893,775.147,776.156,778.003,778.891,779.908,780.645,781.069,781.416,782.234,783.380,783.523,784.005,785.152,786.327,787.191,790.048,793.872,793.985,794.966,795.667,796.979,797.446,798.496,799.618,800.332,801.033,802.141,802.513,803.300,803.648,804.033,804.516,805.384,806.469,806.778,806.996,807.415,807.991,809.207,810.207,811.315,812.667,813.882,815.138,817.123,818.453,820.292,821.042,821.963,823.055,823.899,825.768,826.825,828.414,828.547,828.693,829.568,829.804,830.557,833.493,834.459,834.796,835.914,836.508,837.483,838.077,838.960,839.785,840.605,842.354,843.259,843.669,844.165,846.122,846.735,847.718,848.847,851.647,854.513,855.301,857.066,858.903,860.322], 'z':[-73.572,-71.714,-70.740,-70.083,-69.566,-68.090,-67.158,-66.572,-65.932,-64.657,-64.282,-63.052,-63.774,-63.428,-61.807,-61.097,-59.996,-57.996,-57.633,-58.102,-58.156,-57.410,-57.063,-55.885,-56.053,-54.848,-54.316,-54.799,-53.840,-53.668,-53.023,-52.715,-51.782,-50.625,-50.462,-50.540,-50.076,-49.559,-49.490,-48.790,-48.794,-48.568,-49.802,-48.691,-49.076,-49.689,-48.428,-47.404,-45.153,-43.898,-42.737,-42.300,-41.507,-41.256,-39.876,-39.346,-38.258,-37.726,-37.085,-36.387,-35.717,-35.065,-34.755,-34.767,-35.285,-34.454,-34.442,-34.274,-33.770,-33.024,-31.931,-31.790,-30.726,-31.139,-30.806,-30.214,-29.579,-29.062,-29.067,-28.310,-27.902,-27.288,-26.747,-27.252,-27.594,-27.358,-26.750,-26.558,-26.077,-25.115,-24.638,-24.803,-24.489,-24.380,-23.826,-23.016,-22.225,-21.896,-21.462,-21.240,-20.661,-19.088,-18.378,-18.703,-17.718,-16.214,-15.894,-15.373,-14.520,-13.688,-13.791,-14.670,-15.015,-14.632,-14.196,-14.143,-12.727,-12.539,-11.731,-9.870,-8.835,-7.615,-6.134,-4.674,-4.366,-3.797,-3.234,-2.879,-2.554,-2.432,-1.216,-0.727,-0.114,1.058,2.127,3.010,4.037,5.623,6.422,7.134,7.202,7.447,7.930,8.199,8.336,8.112,8.494,8.937], 'diam':[0.613,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.349,0.349,0.349,0.349,0.349,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.613,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[0]': { 'x':[-297.860,-301.678,-304.183,-306.007,-306.943,-307.800], 'y':[705.320,703.593,702.770,702.413,701.533,701.708], 'z':[-86.808,-85.198,-84.344,-84.329,-85.871,-88.086], 'diam':[3.082,2.197,2.290,2.026,2.026,2.111] }, prefix + 'apic[69]': { 'x':[-378.506,-379.512,-381.424,-381.525,-382.168,-382.693,-382.760,-382.899,-382.684], 'y':[727.022,729.156,729.306,732.428,733.429,734.979,735.904,736.649,737.085], 'z':[-41.156,-39.212,-37.874,-37.467,-36.173,-34.131,-33.186,-32.499,-31.557], 'diam':[0.349,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179] }, prefix + 'apic[63]': { 'x':[-398.247,-398.575,-399.375], 'y':[742.846,744.331,745.313], 'z':[-24.556,-23.585,-22.443], 'diam':[0.349,0.264,0.264] }, prefix + 'apic[43]': { 'x':[-365.089,-364.095,-363.786,-363.053,-361.267,-360.283,-359.567,-359.700,-359.717,-359.359,-358.745,-358.229,-357.819,-357.919,-356.174,-353.860,-352.695,-351.931,-352.066,-351.850,-352.304,-352.948,-355.406,-357.292,-358.293,-359.474], 'y':[732.271,731.448,730.651,730.469,731.074,731.081,731.639,732.750,733.367,733.577,733.590,733.950,734.561,734.489,735.624,735.539,735.280,735.259,736.319,737.215,738.411,739.295,738.353,738.555,738.629,738.284], 'z':[-3.214,-1.161,-0.621,0.093,1.827,3.405,5.921,7.997,9.324,10.252,11.257,12.974,15.144,17.122,18.674,21.851,23.084,24.246,26.174,27.649,29.726,30.552,31.291,31.413,30.925,30.508], 'diam':[0.349,0.349,0.349,0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[8]': { 'x':[-359.362,-358.113,-357.193,-355.757], 'y':[715.202,714.929,715.687,716.173], 'z':[-36.885,-35.572,-35.639,-35.725], 'diam':[0.264,0.264,0.264,0.264] }, prefix + 'apic[19]': { 'x':[-374.047,-372.254,-371.023], 'y':[713.597,714.780,715.203], 'z':[-36.870,-35.253,-34.276], 'diam':[1.056,0.877,0.877] }, prefix + 'apic[99]': { 'x':[-366.046,-365.031,-364.659,-363.949,-363.236,-362.423,-360.957,-359.890,-358.716,-358.415], 'y':[719.602,718.590,717.328,715.568,714.673,713.731,712.309,710.972,710.110,709.056], 'z':[-24.003,-24.716,-25.226,-24.867,-25.013,-25.397,-26.244,-25.981,-25.904,-25.699], 'diam':[0.613,0.442,0.442,0.442,0.442,0.442,0.349,0.349,0.349,0.349] }, prefix + 'apic[55]': { 'x':[-352.948,-352.323,-351.955], 'y':[715.283,716.032,715.597], 'z':[-36.221,-38.168,-39.754], 'diam':[0.349,0.349,0.349] }, prefix + 'apic[131]': { 'x':[-394.546,-395.178,-396.816,-398.059,-397.235,-397.128,-397.378], 'y':[737.443,739.653,741.496,742.931,744.586,745.804,746.403], 'z':[-41.888,-40.861,-37.837,-35.203,-34.149,-33.312,-32.400], 'diam':[0.528,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[41]': { 'x':[-373.328,-372.916,-372.633,-371.503,-370.648,-369.763,-369.576,-368.603,-367.886,-367.894,-366.920,-366.165], 'y':[731.957,732.107,732.450,733.358,733.361,732.488,732.939,733.302,733.131,732.243,732.328,732.626], 'z':[-19.495,-18.466,-17.135,-14.191,-12.347,-12.156,-11.053,-9.863,-8.978,-8.057,-5.991,-4.049], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[50]': { 'x':[-371.908,-372.309,-372.937,-373.834,-374.959,-375.629,-376.311], 'y':[728.584,729.840,730.617,731.047,731.564,732.200,733.169], 'z':[-28.319,-29.607,-28.661,-27.823,-27.087,-25.832,-24.348], 'diam':[0.528,0.528,0.528,0.528,0.528,0.528,0.528] }, prefix + 'apic[2]': { 'x':[-365.814,-368.681,-369.788,-371.406], 'y':[717.747,716.931,718.424,719.126], 'z':[-58.901,-54.958,-53.035,-51.397], 'diam':[1.847,1.584,1.584,1.933] }, prefix + 'apic[54]': { 'x':[-365.713,-364.794,-362.683,-361.201,-359.872,-358.804,-357.848,-356.380,-355.525,-353.766,-353.747,-352.948], 'y':[723.216,722.433,722.539,721.362,720.292,719.760,719.542,718.712,717.942,717.817,714.841,715.283], 'z':[-29.929,-30.380,-30.793,-31.476,-32.613,-32.996,-33.401,-33.869,-34.407,-35.302,-35.166,-36.221], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[64]': { 'x':[-399.375,-398.949,-399.553,-399.921,-399.534,-399.055,-399.483,-399.929], 'y':[745.313,745.642,746.537,746.527,747.841,748.931,749.579,750.448], 'z':[-22.443,-20.947,-19.709,-18.472,-17.861,-17.348,-16.449,-15.017], 'diam':[0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[142]': { 'x':[-405.528,-406.701,-406.364,-406.662,-406.591], 'y':[741.655,742.240,743.432,744.356,745.500], 'z':[-49.825,-50.398,-51.126,-51.799,-52.130], 'diam':[0.349,0.179,0.179,0.179,0.179] }, prefix + 'apic[92]': { 'x':[-366.046,-365.415,-364.489,-363.874,-363.707,-364.266,-364.450,-365.429,-365.583], 'y':[719.602,719.723,719.788,719.926,720.335,719.706,719.971,721.388,722.216], 'z':[-24.003,-22.716,-21.068,-20.212,-19.074,-17.789,-16.837,-14.735,-12.958], 'diam':[0.613,0.528,0.613,0.613,0.613,0.613,0.613,0.528,0.528] }, prefix + 'apic[18]': { 'x':[-374.024,-373.888,-374.047], 'y':[715.198,714.772,713.597], 'z':[-38.925,-37.744,-36.870], 'diam':[0.877,1.056,1.056] }, prefix + 'apic[13]': { 'x':[-349.325,-347.331,-346.054,-345.056,-342.992,-341.074,-340.066], 'y':[719.230,718.763,718.732,718.538,718.594,719.015,719.613], 'z':[-30.168,-28.903,-28.790,-28.614,-27.790,-26.946,-26.354], 'diam':[0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[39]': { 'x':[-371.908,-371.971,-372.031,-373.102,-372.570], 'y':[728.584,729.114,730.297,730.468,730.628], 'z':[-28.319,-27.122,-25.843,-23.092,-21.545], 'diam':[0.528,0.528,0.528,0.528,0.528] }, prefix + 'apic[105]': { 'x':[-389.321,-390.872,-393.230,-394.618,-396.495,-397.479,-399.359,-399.787,-400.428,-401.421,-402.452], 'y':[727.188,728.427,728.388,728.865,729.325,729.974,731.639,732.220,732.834,733.481,733.848], 'z':[-42.050,-41.305,-40.826,-40.309,-39.867,-39.531,-38.747,-37.997,-36.897,-36.561,-36.376], 'diam':[0.349,0.264,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[20]': { 'x':[-371.023,-370.904,-369.504,-368.649,-367.762,-366.881,-366.462,-366.015,-365.121], 'y':[715.203,713.839,712.684,711.914,711.232,710.620,710.628,710.137,711.058], 'z':[-34.276,-33.412,-34.011,-34.549,-34.357,-33.825,-32.826,-31.468,-31.344], 'diam':[0.877,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528] }, prefix + 'apic[95]': { 'x':[-356.531,-356.357,-356.211,-356.847,-357.411,-358.043,-358.371,-358.373,-358.634,-359.241,-359.446,-359.670], 'y':[719.306,719.576,720.009,720.683,721.485,722.612,723.484,724.753,725.350,726.192,726.729,728.162], 'z':[-4.255,-2.374,-1.081,-0.433,0.168,1.329,2.493,4.341,5.251,6.353,7.364,8.825], 'diam':[0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[66]': { 'x':[-398.247,-400.434,-401.322], 'y':[742.846,743.042,743.117], 'z':[-24.556,-24.298,-23.836], 'diam':[0.349,0.264,0.264] }, prefix + 'apic[70]': { 'x':[-375.082,-376.862], 'y':[723.155,723.172], 'z':[-47.527,-46.307], 'diam':[1.234,0.706] }, prefix + 'apic[78]': { 'x':[-389.242,-389.545,-388.952,-389.614,-390.274,-390.847,-391.293,-391.250,-391.190,-391.189,-391.486,-391.589,-390.671,-388.347,-386.753,-385.610,-385.313,-384.984,-384.001,-383.552], 'y':[737.183,735.720,733.874,733.561,734.323,734.985,734.122,736.084,737.218,737.671,737.249,737.279,737.752,737.795,738.020,737.726,736.788,734.907,734.454,733.489], 'z':[-16.218,-13.950,-13.821,-12.543,-11.407,-10.686,-9.825,-9.253,-8.996,-7.876,-6.916,-5.461,-4.066,-1.801,-0.859,0.388,1.668,2.830,3.889,4.727], 'diam':[0.613,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[93]': { 'x':[-365.583,-364.150,-363.331,-362.285], 'y':[722.216,721.800,721.663,721.533], 'z':[-12.958,-11.684,-10.733,-9.374], 'diam':[0.528,0.442,0.442,0.442] }, prefix + 'apic[62]': { 'x':[-378.506,-380.569,-381.467,-382.632,-384.092,-385.209,-386.393,-388.285,-389.493,-390.521,-391.530,-392.829,-393.886,-394.462,-395.274,-396.035,-397.312,-398.247], 'y':[727.022,727.879,728.886,729.984,731.203,732.263,733.444,733.643,734.731,735.347,736.427,737.673,738.514,739.576,740.314,740.502,741.987,742.846], 'z':[-41.156,-40.311,-39.264,-38.405,-37.744,-36.764,-35.594,-34.708,-33.653,-33.310,-32.279,-31.289,-30.422,-28.716,-27.909,-27.083,-25.326,-24.556], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[136]': { 'x':[-406.717,-406.842,-406.977,-407.200,-408.059,-409.312,-410.009,-411.043,-411.962,-412.473], 'y':[739.828,741.628,742.776,744.472,746.314,747.375,748.252,749.408,750.198,751.598], 'z':[-42.726,-41.140,-40.697,-39.503,-37.905,-37.289,-36.712,-35.956,-35.512,-35.486], 'diam':[0.264,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[117]': { 'x':[-365.814,-367.647,-369.685,-370.483,-371.252,-372.316,-375.201,-377.544,-378.792,-380.006,-381.261,-382.274], 'y':[717.747,719.096,719.119,720.159,720.974,721.842,724.816,724.496,725.215,726.053,727.121,727.857], 'z':[-58.901,-58.352,-57.224,-55.925,-55.151,-54.724,-53.864,-52.659,-52.857,-52.752,-52.129,-51.928], 'diam':[1.847,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.877,0.877,0.877,0.877] }, prefix + 'apic[9]': { 'x':[-359.362,-356.640,-355.265,-354.352], 'y':[715.202,714.247,713.181,712.601], 'z':[-36.885,-37.383,-37.494,-37.760], 'diam':[0.264,0.264,0.264,0.264] }, prefix + 'dend[8]': { 'x':[-295.384,-296.495,-296.116,-296.992,-298.077,-299.122,-300.559,-300.436,-299.709,-298.724,-298.273,-297.775,-297.079,-296.956,-296.054,-295.490,-294.830], 'y':[727.861,729.288,730.273,730.870,731.347,731.089,731.140,735.000,735.886,737.148,738.291,739.347,740.327,741.610,742.826,743.422,745.482], 'z':[-103.483,-104.712,-106.145,-106.773,-106.760,-106.621,-105.551,-104.625,-104.605,-104.497,-104.729,-104.954,-104.936,-105.431,-106.151,-106.776,-106.725], 'diam':[1.847,1.669,1.669,1.669,1.669,1.669,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.762,1.762,1.584] }, prefix + 'apic[102]': { 'x':[-383.489,-385.468], 'y':[724.129,724.833], 'z':[-44.607,-44.329], 'diam':[0.613,0.349] }, prefix + 'apic[128]': { 'x':[-399.616,-401.798,-402.972,-403.609,-403.999,-404.388], 'y':[745.693,745.255,745.453,747.194,748.202,749.145], 'z':[-30.891,-30.008,-30.181,-29.852,-28.906,-27.685], 'diam':[0.349,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[132]': { 'x':[-390.228,-391.727,-394.791,-395.800], 'y':[733.473,734.070,734.329,733.524], 'z':[-48.183,-49.096,-49.622,-49.182], 'diam':[0.792,0.706,0.528,0.528] }, prefix + 'dend[13]': { 'x':[-282.502,-281.179,-279.068,-274.478,-270.034,-267.279,-265.304,-263.436,-261.995,-260.552,-259.455,-256.293,-253.906,-250.930,-249.019,-247.267,-245.526,-243.939,-242.562,-240.274,-238.721,-236.088,-230.280,-228.669,-226.304,-222.644,-219.207,-217.921,-215.100,-208.235,-204.413,-202.147,-200.018,-198.458,-197.445,-196.573,-195.415,-191.684,-187.133,-182.885,-181.461,-180.007,-178.388,-176.229,-175.254], 'y':[721.731,722.004,723.160,724.226,724.383,725.578,725.697,725.942,726.813,726.959,727.027,727.705,729.561,729.834,730.007,730.099,730.249,731.363,731.823,733.516,734.054,733.441,733.966,734.152,735.442,735.854,736.203,736.349,737.546,738.344,740.001,739.138,739.435,739.589,739.736,739.886,739.781,740.257,740.750,740.146,740.713,740.905,741.130,741.030,740.302], 'z':[-73.572,-71.566,-70.034,-67.165,-65.426,-64.572,-64.516,-64.602,-64.593,-64.875,-65.110,-64.913,-65.462,-65.199,-64.920,-65.492,-65.483,-65.106,-64.616,-64.007,-63.245,-62.318,-61.707,-61.030,-60.615,-59.171,-57.778,-57.273,-55.282,-52.483,-50.745,-48.811,-47.342,-47.024,-46.245,-44.674,-42.222,-38.913,-35.537,-32.516,-30.047,-29.169,-28.034,-25.932,-22.899], 'diam':[0.613,0.264,0.264,0.264,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179] }, prefix + 'apic[127]': { 'x':[-399.616,-400.125,-401.188,-402.693,-403.063,-404.029,-405.162,-405.961,-406.889,-407.999,-408.825,-409.895,-411.317,-412.380,-414.016,-416.057], 'y':[745.693,746.627,747.490,747.541,748.467,748.010,747.465,748.104,749.220,749.996,750.788,751.048,750.530,749.923,749.656,750.351], 'z':[-30.891,-30.175,-29.754,-28.309,-27.250,-26.340,-25.308,-24.373,-23.269,-21.605,-19.879,-18.613,-17.488,-16.518,-16.074,-15.280], 'diam':[0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[21]': { 'x':[-365.121,-363.474], 'y':[711.058,708.950], 'z':[-31.344,-30.479], 'diam':[0.528,0.442] }, prefix + 'apic[15]': { 'x':[-357.306,-357.953,-358.543,-358.307,-357.732,-356.809,-356.076], 'y':[721.905,722.583,723.532,723.877,725.751,726.027,726.511], 'z':[-32.611,-31.955,-30.569,-29.507,-26.441,-25.210,-24.398], 'diam':[0.349,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[114]': { 'x':[-376.862,-379.421,-380.552,-383.412,-385.811,-386.994,-388.388,-389.631,-392.895,-394.120,-394.255,-395.800,-396.692,-398.766,-399.803,-401.202,-402.064,-403.169,-404.794,-405.774,-406.868,-407.931], 'y':[723.172,724.228,724.759,725.283,726.433,726.483,726.359,727.152,729.428,729.721,731.952,731.709,732.381,733.725,734.770,734.440,734.624,734.576,733.158,733.727,733.887,734.348], 'z':[-46.307,-46.385,-46.866,-47.067,-46.666,-46.106,-46.158,-46.032,-45.480,-45.010,-44.703,-43.578,-42.575,-42.272,-42.288,-41.140,-40.379,-39.449,-38.574,-37.948,-37.611,-37.540], 'diam':[0.706,0.264,0.264,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179] }, prefix + 'apic[124]': { 'x':[-395.218,-396.161], 'y':[740.049,740.635], 'z':[-36.531,-35.502], 'diam':[0.613,0.528] }, prefix + 'apic[56]': { 'x':[-352.948,-351.273,-350.249,-348.228,-348.113,-348.197,-347.632,-347.377,-346.946,-346.441,-345.613,-344.655,-344.943], 'y':[715.283,714.230,713.474,713.651,712.519,711.057,709.772,708.714,707.468,706.862,705.982,704.961,703.928], 'z':[-36.221,-36.445,-36.823,-36.410,-35.304,-34.842,-34.922,-35.743,-37.199,-37.864,-38.714,-39.081,-38.677], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[82]': { 'x':[-405.902,-407.297,-408.848], 'y':[732.221,732.785,733.089], 'z':[-32.098,-33.094,-32.949], 'diam':[0.264,0.179,0.179] }, prefix + 'apic[130]': { 'x':[-396.161,-398.034,-397.334,-397.495], 'y':[740.635,740.416,740.900,740.822], 'z':[-35.501,-35.141,-37.336,-38.423], 'diam':[0.528,0.442,0.442,0.442] }, prefix + 'apic[94]': { 'x':[-362.285,-361.149,-359.575,-358.524,-357.804,-356.531], 'y':[721.533,721.113,720.106,719.504,718.726,719.306], 'z':[-9.374,-8.588,-8.560,-7.890,-6.945,-4.255], 'diam':[0.442,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[126]': { 'x':[-398.619,-399.738,-399.616], 'y':[742.819,744.346,745.693], 'z':[-31.263,-30.987,-30.891], 'diam':[0.528,0.349,0.349] }, prefix + 'apic[3]': { 'x':[-371.406,-372.417,-372.673], 'y':[719.126,716.462,717.133], 'z':[-51.397,-47.815,-46.593], 'diam':[1.933,1.320,1.320] }, prefix + 'apic[115]': { 'x':[-407.931,-408.319,-408.983,-409.267,-410.037,-410.232], 'y':[734.348,734.773,734.294,733.803,733.106,731.915], 'z':[-37.540,-38.974,-40.124,-41.483,-42.736,-43.652], 'diam':[0.179,0.179,0.179,0.179,0.179,0.179] }, prefix + 'apic[108]': { 'x':[-389.321,-389.530,-389.118,-388.421], 'y':[727.188,727.856,726.793,727.252], 'z':[-42.050,-40.572,-39.254,-38.429], 'diam':[0.349,0.264,0.264,0.264] }, prefix + 'apic[109]': { 'x':[-387.519,-387.667,-387.601,-385.286,-384.275,-384.196,-383.470], 'y':[726.008,723.804,722.659,723.001,721.928,721.093,720.237], 'z':[-43.616,-41.851,-41.171,-41.428,-41.689,-41.134,-40.508], 'diam':[0.442,0.179,0.179,0.179,0.179,0.179,0.179] }, prefix + 'apic[31]': { 'x':[-371.023,-369.996,-368.275,-366.578,-364.028,-362.378,-360.430,-359.537,-358.501,-357.324,-355.998,-354.672,-353.303,-352.256,-351.262,-349.685,-348.048,-346.503,-345.326,-344.393,-342.099,-340.425,-339.322,-338.832,-338.595,-338.475], 'y':[715.203,715.492,714.918,714.227,713.160,713.006,712.710,712.563,711.978,711.327,710.644,709.959,709.768,709.245,708.781,708.300,707.690,706.771,706.252,706.123,705.165,705.637,706.128,706.994,707.596,708.870], 'z':[-34.276,-32.378,-31.056,-30.040,-28.583,-27.587,-26.725,-25.688,-25.449,-25.181,-24.752,-24.325,-24.147,-23.752,-23.472,-23.214,-22.729,-22.822,-22.693,-21.846,-20.846,-19.484,-17.307,-16.548,-15.746,-14.759], 'diam':[0.877,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'dend[4]': { 'x':[-300.796,-303.420,-304.396,-304.639,-304.904,-305.925,-307.246,-308.656,-311.137,-312.165,-313.188,-314.124,-314.766,-315.566,-315.748,-315.600,-315.493,-315.699,-315.748,-316.649], 'y':[716.093,710.231,710.087,709.975,710.842,711.041,711.141,711.319,711.187,711.050,711.441,711.362,711.243,711.238,711.308,712.082,712.817,713.528,714.129,714.484], 'z':[-93.880,-94.683,-95.573,-96.661,-98.055,-98.288,-97.644,-97.725,-98.699,-99.365,-99.730,-100.270,-101.097,-102.895,-104.329,-105.392,-106.339,-107.942,-109.158,-111.225], 'diam':[2.639,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056] }, prefix + 'apic[77]': { 'x':[-385.814,-387.864,-388.670,-390.076,-391.455,-392.138,-394.062,-395.158,-395.490,-396.204,-395.997,-397.187,-398.152], 'y':[746.839,748.160,748.352,749.396,750.519,751.189,752.030,752.532,753.696,754.445,755.114,756.660,757.438], 'z':[9.799,9.776,8.974,9.268,9.705,9.326,9.728,10.287,10.139,10.241,8.948,8.536,7.960], 'diam':[0.528,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[42]': { 'x':[-366.165,-365.089], 'y':[732.626,732.271], 'z':[-4.049,-3.214], 'diam':[0.349,0.349] }, prefix + 'apic[104]': { 'x':[-387.519,-388.274,-389.321], 'y':[726.008,726.607,727.188], 'z':[-43.616,-43.183,-42.050], 'diam':[0.442,0.264,0.349] }, prefix + 'apic[118]': { 'x':[-382.274,-384.573,-386.892,-388.468,-390.228], 'y':[727.857,729.727,731.663,733.064,733.473], 'z':[-51.928,-50.990,-49.939,-49.003,-48.183], 'diam':[0.877,1.056,0.792,0.792,0.792] }, prefix + 'apic[16]': { 'x':[-364.098,-365.222,-365.893,-365.640,-365.187,-364.924,-364.947,-364.845,-365.211,-366.166,-366.718,-367.281], 'y':[717.234,718.621,718.444,718.480,718.203,718.504,718.257,718.524,718.969,719.106,720.415,721.020], 'z':[-39.614,-38.003,-36.096,-34.491,-33.549,-32.212,-31.174,-30.159,-29.187,-27.900,-26.029,-25.451], 'diam':[0.706,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'dend[0]': { 'x':[-307.800,-307.179,-306.302,-306.083,-305.433,-305.160,-305.222,-304.997,-304.725,-304.760,-304.916,-304.505,-304.196,-305.303,-305.149,-305.921,-306.550,-306.430,-305.491,-305.073,-304.928,-304.692,-303.934,-303.942,-303.311,-302.670,-302.124,-301.481,-303.920,-304.030,-305.719,-306.337,-306.162,-305.845,-305.569,-305.424], 'y':[701.708,699.574,698.042,695.047,693.418,691.963,690.876,689.630,688.650,686.805,684.562,683.449,682.118,681.327,680.556,679.886,679.065,677.874,676.568,675.648,674.719,673.539,672.196,670.924,669.433,668.320,666.684,665.968,663.779,662.632,662.993,662.763,661.298,660.494,658.850,657.846], 'z':[-88.086,-88.520,-88.244,-87.580,-87.601,-87.742,-88.323,-88.410,-88.532,-88.895,-89.767,-88.696,-87.877,-87.823,-86.974,-87.010,-87.310,-87.318,-86.801,-86.787,-87.166,-87.545,-87.312,-88.116,-88.144,-87.922,-88.616,-89.352,-87.629,-86.651,-86.348,-87.263,-86.915,-86.321,-86.107,-86.353], 'diam':[2.111,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706] }, prefix + 'apic[30]': { 'x':[-365.121,-366.309,-367.132,-368.091,-368.656,-369.181,-369.119,-370.042,-370.639,-371.795,-373.048,-374.080,-374.673,-375.869,-377.759,-378.720], 'y':[711.058,711.498,712.628,712.844,713.499,713.697,713.946,714.720,715.024,715.585,715.645,716.135,716.893,718.224,718.344,718.231], 'z':[-31.344,-29.195,-27.424,-26.412,-25.076,-23.402,-22.212,-20.551,-19.677,-19.827,-19.521,-18.862,-17.477,-15.663,-14.487,-14.134], 'diam':[0.528,0.085,0.085,0.085,0.085,0.085,0.085,0.085,0.085,0.085,0.085,0.085,0.085,0.085,0.085,0.085] }, prefix + 'apic[24]': { 'x':[-359.839,-357.861,-356.382,-355.325,-354.069,-352.798,-350.928,-349.584,-348.536,-347.195,-346.434,-346.325,-344.670,-343.459,-341.726,-340.545,-338.510,-337.481], 'y':[708.648,707.673,707.210,706.873,707.477,707.517,706.996,706.426,705.919,705.026,703.478,702.475,702.192,701.844,701.207,700.881,700.126,699.833], 'z':[-26.957,-26.368,-24.825,-23.813,-23.258,-22.834,-22.217,-22.092,-22.306,-22.820,-22.635,-22.279,-23.122,-23.755,-23.955,-24.418,-25.199,-25.666], 'diam':[0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[26]': { 'x':[-362.344,-361.044,-359.445,-359.718,-358.479,-357.623,-356.858], 'y':[708.536,707.290,707.408,706.088,704.423,703.564,702.880], 'z':[-29.530,-30.521,-31.256,-30.925,-29.946,-29.593,-29.899], 'diam':[0.528,0.442,0.442,0.442,0.442,0.442,0.442] }, prefix + 'apic[11]': { 'x':[-362.553,-360.713,-359.161,-358.146,-357.358,-357.306], 'y':[717.930,718.424,718.829,718.997,719.890,721.905], 'z':[-39.618,-38.090,-37.388,-35.363,-33.925,-32.611], 'diam':[0.442,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[25]': { 'x':[-359.839,-362.730,-363.058], 'y':[708.648,709.793,712.303], 'z':[-26.957,-27.056,-28.228], 'diam':[0.264,0.264,0.264] }, prefix + 'apic[76]': { 'x':[-385.814,-385.050,-384.423,-384.739,-384.753,-384.541,-384.017,-382.640,-382.233,-381.434,-381.072,-380.494,-379.211,-378.434,-377.220,-375.562,-373.409,-371.705,-370.298], 'y':[746.839,746.885,746.938,747.673,747.939,749.302,750.256,751.094,751.909,752.912,753.445,754.150,754.104,754.153,754.170,754.718,755.134,755.118,755.149], 'z':[9.799,11.124,12.899,14.198,15.296,16.674,19.393,23.645,25.377,27.728,29.310,30.742,32.057,32.775,34.152,35.366,37.665,38.784,39.721], 'diam':[0.528,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[85]': { 'x':[-399.225,-398.068,-397.897,-397.019], 'y':[733.084,734.722,735.526,736.193], 'z':[-25.820,-24.604,-23.279,-22.718], 'diam':[0.349,0.264,0.264,0.264] }, prefix + 'apic[12]': { 'x':[-357.306,-355.747,-354.298,-352.999,-351.725,-350.264,-349.325], 'y':[721.905,721.142,720.205,720.362,720.262,719.496,719.230], 'z':[-32.611,-31.972,-32.145,-32.009,-31.451,-30.993,-30.168], 'diam':[0.349,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[98]': { 'x':[-365.583,-367.074,-369.466,-371.117,-372.070,-372.910,-375.096,-374.840,-373.944], 'y':[722.216,723.660,724.526,725.943,727.492,728.858,730.465,731.599,732.184], 'z':[-12.958,-11.771,-10.673,-9.816,-9.388,-9.066,-9.542,-9.288,-8.601], 'diam':[0.528,0.442,0.442,0.442,0.349,0.349,0.264,0.264,0.264] }, prefix + 'apic[17]': { 'x':[-372.673,-373.356,-374.241,-373.789,-372.972,-373.175,-374.024,-374.024], 'y':[717.133,718.444,718.162,717.255,715.986,714.858,714.745,715.198], 'z':[-46.593,-44.449,-42.837,-41.843,-42.279,-40.911,-40.045,-38.925], 'diam':[1.320,0.877,0.877,0.877,0.877,0.877,0.877,0.877] }, }
92.910866
3,305
0.576177
from neuron import h class TransformTC4: def __init__(self): self.name2section = { sec.name(): sec for sec in h.allsec() } self.section_coords = { } def set_coords(self, sec_name): nrn_section = self.name2section[sec_name] new_coords = self.section_coords[sec_name] h.pt3dconst(1, sec=nrn_section) h.pt3dclear(len(new_coords["diam"]), sec=nrn_section) xvec = h.Vector(new_coords["x"]) yvec = h.Vector(new_coords["y"]) zvec = h.Vector(new_coords["z"]) dvec = h.Vector(new_coords["diam"]) h.pt3dadd(xvec, yvec, zvec, dvec, sec=nrn_section) def set_all(self): for sec_name in self.section_coords.keys(): self.set_coords(sec_name) @staticmethod def apply_on(prefix): t = TransformTC4() t.define_coords(prefix) t.set_all() @staticmethod def apply(): t = TransformTC4() t.define_coords() t.set_all() def define_coords(self, prefix = 'TC4[0]'): if prefix != '': prefix += '.' self.section_coords = { prefix + 'apic[68]': { 'x':[-401.322,-402.235,-402.958,-401.756], 'y':[743.117,744.267,743.755,747.357], 'z':[-23.836,-21.982,-21.153,-19.972], 'diam':[0.264,0.264,0.264,0.264] }, prefix + 'apic[100]': { 'x':[-368.650,-369.977,-371.475,-372.161,-372.512,-373.361,-373.937,-374.711,-375.289,-375.521,-375.522,-376.265,-375.041,-375.495,-375.517,-374.957,-374.165,-373.673,-372.672,-371.700], 'y':[721.906,722.984,723.293,723.815,724.044,724.948,725.556,726.107,726.840,727.356,728.641,728.811,731.930,731.927,732.329,732.519,732.126,732.122,732.931,732.884], 'z':[-26.366,-25.829,-24.064,-23.086,-21.692,-20.685,-20.100,-19.668,-18.622,-17.585,-16.403,-13.942,-13.605,-11.861,-10.119,-8.762,-7.375,-6.275,-5.944,-4.515], 'diam':[0.613,0.442,0.442,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[113]': { 'x':[-383.489,-383.890,-383.410,-381.081,-380.535], 'y':[724.129,724.331,723.344,724.340,723.080], 'z':[-44.607,-43.031,-41.923,-41.646,-40.779], 'diam':[0.613,0.264,0.264,0.264,0.264] }, prefix + 'apic[37]': { 'x':[-375.585,-375.040,-374.570,-372.798,-371.266], 'y':[726.541,727.069,727.549,727.462,727.211], 'z':[-37.841,-35.655,-33.710,-32.052,-30.669], 'diam':[0.613,0.706,0.706,0.792,0.792] }, prefix + 'dend[2]': { 'x':[-305.424,-306.149,-306.972,-307.633,-307.203,-306.701,-307.338,-308.001,-307.992,-308.743,-309.466,-310.076,-309.901,-309.758,-310.736,-310.876,-311.714,-311.679,-312.585,-313.265,-314.333,-315.285,-316.729,-317.738,-318.707,-319.653,-320.304,-321.717,-323.098,-323.748,-323.829,-324.387,-325.403,-325.801,-326.171,-327.007,-326.773,-326.650,-327.482,-327.738,-328.016,-328.723,-328.947,-329.713,-330.844,-331.091,-331.111,-332.015,-332.114,-332.743,-333.113,-334.087,-334.663,-335.558,-336.136,-336.693,-337.237,-337.555,-337.335,-337.787,-338.119,-339.486,-340.852,-341.635,-342.410,-343.707,-345.556,-346.546,-347.430,-347.788,-348.533,-350.674,-351.546,-352.687,-353.566,-355.548,-356.503,-358.427,-359.864,-360.664,-361.856,-363.812,-364.870,-365.902,-367.369,-368.292,-368.764,-369.440,-370.536,-369.616,-370.027,-370.562,-369.958,-371.540,-372.116,-372.849,-373.095,-373.288,-373.202,-373.851,-374.295,-374.686,-374.293,-374.813,-375.303,-375.578,-376.148,-376.218,-377.242,-377.452,-377.267,-377.331,-377.443,-377.591,-377.441,-377.731,-378.310,-378.240,-378.158,-379.308,-379.335,-379.848,-380.406,-380.797,-380.513,-380.372,-380.032,-379.849,-379.917,-379.376,-378.853,-379.067,-378.944,-379.432,-379.750,-381.569,-381.330,-381.775,-382.134,-382.884,-383.706,-384.466,-384.231,-383.911,-385.008,-385.241,-385.364,-385.829,-386.448,-386.579,-386.330,-384.136,-387.079,-387.052,-386.854,-387.056,-387.134,-386.899,-387.208,-387.344,-387.404,-388.023,-387.858,-388.750,-389.583,-389.749,-390.293,-390.904,-391.807,-392.082,-393.498,-394.299,-395.083,-396.237,-397.409,-398.536,-398.992,-399.711,-400.673,-401.799,-401.981,-402.645,-402.713,-403.474,-404.364,-404.557,-405.328,-406.310,-406.915,-406.661,-407.622,-408.540,-408.281,-408.601,-409.468,-410.498,-411.801,-412.336,-413.417,-414.658,-415.811,-417.025,-417.416,-418.083,-418.578,-418.893,-419.861,-419.442,-420.697,-420.904,-421.188,-421.585,-422.166,-421.938,-421.805,-421.925,-422.798,-423.851,-424.795], 'y':[657.846,655.817,654.383,653.371,652.356,651.413,650.015,649.378,647.780,646.618,645.949,644.136,642.224,640.841,639.570,637.857,636.189,635.102,634.031,633.678,632.205,631.336,631.200,630.695,628.655,627.457,626.996,626.050,625.432,624.547,623.001,621.427,620.541,619.190,617.529,616.051,614.099,613.047,612.730,611.830,610.882,610.074,608.913,607.579,606.409,605.188,603.234,602.723,601.681,600.729,599.748,598.653,597.857,597.572,596.367,594.512,593.448,591.688,590.399,589.428,587.989,587.069,585.854,585.221,584.161,583.198,580.883,581.289,582.894,584.788,583.671,583.680,584.025,584.415,583.736,583.322,583.894,582.830,582.608,583.592,582.619,582.818,582.532,583.399,583.482,583.227,581.977,580.616,579.303,578.936,577.589,576.747,575.455,573.755,572.849,571.127,569.857,568.450,567.149,565.861,564.832,563.384,562.328,559.544,558.447,557.437,556.355,554.987,553.428,552.117,550.812,549.716,546.844,545.215,542.425,541.523,539.703,538.178,536.442,534.657,532.485,531.476,530.006,528.892,526.795,525.742,524.451,521.642,519.838,518.634,516.972,514.884,513.827,511.941,511.025,508.376,506.818,505.672,504.514,503.805,502.764,502.042,500.095,498.508,497.199,495.989,494.709,493.780,492.397,490.989,490.029,489.595,487.717,485.106,484.052,482.960,481.577,479.617,478.870,477.803,476.740,474.906,473.845,473.536,473.042,471.747,470.879,470.946,470.850,469.999,468.585,467.704,467.859,467.609,467.765,466.920,465.363,464.453,464.173,463.719,462.390,461.857,461.112,459.863,459.303,458.068,457.058,455.924,454.394,453.021,452.240,452.244,451.172,450.056,449.408,449.081,449.179,448.412,446.642,445.859,444.628,444.020,442.960,442.026,441.460,440.411,439.813,438.771,437.936,436.800,435.005,434.026,432.869,431.080,429.895,428.409,426.955,426.013,425.250], 'z':[-86.353,-87.989,-88.761,-88.939,-88.680,-88.000,-88.761,-89.898,-89.692,-89.536,-90.332,-90.940,-91.312,-91.513,-92.119,-92.179,-92.385,-92.720,-93.485,-94.379,-96.344,-98.222,-99.345,-100.621,-101.779,-102.844,-103.498,-105.342,-106.480,-106.656,-107.169,-107.746,-108.364,-109.480,-109.473,-110.100,-110.682,-111.082,-112.447,-113.092,-113.890,-115.204,-115.781,-117.054,-117.343,-117.169,-117.852,-119.066,-119.581,-119.313,-119.441,-119.837,-120.587,-121.746,-122.672,-123.778,-124.385,-125.363,-124.846,-125.350,-126.532,-127.184,-127.755,-128.331,-129.353,-130.216,-130.395,-130.526,-130.866,-130.201,-130.487,-130.377,-130.020,-130.195,-130.095,-129.484,-129.739,-130.273,-129.503,-128.554,-128.446,-128.139,-128.708,-129.447,-129.267,-129.626,-128.220,-129.090,-128.702,-127.449,-127.936,-128.480,-128.426,-128.490,-128.582,-129.206,-128.592,-127.909,-128.036,-127.543,-128.534,-129.986,-129.992,-130.331,-130.234,-130.883,-131.173,-131.188,-131.680,-131.871,-132.231,-132.626,-133.187,-134.125,-134.815,-135.144,-136.072,-136.551,-136.788,-137.401,-138.135,-138.287,-139.150,-139.579,-140.098,-140.192,-140.236,-141.162,-141.916,-142.092,-142.369,-142.775,-143.167,-144.192,-145.113,-145.094,-145.724,-146.425,-146.455,-146.475,-147.001,-147.326,-147.918,-148.456,-148.977,-149.126,-149.373,-149.399,-149.570,-150.616,-150.866,-152.262,-150.603,-151.171,-151.544,-151.308,-152.278,-153.162,-153.967,-154.817,-155.295,-155.630,-155.975,-156.965,-156.694,-157.271,-158.206,-159.039,-160.278,-161.103,-161.318,-162.349,-163.169,-162.746,-163.119,-164.759,-164.727,-165.663,-166.734,-167.411,-167.563,-168.462,-169.395,-169.037,-169.627,-170.025,-170.360,-171.438,-171.585,-172.070,-173.092,-174.290,-174.577,-175.730,-176.070,-176.351,-177.666,-178.886,-180.318,-180.816,-182.097,-182.728,-183.377,-184.530,-185.581,-186.584,-186.938,-186.899,-187.257,-187.614,-188.210,-188.098,-187.870,-188.570,-188.928,-189.297,-189.777,-189.732,-189.137], 'diam':[0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[123]': { 'x':[-388.217,-387.909,-388.043,-388.419,-388.477,-388.170,-388.968,-389.566,-390.968,-391.192,-392.156,-392.402,-392.782,-393.483,-393.249,-393.743], 'y':[750.404,751.127,751.354,751.752,752.328,752.722,753.615,754.306,754.648,754.734,755.681,757.866,758.125,758.138,761.297,762.410], 'z':[-11.011,-8.893,-6.999,-6.000,-4.675,-3.202,-0.731,0.335,2.959,4.058,5.472,7.517,8.479,9.546,10.264,10.996], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[137]': { 'x':[-406.717,-408.041,-408.660], 'y':[739.828,738.773,737.771], 'z':[-42.726,-43.717,-44.083], 'diam':[0.264,0.264,0.264] }, prefix + 'apic[87]': { 'x':[-383.728,-383.712,-383.710,-384.757,-384.819,-384.736,-384.132,-383.222,-383.501,-383.637,-383.721], 'y':[729.654,730.154,730.665,731.362,732.288,733.530,733.810,734.566,736.049,736.656,737.408], 'z':[-36.522,-35.245,-33.983,-32.367,-30.814,-29.637,-28.144,-26.853,-24.876,-24.069,-23.133], 'diam':[0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[107]': { 'x':[-402.452,-402.181,-402.512,-403.510,-404.990,-407.221,-407.770,-408.463,-409.672,-410.454,-411.101,-411.695,-411.789], 'y':[733.848,735.891,736.974,738.379,738.467,740.361,741.079,741.936,743.547,744.308,744.920,746.146,747.115], 'z':[-36.376,-35.862,-35.126,-34.206,-33.382,-31.205,-30.321,-29.313,-27.433,-26.810,-26.317,-25.184,-24.501], 'diam':[0.349,0.349,0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[45]': { 'x':[-366.165,-366.313,-366.835], 'y':[732.626,733.106,733.993], 'z':[-4.049,-3.108,-1.770], 'diam':[0.349,0.349,0.349] }, prefix + 'apic[35]': { 'x':[-375.082,-376.135,-376.999,-377.821], 'y':[723.155,724.325,724.617,725.564], 'z':[-47.527,-44.332,-42.503,-41.334], 'diam':[1.234,0.792,0.792,0.792] }, prefix + 'apic[38]': { 'x':[-371.266,-371.908], 'y':[727.211,728.584], 'z':[-30.669,-28.319], 'diam':[0.792,0.528] }, prefix + 'apic[33]': { 'x':[-374.024,-375.311,-377.581,-378.871,-380.203,-381.533,-382.323,-383.122,-384.607,-385.543,-385.955,-385.374,-384.843,-384.505,-384.329,-384.884,-385.583,-386.239,-387.042], 'y':[715.198,716.497,717.045,717.621,716.615,718.152,718.867,719.520,720.476,721.465,723.395,724.035,724.041,723.880,724.005,724.978,725.181,725.388,726.011], 'z':[-38.925,-37.785,-37.421,-37.312,-36.767,-35.118,-34.480,-34.154,-33.048,-31.047,-27.090,-24.605,-23.094,-21.588,-20.360,-18.534,-17.451,-14.734,-12.598], 'diam':[0.877,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[4]': { 'x':[-372.673,-370.268,-368.721,-367.836,-366.480,-365.724,-364.489,-364.000,-364.098], 'y':[717.133,716.035,716.542,716.517,716.592,716.446,716.739,717.539,717.234], 'z':[-46.593,-45.274,-45.463,-44.560,-43.284,-42.583,-42.087,-41.024,-39.614], 'diam':[1.320,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706] }, prefix + 'apic[73]': { 'x':[-382.134,-384.144,-385.221,-385.503,-386.609,-388.356,-389.217,-389.277], 'y':[726.717,727.360,728.561,729.123,729.959,730.043,731.161,731.679], 'z':[-40.431,-37.713,-36.462,-35.538,-34.327,-31.762,-30.401,-29.218], 'diam':[0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706] }, prefix + 'apic[27]': { 'x':[-356.857,-356.708,-357.203,-357.340], 'y':[702.880,703.299,703.826,703.884], 'z':[-29.899,-28.605,-27.042,-25.850], 'diam':[0.442,0.442,0.442,0.442] }, prefix + 'apic[23]': { 'x':[-362.344,-361.072,-360.172,-360.559,-359.839], 'y':[708.536,708.312,707.816,707.671,708.648], 'z':[-29.530,-28.825,-28.610,-27.247,-26.957], 'diam':[0.528,0.264,0.264,0.264,0.264] }, prefix + 'apic[120]': { 'x':[-394.546,-395.049,-395.217,-395.218], 'y':[737.443,738.429,739.655,740.049], 'z':[-41.888,-40.244,-37.510,-36.531], 'diam':[0.528,0.528,0.613,0.613] }, prefix + 'apic[80]': { 'x':[-396.249,-396.770,-398.279,-400.340,-401.841,-402.934,-404.005,-403.900,-405.902], 'y':[731.890,731.769,733.115,732.914,733.113,733.800,733.330,734.782,732.221], 'z':[-29.596,-30.740,-31.656,-31.900,-31.798,-31.216,-30.988,-32.214,-32.098], 'diam':[0.442,0.528,0.528,0.349,0.349,0.349,0.349,0.349,0.264] }, prefix + 'apic[125]': { 'x':[-396.161,-396.692,-397.460,-397.899,-398.619], 'y':[740.635,741.256,742.070,742.393,742.819], 'z':[-35.501,-33.897,-33.109,-32.098,-31.263], 'diam':[0.528,0.528,0.528,0.528,0.528] }, prefix + 'apic[140]': { 'x':[-392.313,-393.520,-394.433,-396.215,-397.872,-398.268,-400.003,-400.972,-401.942,-403.022,-403.964,-405.032,-405.625,-405.135,-405.528], 'y':[732.909,733.465,733.906,733.127,733.614,735.331,735.090,735.531,736.857,737.613,738.345,738.197,737.888,740.515,741.655], 'z':[-53.049,-53.616,-53.980,-53.947,-53.513,-53.518,-53.593,-54.213,-53.589,-53.466,-53.172,-52.276,-51.350,-51.238,-49.825], 'diam':[0.442,0.349,0.349,0.349,0.349,0.442,0.442,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[28]': { 'x':[-356.857,-356.919,-356.761], 'y':[702.880,701.549,701.058], 'z':[-29.899,-30.956,-32.674], 'diam':[0.442,0.442,0.442] }, prefix + 'apic[79]': { 'x':[-389.277,-392.355,-393.562,-395.216,-396.249], 'y':[731.679,731.891,732.249,732.656,731.890], 'z':[-29.218,-29.900,-30.475,-29.766,-29.596], 'diam':[0.706,0.442,0.442,0.442,0.442] }, prefix + 'apic[6]': { 'x':[-362.553,-361.157], 'y':[717.930,717.776], 'z':[-39.618,-40.571], 'diam':[0.442,0.264] }, prefix + 'apic[58]': { 'x':[-368.533,-367.127,-367.500,-367.990,-366.772,-364.813,-363.144,-361.999,-360.753,-360.087,-359.239,-358.460,-356.936,-355.972], 'y':[725.556,724.702,725.159,725.813,725.501,724.931,724.064,723.631,723.152,723.091,721.588,721.156,720.129,718.758], 'z':[-29.616,-28.522,-27.381,-26.560,-25.220,-23.497,-21.118,-19.723,-18.596,-17.662,-17.243,-16.599,-16.381,-16.184], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[116]': { 'x':[-407.931,-408.947,-409.732,-410.750,-412.326,-413.177], 'y':[734.348,735.025,735.733,735.467,735.552,735.258], 'z':[-37.540,-37.480,-37.005,-36.943,-36.793,-37.324], 'diam':[0.179,0.179,0.179,0.179,0.179,0.179] }, prefix + 'apic[40]': { 'x':[-372.570,-372.849,-373.328], 'y':[730.628,731.242,731.957], 'z':[-21.545,-20.472,-19.495], 'diam':[0.528,0.349,0.349] }, prefix + 'apic[74]': { 'x':[-389.277,-389.302,-389.392,-389.856,-389.686,-389.242], 'y':[731.679,732.541,733.801,735.468,736.410,737.183], 'z':[-29.218,-27.141,-24.164,-20.790,-18.228,-16.218], 'diam':[0.706,0.528,0.613,0.613,0.613,0.613] }, prefix + 'apic[112]': { 'x':[-393.081,-394.111,-395.147], 'y':[723.019,724.029,723.597], 'z':[-41.593,-40.711,-39.279], 'diam':[0.349,0.349,0.349] }, prefix + 'dend[6]': { 'x':[-316.649,-316.983,-317.001,-316.991,-318.052,-319.144,-320.229,-320.690,-320.721,-320.971,-321.537,-323.054,-323.926,-325.276,-327.635,-326.904,-327.275,-328.221,-328.880,-329.401,-329.713,-330.354,-331.563,-332.397,-332.869,-333.901,-334.766,-336.052,-337.195,-338.096,-338.652,-339.383,-339.641,-339.814,-339.943,-339.773,-340.698,-341.420,-342.074,-343.010,-343.509,-344.218,-345.016,-345.544,-345.947,-346.366,-346.623,-346.994,-348.169,-349.116,-350.655,-351.823,-352.929,-354.289,-355.540,-356.724,-358.809,-360.180,-361.545,-363.034,-364.550,-366.090,-368.226,-370.293,-371.230,-372.645,-373.711,-374.577,-376.534,-377.696,-378.902,-379.974,-380.897,-382.571,-384.229,-386.551,-386.744,-387.056,-388.525,-388.441,-388.860,-390.513,-391.655,-392.346,-393.119,-394.626,-396.507,-397.421,-398.495,-399.628,-400.393,-401.059,-400.775,-400.778,-402.156,-402.780,-403.163,-403.496,-403.410,-403.824,-403.804,-404.479,-405.193,-406.114,-405.251,-405.872,-407.220,-407.017,-407.361,-408.038,-408.831,-409.900,-409.459,-410.673,-411.358,-411.926,-412.272,-412.908,-413.529,-414.666,-415.458,-416.558,-417.888,-419.097,-419.184,-420.554,-421.509,-422.694,-423.226,-423.698,-424.487,-425.051,-426.607,-427.473,-428.605,-429.542,-431.626,-433.594,-434.985,-435.229,-435.324,-435.402,-435.347,-434.879,-434.224,-434.166,-434.772,-435.318,-435.951,-436.312,-436.963,-437.227,-437.313,-437.152,-437.569,-438.780,-440.223,-441.081,-441.657,-442.116,-443.317,-444.559,-446.245,-447.687], 'y':[714.484,714.221,715.057,716.820,716.696,716.724,716.798,717.294,717.360,717.687,718.119,718.775,718.794,718.806,719.070,719.804,719.978,720.201,720.189,720.071,720.724,721.468,721.636,721.968,722.043,722.759,722.716,723.242,723.542,723.505,723.461,724.344,724.482,724.358,724.307,724.258,724.339,724.578,724.602,724.640,725.008,725.341,725.094,724.889,724.749,725.711,726.235,727.135,727.474,727.264,728.507,729.042,729.031,728.949,728.793,728.703,728.929,728.849,728.824,729.236,729.066,728.853,730.052,729.783,729.616,729.516,729.532,729.442,729.475,729.328,729.244,729.123,728.956,728.750,728.624,730.111,729.933,731.110,731.107,731.188,731.421,731.550,731.448,731.394,731.317,731.061,730.824,731.181,731.345,731.293,731.604,731.442,731.303,731.175,733.338,733.942,734.276,734.242,734.418,734.992,735.434,735.902,736.442,736.800,736.761,737.061,737.474,737.508,738.166,739.026,739.582,739.321,739.225,739.208,739.967,739.972,740.377,740.793,740.775,740.865,741.357,741.737,741.558,741.439,741.470,742.032,742.406,742.088,738.975,738.371,738.149,737.385,737.046,736.909,736.754,736.588,735.994,735.937,735.640,735.058,734.900,735.510,736.036,735.937,735.919,735.807,735.770,735.918,736.277,736.113,735.849,735.755,735.553,735.454,735.173,734.910,734.628,734.484,734.347,734.210,733.492,733.964,734.527,734.769], 'z':[-111.225,-114.063,-116.672,-117.876,-118.327,-118.778,-119.829,-120.661,-121.710,-122.946,-123.788,-125.324,-126.776,-127.648,-128.862,-130.491,-131.624,-132.882,-134.193,-135.688,-136.718,-137.379,-139.032,-140.858,-142.578,-143.834,-144.717,-146.181,-148.760,-150.107,-151.384,-152.760,-153.873,-155.288,-156.354,-158.299,-160.121,-161.333,-162.173,-164.462,-165.634,-166.386,-169.205,-171.164,-172.511,-173.835,-175.081,-176.608,-178.738,-180.321,-181.422,-182.288,-182.632,-183.390,-184.101,-183.996,-185.383,-186.128,-186.892,-187.802,-188.348,-189.358,-189.816,-190.464,-191.580,-191.995,-192.570,-193.437,-194.785,-195.363,-195.728,-196.188,-197.307,-198.222,-198.673,-199.755,-201.642,-202.367,-202.093,-203.128,-204.036,-205.216,-205.904,-207.091,-207.836,-209.536,-210.497,-211.413,-211.993,-213.273,-214.849,-216.140,-217.461,-219.082,-220.175,-221.973,-223.114,-224.928,-225.964,-227.718,-229.134,-230.704,-232.044,-232.848,-233.580,-234.790,-236.957,-237.958,-238.881,-240.012,-241.024,-243.092,-244.631,-246.152,-246.583,-247.862,-249.239,-251.487,-253.017,-254.423,-257.443,-259.092,-260.520,-262.041,-263.933,-264.954,-266.800,-267.720,-268.800,-269.669,-270.867,-272.910,-274.841,-275.713,-276.408,-277.523,-280.140,-281.939,-284.192,-286.187,-287.933,-289.034,-290.688,-292.907,-293.812,-295.181,-296.226,-297.638,-298.721,-299.720,-301.587,-302.552,-304.882,-306.234,-309.215,-311.194,-312.640,-313.513,-314.663,-315.795,-317.907,-319.477,-320.685,-321.816], 'diam':[1.056,0.877,0.877,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.613,0.613,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.264,0.264,0.264,0.264] }, prefix + 'apic[48]': { 'x':[-369.377,-368.868,-369.001], 'y':[728.596,728.853,729.446], 'z':[-20.031,-18.610,-17.351], 'diam':[0.349,0.264,0.264] }, prefix + 'apic[90]': { 'x':[-380.344,-377.873,-376.028,-375.083,-374.022,-371.998,-371.004,-369.502,-367.979,-368.221,-367.901,-368.675,-367.791,-368.599,-368.650], 'y':[724.015,722.870,724.168,722.390,722.279,721.505,720.499,721.433,721.332,722.116,722.974,721.697,722.709,721.204,721.906], 'z':[-44.355,-43.085,-41.437,-39.030,-38.067,-36.429,-34.992,-34.486,-33.082,-31.540,-30.933,-29.551,-29.546,-28.180,-26.366], 'diam':[0.613,0.613,0.613,0.613,0.528,0.528,0.528,0.528,0.613,0.613,0.613,0.613,0.613,0.613,0.613] }, prefix + 'apic[34]': { 'x':[-371.406,-373.446,-374.045,-375.082], 'y':[719.126,720.902,722.725,723.155], 'z':[-51.397,-50.313,-48.625,-47.527], 'diam':[1.933,1.234,1.234,1.234] }, prefix + 'soma': { 'x':[-297.841,-296.129,-294.417], 'y':[712.070,707.901,703.732], 'z':[-90.454,-89.770,-89.086], 'diam':[9.117,9.117,9.117] }, prefix + 'apic[44]': { 'x':[-365.089,-365.966,-366.538,-366.585,-366.373,-365.923], 'y':[732.271,732.384,732.702,732.198,732.093,731.595], 'z':[-3.214,-0.623,1.276,2.750,4.070,5.421], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'dend[7]': { 'x':[-300.796,-300.629,-299.381,-298.107,-296.935,-295.815,-297.338,-296.883,-295.403,-294.246,-293.197,-294.411,-295.384], 'y':[716.093,716.461,718.499,719.941,720.652,722.212,722.700,723.818,725.076,725.606,726.013,727.292,727.861], 'z':[-93.880,-97.054,-98.171,-97.995,-97.600,-97.415,-98.277,-100.250,-100.297,-100.731,-101.787,-103.411,-103.483], 'diam':[2.639,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847] }, prefix + 'apic[51]': { 'x':[-371.266,-370.307,-369.473], 'y':[727.211,726.650,726.158], 'z':[-30.669,-30.517,-29.787], 'diam':[0.792,0.442,0.442] }, prefix + 'dend[1]': { 'x':[-305.424,-304.042,-302.853,-301.401,-301.475,-300.185,-299.370,-298.648,-297.367,-296.733,-296.589,-296.564,-295.410,-294.247,-293.738,-293.850,-292.744,-292.152,-291.235,-291.015,-290.358,-290.719,-290.732,-289.687,-289.078,-288.530,-288.398,-288.768,-289.694,-291.113,-291.647,-290.869,-289.664,-289.045,-289.208,-289.575,-288.697,-287.855,-287.774,-287.870,-288.258,-287.918,-288.898,-289.985,-291.039,-290.634,-289.983,-289.708,-289.081,-288.893,-288.390,-288.861,-288.311,-289.781,-289.462,-289.582,-288.727,-287.871,-286.490,-286.391,-286.640,-286.069,-285.657,-286.066,-285.516,-284.870,-284.029,-283.113,-282.856,-282.601,-283.255,-282.010,-281.988,-281.796,-281.050,-281.154,-280.658,-279.152,-276.654,-275.812,-275.296,-275.576,-275.747,-274.804,-274.308,-273.451,-273.500,-274.257,-274.079,-273.230,-271.422,-270.993,-271.541,-271.849,-271.412,-271.399,-272.308,-272.909,-272.324,-271.094,-270.359,-270.459,-270.600,-269.870,-268.826,-267.621,-266.871,-265.858,-264.683,-264.741,-264.610,-263.893,-262.818,-262.468,-262.149,-261.449,-260.954,-260.040,-259.115,-257.052,-257.087,-256.522,-256.485,-256.763,-257.396,-257.902,-257.965,-257.688,-257.164], 'y':[657.846,657.791,657.893,657.814,657.019,656.482,656.563,655.737,654.890,654.083,653.043,651.499,651.047,650.917,649.724,648.757,647.762,646.524,645.859,645.206,644.845,645.449,645.536,645.856,645.241,645.518,645.860,646.617,645.696,645.313,644.061,643.927,643.242,642.669,641.119,639.853,638.957,638.146,636.354,635.362,635.940,635.534,634.786,633.929,632.889,632.434,632.389,631.401,630.361,628.448,627.315,625.868,625.358,623.596,622.671,622.106,620.987,619.894,618.554,617.114,615.494,614.186,612.488,611.281,610.310,609.927,610.067,608.745,607.589,606.562,604.617,604.482,603.054,602.084,602.371,600.515,599.739,600.062,600.860,600.380,599.933,598.475,597.205,596.701,595.451,594.543,593.467,591.978,592.247,590.802,590.391,589.646,588.469,588.695,587.992,587.962,587.366,585.678,584.292,583.218,582.187,581.145,579.203,578.520,578.122,577.192,576.552,576.048,576.075,575.140,574.006,573.708,574.957,575.148,575.296,575.967,576.599,576.663,576.532,576.820,576.110,576.379,576.314,575.493,574.309,573.159,572.010,571.139,568.656], 'z':[-86.353,-85.529,-85.081,-85.081,-84.108,-83.038,-82.162,-82.382,-82.418,-82.809,-82.436,-82.485,-82.104,-81.102,-80.896,-81.498,-81.182,-80.628,-80.760,-78.686,-77.214,-76.173,-74.987,-73.858,-72.479,-71.627,-70.503,-69.472,-69.583,-68.837,-67.928,-67.179,-66.627,-65.977,-66.335,-66.195,-65.980,-65.711,-65.095,-64.514,-63.447,-62.578,-61.868,-62.631,-62.426,-61.430,-60.244,-59.620,-58.465,-58.266,-56.615,-56.255,-55.507,-54.016,-53.469,-52.455,-51.468,-51.645,-50.379,-50.081,-47.948,-46.420,-45.712,-45.465,-44.915,-44.095,-43.288,-43.068,-43.100,-42.232,-41.208,-40.582,-39.689,-39.174,-38.423,-36.285,-35.165,-34.167,-33.331,-32.431,-31.376,-30.655,-30.141,-29.144,-28.431,-28.655,-28.135,-27.252,-25.953,-25.375,-25.486,-24.248,-22.363,-21.133,-20.396,-19.227,-18.697,-18.745,-18.398,-18.727,-19.260,-19.073,-18.625,-18.097,-17.512,-16.403,-16.166,-15.700,-14.756,-13.758,-14.177,-12.613,-9.986,-8.810,-7.134,-6.015,-4.744,-3.132,-2.168,-1.488,-0.362,0.628,1.713,3.046,2.575,1.905,1.594,1.117,0.154], 'diam':[0.706,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[89]': { 'x':[-379.163,-380.344], 'y':[723.461,724.015], 'z':[-44.007,-44.355], 'diam':[0.877,0.613] }, prefix + 'apic[47]': { 'x':[-372.570,-371.402,-370.112,-369.377], 'y':[730.628,729.969,729.136,728.596], 'z':[-21.545,-21.283,-21.133,-20.031], 'diam':[0.528,0.349,0.349,0.349] }, prefix + 'apic[135]': { 'x':[-403.344,-404.833,-405.705,-406.717], 'y':[738.048,739.098,739.762,739.828], 'z':[-43.286,-43.078,-42.839,-42.726], 'diam':[0.442,0.264,0.264,0.264] }, prefix + 'apic[91]': { 'x':[-368.650,-367.768,-366.866,-366.207,-366.046], 'y':[721.906,721.405,720.902,720.854,719.602], 'z':[-26.366,-26.208,-25.987,-24.898,-24.003], 'diam':[0.613,0.613,0.613,0.613,0.613] }, prefix + 'apic[5]': { 'x':[-364.098,-362.553], 'y':[717.234,717.930], 'z':[-39.614,-39.618], 'diam':[0.706,0.442] }, prefix + 'apic[75]': { 'x':[-389.242,-388.895,-388.210,-388.241,-388.144,-387.602,-387.273,-387.188,-386.756,-386.127,-385.543,-385.309,-385.814], 'y':[737.183,738.243,739.209,739.894,741.103,741.980,742.475,743.913,744.573,745.087,745.377,745.847,746.839], 'z':[-16.218,-12.900,-9.258,-7.620,-5.404,-3.018,-1.408,0.555,2.090,4.370,6.626,8.162,9.799], 'diam':[0.613,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528] }, prefix + 'apic[134]': { 'x':[-403.344,-402.905,-403.123,-403.736,-403.761,-404.028,-404.588,-405.416,-406.891,-407.591,-408.446,-409.223,-410.226,-411.601,-412.837], 'y':[738.048,738.367,738.915,738.747,739.105,739.715,740.437,741.376,741.669,742.078,741.766,742.791,742.719,742.498,741.671], 'z':[-43.286,-41.803,-40.778,-39.230,-38.238,-37.158,-36.282,-35.290,-34.281,-33.621,-32.949,-31.983,-31.129,-30.446,-29.820], 'diam':[0.442,0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[59]': { 'x':[-369.473,-370.332,-370.901,-371.241,-371.721,-372.168,-372.791,-373.585,-375.066,-375.746,-377.356,-378.685,-380.662,-381.393,-382.332], 'y':[726.158,726.320,727.055,727.076,727.030,727.498,728.226,728.932,730.561,730.807,731.445,731.398,732.496,733.263,734.055], 'z':[-29.787,-28.427,-27.366,-26.320,-25.163,-24.110,-23.312,-22.837,-21.048,-19.973,-19.261,-19.341,-18.252,-17.209,-15.994], 'diam':[0.442,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[129]': { 'x':[-398.619,-398.144,-396.833,-395.620,-394.129,-393.195,-391.656], 'y':[742.819,744.039,744.242,744.354,744.977,745.242,745.878], 'z':[-31.263,-30.283,-29.397,-29.496,-29.474,-29.020,-28.572], 'diam':[0.528,0.442,0.442,0.349,0.349,0.349,0.349] }, prefix + 'apic[121]': { 'x':[-395.218,-394.442,-392.681,-392.662,-392.284,-391.833,-391.694,-391.831,-391.358,-390.996,-390.826,-390.616,-390.174,-389.856,-389.471,-389.975,-389.094,-388.217], 'y':[740.049,740.470,742.068,742.957,743.347,744.253,744.763,745.305,746.466,746.931,747.742,748.447,749.095,749.411,749.985,751.045,751.172,750.404], 'z':[-36.531,-34.248,-32.785,-30.706,-29.154,-28.049,-26.876,-25.779,-24.940,-23.069,-22.177,-20.901,-18.759,-17.774,-16.807,-15.021,-13.488,-11.011], 'diam':[0.613,0.528,0.528,0.528,0.528,0.528,0.442,0.442,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[110]': { 'x':[-385.468,-387.572,-389.788,-391.006,-392.106,-393.081], 'y':[724.833,724.673,724.627,724.242,723.925,723.019], 'z':[-44.329,-45.429,-45.203,-43.626,-42.591,-41.593], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[106]': { 'x':[-402.452,-403.941,-404.936,-406.279,-407.311,-408.710,-410.147,-411.321,-412.445,-414.348,-415.722,-416.569,-417.334,-418.375], 'y':[733.848,734.898,734.288,735.318,736.342,736.824,737.289,737.867,738.070,738.011,738.010,738.637,738.109,737.668], 'z':[-36.376,-36.168,-36.322,-35.927,-35.044,-34.549,-34.458,-34.444,-34.199,-34.411,-33.981,-33.486,-32.905,-32.090], 'diam':[0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[84]': { 'x':[-399.225,-400.103,-401.110,-401.373,-401.164,-401.370,-402.264,-403.218,-403.813,-404.231,-404.721,-405.639,-406.121,-406.493], 'y':[733.084,733.197,733.796,734.209,734.694,735.575,736.320,736.465,737.091,736.996,737.832,737.431,737.661,737.447], 'z':[-25.820,-24.007,-23.049,-22.161,-21.072,-19.401,-18.681,-17.993,-17.246,-15.982,-14.545,-12.813,-11.146,-10.109], 'diam':[0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[138]': { 'x':[-395.800,-395.965,-396.134,-396.609,-397.328,-398.070,-399.140], 'y':[733.524,732.992,732.306,731.152,730.447,729.318,729.053], 'z':[-49.182,-50.780,-51.807,-53.077,-54.235,-54.980,-55.770], 'diam':[0.528,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[71]': { 'x':[-376.862,-378.454,-379.163], 'y':[723.172,723.508,723.461], 'z':[-46.307,-44.748,-44.007], 'diam':[0.706,0.877,0.877] }, prefix + 'apic[46]': { 'x':[-373.328,-374.274,-375.465], 'y':[731.957,734.034,733.094], 'z':[-19.495,-19.446,-19.025], 'diam':[0.349,0.349,0.349] }, prefix + 'apic[67]': { 'x':[-401.322,-403.370,-405.274,-406.226,-407.264,-408.568,-409.344,-409.866], 'y':[743.117,744.299,744.453,744.789,745.350,745.594,745.888,746.372], 'z':[-23.836,-23.740,-23.604,-22.887,-21.930,-21.080,-20.374,-19.399], 'diam':[0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[119]': { 'x':[-390.228,-390.976,-392.517,-393.740,-394.546], 'y':[733.473,734.446,735.745,736.353,737.443], 'z':[-48.183,-46.963,-44.675,-42.952,-41.888], 'diam':[0.792,0.613,0.613,0.613,0.528] }, prefix + 'apic[72]': { 'x':[-379.163,-380.181,-381.890,-382.134], 'y':[723.461,724.379,725.773,726.717], 'z':[-44.007,-42.596,-40.784,-40.431], 'diam':[0.877,0.613,0.706,0.706] }, prefix + 'dend[11]': { 'x':[-294.791,-293.140,-292.783,-290.713,-290.655,-290.188,-288.506,-287.280,-286.090,-284.912,-285.133,-283.721,-282.796,-282.623,-282.502], 'y':[710.004,713.461,715.652,716.458,716.473,716.604,717.441,717.570,718.762,718.895,719.742,719.885,720.735,721.054,721.731], 'z':[-86.422,-85.845,-85.220,-83.665,-82.255,-81.122,-81.177,-80.922,-80.404,-79.352,-78.063,-77.651,-76.237,-74.944,-73.572], 'diam':[1.056,0.970,0.792,0.792,0.792,0.706,0.706,0.706,0.613,0.613,0.613,0.613,0.613,0.613,0.613] }, prefix + 'apic[122]': { 'x':[-388.217,-386.515,-385.184,-383.909,-382.779], 'y':[750.404,748.284,748.026,747.797,747.609], 'z':[-11.011,-11.024,-12.036,-12.709,-13.393], 'diam':[0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[49]': { 'x':[-369.377,-368.228,-367.476,-366.543], 'y':[728.596,727.114,725.964,725.221], 'z':[-20.031,-20.326,-19.765,-18.258], 'diam':[0.349,0.264,0.264,0.264] }, prefix + 'dend[5]': { 'x':[-316.649,-318.958,-318.981,-319.333,-320.244,-321.413,-322.842,-324.481,-325.669,-326.839,-328.090,-329.139,-330.198,-331.295,-333.278,-332.747,-331.998,-332.347,-332.276,-332.415,-332.778,-333.568,-333.965,-333.579,-332.436,-332.341,-332.329,-333.431,-333.684,-334.871,-335.965,-336.832,-337.691,-337.277,-336.875,-336.846,-337.515,-337.397,-338.426,-339.039,-339.107,-339.004,-339.427,-340.204,-340.455,-341.852,-342.206,-342.441,-343.182,-344.209,-343.085,-342.254,-344.055,-344.947,-344.602,-343.618,-343.279,-342.908,-343.759,-345.362,-346.787,-347.350,-346.364,-347.149,-347.365,-347.640,-348.724,-349.710,-351.060,-350.389,-350.014,-351.023,-352.021,-351.911,-353.296,-354.248,-354.893,-356.258,-357.746,-358.774,-359.466,-359.599,-361.041,-362.928,-364.470,-365.607,-366.839,-367.907,-369.602,-371.029,-372.248,-372.467,-372.430,-374.338,-375.407,-376.527,-377.433,-378.730,-379.878,-380.990,-381.925,-383.621,-384.549,-386.062,-386.751,-387.244,-388.160,-389.073,-390.029,-390.853,-391.545,-392.577,-393.437,-393.721,-395.070,-396.529,-397.119,-397.932,-398.996,-399.741,-401.409,-402.944,-404.120,-404.359,-405.317,-406.802,-407.860,-409.152,-410.414,-411.510,-412.517,-413.068,-413.433,-413.952,-414.417,-414.571,-414.548,-414.383], 'y':[714.484,716.593,718.184,716.186,717.644,718.233,719.091,719.448,719.313,719.418,720.599,721.048,721.170,721.395,721.354,722.579,723.203,723.854,724.553,724.896,725.306,725.287,725.570,725.498,726.193,727.513,728.054,728.854,729.625,729.489,731.018,731.739,732.271,732.529,734.471,736.637,737.154,738.074,738.658,739.201,739.808,742.433,743.500,743.371,744.331,744.318,744.245,745.964,746.608,747.151,747.645,748.057,749.000,750.458,751.448,752.148,753.193,754.235,755.250,755.168,754.970,756.855,757.453,757.620,757.751,758.042,758.596,758.589,759.962,760.707,761.837,762.908,763.340,763.650,764.305,765.202,766.530,768.380,769.992,770.601,771.804,772.282,772.908,773.040,773.002,772.898,772.962,772.991,773.544,773.667,773.671,774.578,775.392,775.525,775.479,776.353,776.592,776.886,776.758,776.634,777.459,778.340,778.455,779.689,780.327,780.651,780.483,780.313,781.298,781.902,783.166,783.597,784.795,784.952,784.832,784.678,784.742,785.722,786.506,786.587,787.436,788.051,788.074,787.471,788.881,789.500,789.952,790.847,791.594,791.883,791.638,791.490,792.315,793.171,793.332,794.332,794.514,795.050], 'z':[-111.225,-112.096,-112.778,-112.952,-112.086,-112.363,-112.727,-112.864,-113.338,-113.360,-113.583,-113.837,-114.419,-114.901,-115.908,-116.220,-117.276,-118.195,-118.920,-120.715,-121.987,-122.726,-123.758,-125.640,-127.540,-128.067,-129.492,-130.248,-131.623,-132.098,-132.665,-133.357,-134.616,-135.596,-135.639,-135.664,-136.645,-135.985,-135.773,-136.517,-137.608,-138.234,-138.390,-139.128,-140.062,-140.115,-141.237,-142.085,-143.330,-144.870,-145.470,-146.247,-147.042,-148.025,-148.484,-149.022,-150.634,-151.207,-153.307,-153.989,-154.985,-155.852,-156.962,-157.833,-159.045,-160.161,-160.904,-161.222,-162.184,-162.331,-163.013,-163.759,-164.807,-166.084,-167.110,-166.909,-166.093,-166.035,-165.757,-165.335,-165.266,-164.286,-164.368,-164.008,-164.724,-164.839,-165.324,-165.097,-165.881,-166.721,-167.310,-168.314,-169.388,-170.169,-170.854,-172.060,-172.520,-173.703,-174.731,-175.178,-175.785,-176.946,-178.194,-179.466,-180.153,-181.245,-182.477,-183.588,-185.357,-185.715,-186.803,-187.278,-189.062,-191.056,-193.691,-194.063,-195.156,-197.145,-197.544,-199.456,-200.944,-202.405,-203.334,-204.265,-205.276,-206.048,-206.190,-206.854,-207.607,-208.433,-209.774,-211.073,-212.885,-214.262,-216.731,-219.673,-221.165,-222.107], 'diam':[1.056,0.792,0.792,0.792,0.792,0.792,0.792,0.613,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[97]': { 'x':[-362.285,-362.051,-362.069,-362.465,-362.054], 'y':[721.533,722.002,722.743,722.616,725.244], 'z':[-9.374,-7.838,-6.037,-4.512,-3.277], 'diam':[0.442,0.349,0.349,0.349,0.349] }, prefix + 'dend[9]': { 'x':[-294.830,-295.019,-296.705,-298.463,-299.485,-300.396,-300.541,-300.711,-300.967,-301.287,-302.167,-303.836,-304.771,-305.265,-305.334,-304.783,-304.938,-306.477,-306.579,-306.605,-306.689,-307.224,-308.364,-309.162,-309.453,-309.910,-311.716,-313.958,-314.448,-313.862,-313.425,-314.097,-315.684,-317.108,-317.128,-317.402,-317.895,-319.382,-320.558,-320.194,-321.449,-322.181,-323.190,-323.992,-325.336,-326.664,-328.158,-329.705,-330.207,-330.231,-329.519,-328.997,-329.664,-330.116,-329.647,-328.969,-328.500,-330.009,-330.995,-331.880,-332.206,-330.894,-330.321,-330.754,-331.398,-330.727,-330.165,-329.455,-329.211,-329.932,-330.788,-331.039,-330.200,-329.123,-330.442,-331.822,-332.370,-332.965,-333.966,-335.342,-336.305,-337.337,-338.062,-337.802,-336.979,-337.241,-337.839,-337.862,-337.650,-339.262,-340.757,-340.760,-339.830,-340.562,-341.519,-342.628,-343.668,-343.146,-343.413,-345.207,-345.814,-346.727,-348.098,-349.362,-350.359,-350.885,-350.409,-350.328,-350.100,-350.166,-351.863,-352.672,-352.830,-351.990,-351.964,-352.901,-353.631,-354.191,-353.962,-353.052,-352.448,-352.575,-352.585,-352.488,-352.743,-353.489,-352.411,-351.461,-351.838,-353.632,-354.914,-356.387,-357.193,-358.372,-359.149,-360.096,-360.043,-359.621,-359.522,-359.528,-359.507,-359.366,-358.791,-357.691,-358.258,-359.288,-360.272,-362.296,-361.057,-361.591,-360.769,-359.677,-359.492,-360.772,-362.029,-363.020,-362.052,-362.053,-362.828,-364.067,-365.062,-366.401,-368.134,-369.346,-370.330,-370.535,-371.044,-371.190,-371.517,-373.030,-374.155,-376.178,-377.205,-379.135,-379.908,-379.591,-381.050,-382.671,-384.904,-385.771,-386.850,-387.624,-389.130,-390.054,-390.873,-389.911,-390.880,-392.670,-393.909,-395.051,-394.087,-393.367,-394.004,-394.952,-395.290,-394.891,-394.160,-393.017,-391.815,-391.271,-392.436,-393.456,-393.611,-392.471,-392.044,-392.390,-392.691,-393.166,-395.432,-394.087,-392.539,-391.980,-391.454,-391.349,-393.052,-394.609,-394.727,-394.135,-392.862,-391.741,-391.197,-392.902,-394.211,-394.537,-395.048,-393.304,-393.007,-393.454,-394.327,-395.345,-395.379,-394.668,-393.616,-392.766,-391.684,-391.898,-393.057,-393.293,-392.370,-393.288,-395.177,-395.728,-394.366,-394.033,-395.375,-396.420,-397.630,-399.400,-400.338,-401.494,-402.032,-402.541,-402.933,-404.294,-405.208,-406.295,-407.326,-408.671,-409.401,-411.009,-410.883,-411.841,-414.295,-415.304,-416.806,-417.313,-417.892,-419.029,-420.457,-420.779,-420.403,-421.253,-422.369,-421.540,-421.434,-421.200,-420.936,-421.233,-422.947,-424.726,-425.650,-426.884,-426.475,-426.529,-427.484,-428.742,-429.364,-429.870,-430.119,-428.618,-430.383,-431.852,-432.922,-433.970,-433.098,-432.312,-431.996,-431.601,-432.153,-431.739,-433.528,-432.767,-431.738,-432.515,-432.570,-433.421,-433.545,-432.803,-432.798,-433.210,-433.374,-432.580,-433.241,-433.819,-434.415,-434.811,-434.381,-434.951,-437.417,-438.549,-439.545,-440.883,-441.895,-443.236,-443.498,-444.618,-445.658,-447.702,-448.539,-449.584,-451.291,-452.933,-454.340,-456.504,-459.001,-460.314,-461.831,-463.193,-465.030,-466.279,-468.057,-469.173,-470.487,-471.485,-472.819,-473.561,-474.700,-475.830,-475.782,-476.661,-477.651,-478.943,-479.486,-480.410,-479.879,-480.702,-481.437,-480.497,-480.641,-480.652,-482.521,-483.324,-484.395,-485.971,-486.452], 'y':[745.482,744.352,743.219,743.800,744.449,746.007,746.859,747.858,749.656,750.480,751.048,753.750,754.930,756.068,756.744,758.140,759.155,760.524,761.354,762.503,763.005,763.440,763.998,764.570,764.898,764.869,764.346,764.319,765.107,766.001,767.422,769.417,769.880,770.429,771.439,772.813,775.088,776.363,777.119,779.079,779.481,780.412,780.724,781.609,781.305,779.904,782.475,783.082,783.100,784.517,785.215,786.928,787.447,787.683,788.110,788.990,789.803,789.930,790.079,790.062,790.946,791.931,793.595,793.963,794.357,795.361,796.090,796.402,796.803,797.787,798.493,799.800,800.938,801.769,802.525,802.648,802.886,802.852,803.499,804.297,804.842,805.280,806.123,807.350,807.879,808.693,809.383,810.764,811.272,811.338,811.427,811.822,812.431,813.547,814.073,814.577,815.709,816.688,817.727,819.067,819.690,819.794,817.293,818.399,818.671,820.298,822.874,823.842,824.717,825.499,825.296,825.238,826.200,826.766,827.593,827.854,828.093,828.450,829.209,830.051,830.441,831.215,831.978,832.821,833.120,834.227,835.383,836.194,836.766,837.168,836.616,837.484,838.267,838.488,838.633,839.115,840.373,841.928,843.574,844.835,846.355,847.361,848.759,850.050,850.851,852.153,852.547,853.898,855.096,855.972,856.997,857.214,857.943,857.957,858.348,858.326,860.524,861.790,862.292,862.392,862.175,862.586,862.080,861.735,861.481,862.462,864.487,865.461,866.392,867.722,868.078,868.574,868.716,868.865,869.618,869.901,870.340,870.872,870.916,872.019,872.045,873.016,873.280,873.350,873.508,874.412,875.846,876.039,876.271,877.669,878.962,879.867,880.266,880.881,881.525,883.278,884.233,884.794,885.859,887.392,887.771,888.566,889.325,890.103,890.860,891.566,892.443,892.672,893.165,894.595,895.287,896.465,896.900,898.008,899.305,900.586,900.818,901.506,902.470,902.988,904.741,905.246,906.312,908.023,908.740,910.493,911.581,912.613,912.874,913.624,915.199,916.316,916.536,916.706,917.052,918.717,919.789,920.528,921.368,921.923,922.993,923.102,923.804,924.601,924.933,924.925,925.005,925.497,925.938,926.734,927.705,928.522,928.871,929.140,929.739,929.885,929.840,929.580,930.295,930.619,930.764,931.272,931.176,931.755,931.502,932.505,933.405,933.900,934.629,935.894,937.165,937.775,939.299,940.168,941.640,943.283,944.239,946.413,946.528,946.015,945.659,947.900,948.609,949.588,949.989,949.789,949.972,950.591,950.699,952.564,952.515,953.117,953.166,953.969,955.103,956.117,957.570,959.134,960.239,961.239,961.663,962.324,963.749,963.905,961.947,962.811,964.146,965.825,966.270,966.956,967.559,968.192,968.472,968.900,970.231,970.887,971.103,971.058,971.829,972.074,971.811,972.336,973.337,975.128,976.087,976.664,976.993,976.606,976.604,977.364,977.966,979.931,980.712,980.760,981.149,982.842,983.566,984.157,984.343,984.565,984.960,984.705,984.286,984.373,984.471,984.652,984.938,984.708,985.375,985.914,985.511,986.685,988.974,992.202,993.280,994.033,995.336,997.476,998.370,999.680,1001.725,1002.479,1002.545,1004.289,1006.041], 'z':[-106.725,-109.001,-108.739,-108.583,-108.530,-109.027,-110.074,-110.539,-111.014,-111.748,-111.112,-109.931,-109.796,-110.057,-111.248,-111.649,-112.218,-110.520,-109.243,-108.272,-107.280,-106.377,-106.834,-105.948,-104.900,-103.802,-103.701,-104.527,-104.958,-105.431,-105.847,-105.773,-104.451,-104.119,-105.376,-105.796,-106.933,-107.209,-107.178,-107.401,-107.662,-107.640,-107.868,-107.973,-108.780,-111.078,-111.654,-112.237,-113.297,-113.470,-114.266,-114.728,-115.497,-116.532,-117.827,-118.942,-119.958,-120.840,-120.978,-121.715,-122.088,-122.474,-123.397,-125.086,-127.132,-128.463,-128.913,-129.988,-131.190,-131.565,-132.212,-133.454,-133.032,-133.007,-133.891,-134.875,-136.128,-137.427,-138.890,-139.330,-139.656,-140.119,-141.324,-141.272,-140.139,-141.090,-141.841,-143.167,-144.467,-143.976,-143.472,-144.685,-145.027,-145.724,-145.835,-145.715,-146.900,-147.905,-148.020,-146.709,-145.856,-145.334,-146.157,-146.100,-146.461,-146.981,-148.361,-149.509,-150.767,-148.395,-147.469,-146.155,-144.677,-143.876,-142.637,-142.195,-141.415,-140.370,-138.440,-136.463,-135.128,-133.322,-131.525,-129.821,-127.852,-126.957,-126.535,-126.276,-125.204,-124.914,-122.076,-120.340,-119.029,-119.870,-120.930,-122.629,-123.057,-123.305,-122.765,-121.249,-120.840,-121.504,-122.923,-123.271,-121.958,-121.172,-120.607,-119.529,-119.662,-119.014,-118.052,-117.621,-116.620,-115.651,-114.760,-114.241,-113.129,-111.731,-111.145,-110.962,-111.166,-110.723,-110.574,-110.537,-110.832,-111.761,-112.573,-114.296,-115.125,-114.001,-112.972,-113.209,-114.375,-114.555,-113.352,-112.165,-111.832,-112.856,-113.402,-112.279,-110.489,-111.888,-113.526,-114.229,-115.044,-117.066,-117.402,-118.132,-118.265,-117.808,-117.967,-118.300,-119.307,-121.780,-122.981,-123.681,-124.349,-124.124,-123.505,-123.657,-123.993,-124.409,-125.114,-125.915,-126.492,-127.790,-128.509,-129.527,-129.894,-130.940,-131.949,-132.699,-133.438,-134.220,-133.799,-135.302,-136.435,-137.355,-137.192,-136.527,-135.854,-135.750,-136.588,-136.873,-137.603,-137.112,-137.211,-138.369,-138.829,-139.236,-139.855,-139.136,-137.927,-137.191,-136.999,-137.042,-138.456,-139.750,-139.278,-138.564,-137.944,-138.976,-139.081,-140.226,-141.159,-141.426,-141.461,-141.932,-142.262,-142.554,-143.842,-146.616,-147.514,-147.864,-149.089,-149.461,-149.851,-150.039,-150.895,-151.377,-150.339,-148.826,-149.043,-148.904,-148.525,-146.954,-145.606,-144.923,-144.310,-144.874,-144.941,-145.590,-145.796,-145.791,-144.587,-144.171,-145.085,-144.277,-143.979,-143.878,-143.040,-142.802,-143.534,-142.986,-141.908,-141.910,-143.482,-144.777,-146.473,-146.765,-147.099,-147.926,-148.816,-149.406,-149.876,-150.466,-151.011,-151.435,-150.980,-149.861,-149.800,-150.081,-149.384,-148.444,-147.844,-146.951,-148.078,-149.628,-150.950,-151.670,-152.860,-153.838,-154.822,-156.033,-157.488,-159.356,-160.253,-161.386,-162.532,-162.487,-162.628,-162.317,-161.640,-161.902,-162.831,-162.415,-161.915,-161.242,-160.431,-161.141,-161.516,-160.725,-161.089,-160.943,-161.476,-160.734,-160.286,-160.674,-159.941,-160.474,-160.646,-160.657,-160.211,-159.288,-159.365,-160.144,-161.011,-161.364,-160.617,-159.636,-159.971,-159.261,-158.119,-157.558,-157.351,-156.804,-156.222,-155.675,-155.124,-155.682,-157.387,-157.305,-157.856,-157.899,-158.404], 'diam':[1.584,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.141,1.141,1.141,1.056,1.056,1.056,1.056,1.056,1.056,1.056,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,1.141,1.141,1.141,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.706,0.706,0.706,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.528,0.528,0.528,0.528] }, prefix + 'apic[133]': { 'x':[-395.800,-396.659,-398.062,-399.762,-401.076,-401.844,-402.367,-402.802,-403.344], 'y':[733.524,734.243,734.271,734.799,735.448,736.263,736.813,737.474,738.048], 'z':[-49.182,-48.793,-48.810,-47.874,-46.669,-45.895,-45.210,-44.141,-43.286], 'diam':[0.528,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442] }, prefix + 'apic[52]': { 'x':[-369.473,-368.533], 'y':[726.158,725.556], 'z':[-29.787,-29.616], 'diam':[0.442,0.349] }, prefix + 'apic[60]': { 'x':[-375.585,-374.330,-373.399], 'y':[726.541,725.473,724.744], 'z':[-37.841,-38.464,-38.753], 'diam':[0.613,0.349,0.349] }, prefix + 'apic[29]': { 'x':[-363.474,-361.593,-360.236,-356.998,-355.747,-354.171], 'y':[708.950,709.223,709.329,710.767,711.430,711.753], 'z':[-30.479,-31.285,-31.665,-31.946,-31.404,-31.184], 'diam':[0.442,0.442,0.442,0.442,0.442,0.442] }, prefix + 'apic[83]': { 'x':[-396.249,-397.668,-398.580,-399.275,-398.445,-399.225], 'y':[731.890,732.937,732.567,731.888,733.471,733.084], 'z':[-29.596,-29.295,-29.020,-28.390,-27.647,-25.820], 'diam':[0.442,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[141]': { 'x':[-405.528,-407.064,-407.997,-409.379,-410.668,-413.057,-414.735,-415.819], 'y':[741.655,740.806,741.126,741.189,741.166,742.567,742.282,742.290], 'z':[-49.825,-48.485,-47.945,-47.974,-48.236,-47.509,-46.876,-46.560], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[32]': { 'x':[-374.047,-375.377,-376.578,-376.863,-376.698,-376.712,-375.809,-375.324,-373.768,-373.132,-372.237,-370.628,-368.896,-365.873], 'y':[713.597,714.397,714.061,713.488,713.107,711.757,711.765,711.906,711.252,711.417,711.263,710.982,709.197,709.878], 'z':[-36.870,-36.237,-35.099,-34.175,-33.014,-30.618,-29.134,-28.005,-27.161,-25.704,-24.674,-24.485,-24.259,-25.370], 'diam':[1.056,0.613,0.613,0.613,0.613,0.528,0.528,0.528,0.528,0.528,0.528,0.264,0.264,0.264] }, prefix + 'apic[10]': { 'x':[-361.157,-360.269,-359.369,-358.779,-357.548,-356.271], 'y':[717.776,716.766,715.817,715.534,714.767,714.283], 'z':[-40.571,-41.634,-42.525,-43.829,-45.002,-46.011], 'diam':[0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'dend[3]': { 'x':[-298.473,-300.796], 'y':[711.113,716.093], 'z':[-91.333,-93.880], 'diam':[2.111,2.639] }, prefix + 'apic[96]': { 'x':[-356.531,-355.340,-355.120,-355.284,-355.345,-355.552,-355.564,-355.514,-356.372,-356.873,-357.634,-358.764,-359.947,-359.490], 'y':[719.306,718.169,718.525,719.169,719.818,720.428,721.228,721.833,721.206,721.586,722.125,722.048,723.032,725.088], 'z':[-4.255,-4.066,-2.835,-1.689,-0.632,0.534,1.869,2.673,3.478,5.167,6.038,7.003,8.150,8.067], 'diam':[0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[57]': { 'x':[-365.713,-366.883,-367.364,-367.951,-367.590,-366.086,-365.206,-365.642], 'y':[723.216,724.451,724.954,725.173,725.573,726.170,726.953,728.929], 'z':[-29.929,-28.596,-27.811,-26.825,-25.103,-24.034,-21.788,-19.918], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[14]': { 'x':[-349.325,-348.724,-348.591,-347.995,-347.016], 'y':[719.230,719.576,719.953,720.240,720.597], 'z':[-30.168,-28.356,-27.211,-26.319,-25.730], 'diam':[0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[101]': { 'x':[-380.344,-381.313,-383.489], 'y':[724.015,724.347,724.129], 'z':[-44.355,-45.068,-44.607], 'diam':[0.613,0.613,0.613] }, prefix + 'apic[86]': { 'x':[-382.134,-383.162,-383.728], 'y':[726.717,727.850,729.654], 'z':[-40.431,-37.872,-36.522], 'diam':[0.706,0.264,0.264] }, prefix + 'apic[88]': { 'x':[-383.728,-385.207,-385.674,-387.048,-388.106,-388.561,-388.470,-389.568], 'y':[729.654,730.487,731.331,733.054,734.254,735.086,734.935,735.387], 'z':[-36.522,-36.485,-37.028,-36.814,-36.334,-37.654,-39.407,-40.369], 'diam':[0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'dend[10]': { 'x':[-294.830,-295.640,-295.450,-294.694,-294.726,-293.419,-294.203,-295.289,-295.734,-296.180,-295.141,-293.543,-292.051,-290.781,-289.723,-289.378,-288.088,-286.941,-285.542,-284.092,-283.645,-284.772,-285.999,-287.526,-288.461,-287.967,-287.483,-286.755,-286.283,-287.194,-287.998,-287.085,-285.126,-284.878,-285.347,-285.881,-286.782,-287.650,-289.126,-290.105,-289.804,-289.077,-288.715,-287.721,-287.381,-287.442,-288.738,-289.723,-289.561,-288.807,-287.963,-287.514,-286.662,-284.561,-282.570,-281.217,-279.802,-280.861,-279.524,-278.765,-278.790,-278.763,-279.020,-279.999,-281.548,-282.640,-284.015,-284.705,-286.890,-288.634,-289.180,-288.230,-287.276,-287.563,-288.513,-289.974,-290.591,-290.583,-290.845,-292.186,-291.397,-290.192,-288.949,-290.005,-290.912,-291.519,-292.976,-292.787,-291.593,-290.416,-290.066,-290.697,-292.022,-293.006,-294.076,-294.929,-296.013,-294.622,-293.443,-291.774,-290.253,-290.273,-290.721,-290.340,-290.745,-290.617,-290.264,-290.234,-290.235,-290.868,-292.060,-293.410,-292.706,-291.754,-290.734,-291.977,-291.036,-290.427,-291.333,-290.860,-289.640,-289.288,-287.986,-289.078,-289.939,-290.730,-289.432,-288.759,-288.180,-288.007,-288.023,-288.613,-286.807,-285.979,-286.101,-286.037,-285.054,-284.233,-282.866,-281.557,-280.836,-280.910,-281.131,-281.975,-282.513,-282.688,-282.261,-281.770,-280.603,-279.859,-280.361,-282.253,-283.264,-282.732,-282.137,-281.988,-282.627,-283.196,-284.436,-285.389,-284.651,-284.775,-285.236,-286.796,-286.976,-288.348,-289.963,-291.327,-291.775,-293.295,-294.377,-293.032,-292.165,-291.113,-290.569,-291.294,-292.152,-292.846,-293.153,-294.779,-295.386,-296.052,-295.753,-295.155,-295.122,-294.939,-294.601,-293.442,-292.931,-293.528,-294.743,-295.864,-296.547,-295.360,-294.388,-295.357,-295.475,-294.593,-294.070,-293.536,-293.127,-294.477,-296.176,-297.756,-296.429,-296.297,-297.212,-298.384,-299.767,-300.285,-299.916,-299.912,-298.850,-298.943,-299.973,-300.784,-299.826,-297.522,-296.326,-295.507,-295.883,-296.436,-296.757,-296.521,-295.509,-295.312,-294.807,-294.535,-293.400,-292.763,-292.063,-291.696,-291.394,-291.458,-290.967,-290.335,-289.100,-287.852,-286.254,-287.387,-287.607,-286.741,-286.054,-286.971,-287.103,-286.690,-286.365,-285.563,-285.540,-286.532,-285.872,-284.207,-284.595,-285.816,-284.811,-283.500,-282.449,-281.391,-280.330,-279.739,-280.892,-281.820,-281.522,-280.317,-279.438,-279.451,-279.025,-278.612,-277.884,-277.873,-278.237,-279.036,-280.243,-279.809,-280.535,-282.726,-282.178,-281.502,-280.590,-279.864,-280.728,-281.723,-281.630,-279.935,-279.132,-278.168,-278.580,-279.378,-278.334,-277.403,-276.584,-275.921,-275.876,-276.302,-277.218,-277.648,-277.335,-276.456,-274.987,-273.699,-273.814,-273.212,-272.275,-271.599,-271.412,-271.380,-270.604,-270.203,-269.480,-268.753,-268.081,-267.393,-267.292,-266.883,-267.076,-265.014,-264.290,-264.039,-262.618,-261.282,-262.425,-262.780,-263.712,-264.416,-265.944,-265.798,-266.823,-268.222,-268.103,-269.320,-271.102,-271.123,-272.291,-273.089,-273.453,-273.855,-274.027,-274.532,-273.968,-273.611,-273.352,-273.484,-274.913,-275.586,-276.510,-277.437,-278.891,-279.648,-280.840,-281.086], 'y':[745.482,746.323,747.646,748.524,749.509,750.408,750.717,750.473,751.163,751.672,752.517,753.937,754.461,754.845,755.100,755.777,756.626,757.502,758.334,759.625,760.588,761.357,761.442,761.090,760.913,760.945,762.316,762.545,762.904,764.097,764.358,764.552,765.070,766.644,767.398,768.069,769.216,769.587,769.847,770.637,771.453,773.289,774.297,774.342,774.418,774.815,775.468,776.002,776.513,777.358,778.200,778.183,778.263,778.834,779.155,780.377,781.161,781.504,782.205,782.355,783.203,783.838,783.955,783.918,785.194,785.959,785.531,785.061,786.160,786.973,787.759,788.539,788.709,789.764,790.141,790.409,790.725,792.382,794.290,794.376,795.120,796.156,796.591,796.930,797.444,797.650,798.326,800.033,801.091,801.919,802.892,802.836,802.817,802.335,802.608,802.521,802.740,803.561,804.290,804.856,805.304,805.871,807.286,808.349,809.460,810.533,812.071,812.684,814.192,814.926,815.572,815.459,816.363,816.928,818.213,819.281,820.935,821.483,822.190,823.709,824.308,825.288,826.651,827.713,828.176,828.912,829.962,830.335,832.120,833.286,834.188,835.165,836.239,836.385,837.249,838.348,839.166,840.376,841.048,841.790,842.943,843.781,843.652,843.947,844.110,844.899,846.084,847.766,849.226,849.725,850.301,851.091,851.636,853.324,854.041,855.905,856.635,856.565,856.063,856.572,857.087,858.036,858.036,858.056,859.055,859.708,860.245,860.190,859.869,859.759,859.923,860.517,861.216,862.943,864.205,864.936,865.443,865.994,865.909,866.688,867.465,868.476,869.473,870.247,871.910,872.280,873.615,874.409,875.413,876.129,875.783,875.408,876.724,877.666,878.364,879.340,880.762,881.410,882.182,882.953,884.001,884.930,885.758,887.083,888.550,889.544,889.899,889.804,890.602,891.153,893.699,894.523,895.364,896.593,896.473,896.544,897.133,898.282,899.547,899.869,900.375,900.356,901.662,902.902,904.082,906.131,906.871,907.288,908.810,909.763,910.461,912.949,914.172,914.976,915.570,916.028,916.328,917.520,918.260,919.557,920.576,921.229,922.115,922.527,923.203,924.092,925.082,927.253,927.829,928.464,929.980,931.387,932.136,932.684,933.712,934.132,934.658,935.104,935.552,936.227,936.293,936.471,937.334,938.134,938.779,940.212,942.746,943.796,944.968,946.523,946.690,946.777,947.102,948.325,949.385,950.040,950.809,951.698,952.073,953.409,954.081,953.945,953.993,955.051,955.992,956.772,957.517,957.635,958.779,959.302,960.151,960.590,962.092,962.801,963.434,964.650,965.940,966.991,967.431,968.398,970.102,970.935,971.441,972.836,973.836,974.492,976.023,977.468,979.159,980.782,981.800,982.252,982.646,983.729,984.908,986.277,987.098,988.355,989.613,990.823,992.339,993.678,994.871,995.314,996.185,996.949,998.115,998.006,998.924,999.465,999.977,1002.189,1003.349,1004.127,1004.972,1006.830,1007.091,1008.878,1007.774,1008.625,1009.830,1011.138,1013.236,1013.463,1013.742,1014.491,1015.413,1016.021,1018.192,1019.920], 'z':[-106.725,-104.402,-104.064,-105.445,-106.001,-106.473,-104.117,-103.170,-102.444,-101.508,-101.794,-102.603,-103.570,-103.782,-102.764,-101.798,-100.892,-101.175,-100.829,-100.758,-101.246,-102.691,-103.914,-104.208,-103.566,-102.440,-101.815,-100.972,-100.156,-98.965,-97.658,-96.445,-96.068,-93.927,-91.931,-90.748,-90.137,-90.569,-90.075,-89.299,-88.788,-88.856,-89.000,-89.185,-87.971,-86.985,-86.747,-87.989,-89.510,-89.606,-88.312,-86.854,-85.780,-85.595,-85.738,-85.687,-85.357,-83.492,-82.024,-79.331,-77.932,-76.449,-75.302,-74.549,-74.478,-74.313,-73.870,-71.212,-70.170,-69.143,-68.174,-66.429,-65.554,-64.304,-64.075,-64.588,-65.380,-65.188,-64.173,-64.129,-64.564,-65.174,-64.485,-63.024,-62.444,-61.532,-61.997,-61.327,-60.672,-60.399,-59.243,-57.332,-55.693,-53.745,-53.310,-52.796,-53.290,-52.888,-53.648,-54.069,-53.707,-52.611,-51.893,-51.522,-50.270,-49.679,-50.393,-51.238,-50.596,-48.377,-47.794,-46.851,-45.562,-45.900,-45.350,-43.929,-43.680,-42.775,-41.480,-40.714,-40.116,-40.549,-40.557,-39.679,-39.453,-39.636,-38.637,-37.882,-37.865,-38.062,-36.700,-35.705,-36.511,-35.637,-34.191,-33.022,-33.222,-34.066,-34.252,-33.754,-33.343,-32.566,-30.887,-28.946,-27.472,-26.474,-25.632,-27.004,-27.216,-26.436,-25.253,-25.039,-23.424,-22.626,-23.425,-22.851,-20.523,-19.297,-18.398,-17.367,-15.204,-14.075,-12.833,-12.804,-13.841,-13.836,-13.393,-12.565,-10.576,-9.190,-8.195,-7.708,-7.581,-8.690,-9.316,-8.804,-7.427,-6.598,-5.595,-4.446,-4.042,-2.491,-2.252,-3.511,-3.892,-2.930,-2.765,-2.181,-1.357,-0.847,-0.820,-0.324,0.825,0.517,0.975,2.527,3.594,3.823,3.353,2.890,3.022,3.419,2.312,0.806,-0.126,-0.806,-1.147,-0.974,-1.390,-3.061,-2.988,-1.294,-0.937,0.570,0.398,1.515,2.532,2.299,2.493,3.130,4.770,6.001,7.164,7.421,6.901,7.835,9.644,10.954,10.951,11.536,12.329,12.501,13.680,14.802,13.975,13.243,13.209,12.701,12.519,11.419,10.613,9.228,9.590,9.142,8.299,7.389,7.281,7.670,6.708,6.404,6.254,5.790,4.953,4.958,5.346,5.327,5.203,5.285,5.377,4.556,3.731,2.570,1.539,1.672,1.891,3.192,4.060,4.201,4.478,5.106,6.028,7.042,7.709,8.668,9.557,9.323,10.453,10.808,11.682,11.403,12.586,13.792,15.628,16.146,16.291,16.414,17.735,18.413,19.380,19.355,19.484,20.120,21.858,23.521,23.897,25.154,24.176,24.435,24.281,24.012,23.389,21.977,21.220,21.698,22.128,23.446,22.439,23.721,22.972,22.885,22.978,23.583,25.097,24.869,24.064,25.024,24.068,23.733,24.628,23.602,23.076,22.187,21.743,20.545,19.059,18.104,17.099,16.873,15.830,14.866,13.575,13.336,13.575,12.418,11.819,11.885,10.431,10.393,10.053,9.326,8.989,8.659,8.666,10.176,11.015,11.316,11.096,10.590,9.106,9.400], 'diam':[1.584,1.405,1.405,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.056,1.056,1.056,1.056,1.141,1.141,1.141,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,0.877,0.877,0.877,0.877,0.877,0.877,0.970,1.056,1.234,1.234,1.234,1.234,1.234,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.405,1.405,1.141,1.141,1.141,1.056,1.056,1.056,1.056,1.056,1.056,1.056,0.877,0.877,0.877,0.877,0.877,0.877,0.877,0.877,0.877,0.877,0.877,0.877,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,1.056,1.056,1.056,1.056,1.056,1.056,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,1.141,1.141,1.141,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.706,0.706,0.706,0.706,0.613,0.613,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528] }, prefix + 'apic[53]': { 'x':[-368.533,-367.013,-365.713], 'y':[725.556,724.272,723.216], 'z':[-29.616,-30.325,-29.929], 'diam':[0.349,0.349,0.349] }, prefix + 'apic[1]': { 'x':[-307.800,-309.439,-311.572,-313.045,-313.279,-315.185,-316.904,-318.742,-320.373,-321.410,-321.222,-321.668,-323.198,-324.584,-325.879,-326.960,-327.741,-328.353,-328.294,-328.457,-329.281,-330.732,-331.515,-332.332,-333.168,-334.237,-336.066,-337.787,-339.737,-340.831,-341.487,-342.366,-342.826,-343.405,-344.321,-345.188,-346.907,-348.249,-349.687,-351.307,-352.654,-354.178,-355.769,-356.813,-358.275,-359.786,-361.096,-363.107,-364.527,-365.814], 'y':[701.708,701.662,700.645,700.201,700.482,701.080,700.706,700.313,700.961,702.195,702.784,703.712,703.310,704.513,704.891,705.222,704.637,704.477,704.542,704.697,705.028,704.913,704.687,704.686,704.855,705.066,705.481,705.046,704.039,703.520,704.217,705.076,705.891,706.454,707.485,708.339,709.030,709.653,710.322,710.922,710.819,711.232,711.320,711.501,712.310,713.047,714.291,714.824,716.382,717.747], 'z':[-88.086,-90.825,-90.843,-89.633,-88.540,-88.394,-88.943,-89.127,-88.912,-87.526,-85.778,-84.205,-81.907,-81.152,-80.442,-79.474,-78.447,-77.487,-76.303,-74.644,-73.606,-74.331,-75.064,-75.881,-76.500,-77.378,-78.038,-78.291,-77.378,-76.514,-75.711,-74.685,-73.416,-70.455,-68.446,-67.427,-67.078,-67.054,-67.400,-68.040,-67.660,-67.217,-66.905,-66.742,-65.842,-64.732,-63.742,-61.937,-60.204,-58.901], 'diam':[2.111,2.290,1.933,1.762,1.762,1.762,1.762,1.762,1.762,2.111,2.111,2.111,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.847] }, prefix + 'axon': { 'x':[-295.384,-292.833,-291.698,-290.797,-290.500,-290.190,-290.049,-289.817,-289.077,-288.859], 'y':[727.861,726.253,727.784,728.697,729.609,729.827,730.979,731.298,731.819,732.157], 'z':[-103.483,-106.215,-107.317,-107.620,-108.480,-109.789,-111.454,-112.411,-114.434,-116.668], 'diam':[1.847,0.792,0.792,0.792,0.613,0.613,0.613,0.613,0.613,0.613] }, prefix + 'apic[103]': { 'x':[-385.468,-386.636,-387.519], 'y':[724.833,725.405,726.008], 'z':[-44.329,-43.700,-43.616], 'diam':[0.349,0.349,0.442] }, prefix + 'apic[36]': { 'x':[-377.821,-376.611,-375.585], 'y':[725.564,725.842,726.541], 'z':[-41.334,-38.724,-37.841], 'diam':[0.792,0.528,0.613] }, prefix + 'apic[143]': { 'x':[-392.313,-393.149,-393.620,-395.844,-396.906,-397.972], 'y':[732.909,733.729,735.242,733.712,733.360,733.506], 'z':[-53.049,-52.525,-52.809,-51.594,-50.897,-50.708], 'diam':[0.442,0.085,0.085,0.085,0.085,0.085] }, prefix + 'apic[65]': { 'x':[-399.375,-401.214,-402.006,-403.047,-404.055,-405.285,-406.241], 'y':[745.313,746.594,747.718,748.440,748.906,749.265,749.621], 'z':[-22.443,-22.214,-22.578,-22.794,-22.473,-21.685,-21.414], 'diam':[0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[81]': { 'x':[-405.902,-406.027,-406.669], 'y':[732.221,731.166,729.976], 'z':[-32.098,-33.508,-33.897], 'diam':[0.264,0.179,0.179] }, prefix + 'apic[111]': { 'x':[-393.081,-391.578,-390.541,-390.563], 'y':[723.019,723.229,722.316,720.782], 'z':[-41.593,-41.918,-41.138,-40.745], 'diam':[0.349,0.349,0.349,0.349] }, prefix + 'apic[7]': { 'x':[-361.157,-360.532,-359.778,-359.362], 'y':[717.776,716.952,716.330,715.202], 'z':[-40.571,-39.099,-37.884,-36.885], 'diam':[0.264,0.264,0.264,0.264] }, prefix + 'apic[139]': { 'x':[-382.274,-384.558,-385.357,-386.809,-389.189,-390.467,-391.748,-392.313], 'y':[727.857,729.161,729.749,730.364,731.240,731.586,731.815,732.910], 'z':[-51.928,-52.365,-52.188,-52.683,-52.171,-51.808,-51.728,-53.049], 'diam':[0.877,0.442,0.442,0.442,0.442,0.442,0.442,0.442] }, prefix + 'apic[22]': { 'x':[-363.474,-362.344], 'y':[708.950,708.536], 'z':[-30.479,-29.530], 'diam':[0.442,0.528] }, prefix + 'apic[61]': { 'x':[-377.821,-378.506], 'y':[725.564,727.022], 'z':[-41.334,-41.156], 'diam':[0.792,0.349] }, prefix + 'dend[12]': { 'x':[-282.502,-282.951,-283.264,-282.651,-281.742,-281.836,-281.521,-281.167,-280.261,-278.950,-277.874,-277.453,-276.385,-275.693,-276.174,-275.823,-274.889,-275.709,-275.128,-274.394,-273.690,-273.799,-275.126,-274.183,-273.470,-273.059,-272.762,-272.434,-271.538,-270.287,-270.580,-269.918,-268.621,-268.176,-268.772,-268.324,-267.145,-266.008,-265.314,-264.971,-264.444,-264.715,-264.102,-263.089,-262.318,-261.276,-261.048,-260.969,-261.047,-260.995,-260.433,-259.366,-258.657,-257.841,-257.720,-256.785,-254.819,-253.896,-252.407,-251.150,-250.773,-249.012,-247.861,-247.108,-246.989,-246.580,-247.266,-247.012,-247.095,-247.104,-247.176,-245.840,-245.147,-244.552,-243.213,-242.054,-241.056,-240.447,-239.043,-238.465,-238.359,-235.924,-235.064,-233.719,-232.133,-231.126,-230.411,-230.062,-229.061,-228.056,-227.361,-225.939,-224.848,-223.318,-222.018,-221.262,-219.883,-219.418,-218.863,-217.762,-216.335,-215.267,-214.578,-213.499,-212.182,-211.160,-210.388,-210.073,-209.702,-209.145,-208.096,-207.482,-205.906,-204.867,-204.319,-203.235,-200.866,-200.512,-200.397,-200.008,-199.882,-199.628,-199.439,-199.189,-198.568,-197.782,-196.711,-195.691,-194.392,-193.562,-192.465,-191.441,-190.536,-189.684,-189.133,-188.724,-188.509,-188.375,-188.037,-187.356,-187.103,-187.114,-187.182,-186.890,-186.045,-185.187,-184.586,-183.717], 'y':[721.731,723.508,723.561,724.266,724.692,725.009,725.765,726.947,727.081,727.791,729.214,729.553,729.779,730.419,730.667,731.556,731.831,732.378,734.065,734.694,736.106,736.763,737.736,738.712,740.218,740.703,742.478,743.779,744.535,745.910,747.546,748.483,748.466,749.956,750.926,753.573,753.809,753.092,754.314,755.303,757.112,758.114,759.318,759.846,761.132,761.416,762.450,762.994,763.931,764.339,764.522,764.748,765.485,766.124,766.848,767.021,767.323,767.592,767.866,768.377,770.324,771.279,772.052,772.812,773.893,775.147,776.156,778.003,778.891,779.908,780.645,781.069,781.416,782.234,783.380,783.523,784.005,785.152,786.327,787.191,790.048,793.872,793.985,794.966,795.667,796.979,797.446,798.496,799.618,800.332,801.033,802.141,802.513,803.300,803.648,804.033,804.516,805.384,806.469,806.778,806.996,807.415,807.991,809.207,810.207,811.315,812.667,813.882,815.138,817.123,818.453,820.292,821.042,821.963,823.055,823.899,825.768,826.825,828.414,828.547,828.693,829.568,829.804,830.557,833.493,834.459,834.796,835.914,836.508,837.483,838.077,838.960,839.785,840.605,842.354,843.259,843.669,844.165,846.122,846.735,847.718,848.847,851.647,854.513,855.301,857.066,858.903,860.322], 'z':[-73.572,-71.714,-70.740,-70.083,-69.566,-68.090,-67.158,-66.572,-65.932,-64.657,-64.282,-63.052,-63.774,-63.428,-61.807,-61.097,-59.996,-57.996,-57.633,-58.102,-58.156,-57.410,-57.063,-55.885,-56.053,-54.848,-54.316,-54.799,-53.840,-53.668,-53.023,-52.715,-51.782,-50.625,-50.462,-50.540,-50.076,-49.559,-49.490,-48.790,-48.794,-48.568,-49.802,-48.691,-49.076,-49.689,-48.428,-47.404,-45.153,-43.898,-42.737,-42.300,-41.507,-41.256,-39.876,-39.346,-38.258,-37.726,-37.085,-36.387,-35.717,-35.065,-34.755,-34.767,-35.285,-34.454,-34.442,-34.274,-33.770,-33.024,-31.931,-31.790,-30.726,-31.139,-30.806,-30.214,-29.579,-29.062,-29.067,-28.310,-27.902,-27.288,-26.747,-27.252,-27.594,-27.358,-26.750,-26.558,-26.077,-25.115,-24.638,-24.803,-24.489,-24.380,-23.826,-23.016,-22.225,-21.896,-21.462,-21.240,-20.661,-19.088,-18.378,-18.703,-17.718,-16.214,-15.894,-15.373,-14.520,-13.688,-13.791,-14.670,-15.015,-14.632,-14.196,-14.143,-12.727,-12.539,-11.731,-9.870,-8.835,-7.615,-6.134,-4.674,-4.366,-3.797,-3.234,-2.879,-2.554,-2.432,-1.216,-0.727,-0.114,1.058,2.127,3.010,4.037,5.623,6.422,7.134,7.202,7.447,7.930,8.199,8.336,8.112,8.494,8.937], 'diam':[0.613,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.349,0.349,0.349,0.349,0.349,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.613,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[0]': { 'x':[-297.860,-301.678,-304.183,-306.007,-306.943,-307.800], 'y':[705.320,703.593,702.770,702.413,701.533,701.708], 'z':[-86.808,-85.198,-84.344,-84.329,-85.871,-88.086], 'diam':[3.082,2.197,2.290,2.026,2.026,2.111] }, prefix + 'apic[69]': { 'x':[-378.506,-379.512,-381.424,-381.525,-382.168,-382.693,-382.760,-382.899,-382.684], 'y':[727.022,729.156,729.306,732.428,733.429,734.979,735.904,736.649,737.085], 'z':[-41.156,-39.212,-37.874,-37.467,-36.173,-34.131,-33.186,-32.499,-31.557], 'diam':[0.349,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179] }, prefix + 'apic[63]': { 'x':[-398.247,-398.575,-399.375], 'y':[742.846,744.331,745.313], 'z':[-24.556,-23.585,-22.443], 'diam':[0.349,0.264,0.264] }, prefix + 'apic[43]': { 'x':[-365.089,-364.095,-363.786,-363.053,-361.267,-360.283,-359.567,-359.700,-359.717,-359.359,-358.745,-358.229,-357.819,-357.919,-356.174,-353.860,-352.695,-351.931,-352.066,-351.850,-352.304,-352.948,-355.406,-357.292,-358.293,-359.474], 'y':[732.271,731.448,730.651,730.469,731.074,731.081,731.639,732.750,733.367,733.577,733.590,733.950,734.561,734.489,735.624,735.539,735.280,735.259,736.319,737.215,738.411,739.295,738.353,738.555,738.629,738.284], 'z':[-3.214,-1.161,-0.621,0.093,1.827,3.405,5.921,7.997,9.324,10.252,11.257,12.974,15.144,17.122,18.674,21.851,23.084,24.246,26.174,27.649,29.726,30.552,31.291,31.413,30.925,30.508], 'diam':[0.349,0.349,0.349,0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[8]': { 'x':[-359.362,-358.113,-357.193,-355.757], 'y':[715.202,714.929,715.687,716.173], 'z':[-36.885,-35.572,-35.639,-35.725], 'diam':[0.264,0.264,0.264,0.264] }, prefix + 'apic[19]': { 'x':[-374.047,-372.254,-371.023], 'y':[713.597,714.780,715.203], 'z':[-36.870,-35.253,-34.276], 'diam':[1.056,0.877,0.877] }, prefix + 'apic[99]': { 'x':[-366.046,-365.031,-364.659,-363.949,-363.236,-362.423,-360.957,-359.890,-358.716,-358.415], 'y':[719.602,718.590,717.328,715.568,714.673,713.731,712.309,710.972,710.110,709.056], 'z':[-24.003,-24.716,-25.226,-24.867,-25.013,-25.397,-26.244,-25.981,-25.904,-25.699], 'diam':[0.613,0.442,0.442,0.442,0.442,0.442,0.349,0.349,0.349,0.349] }, prefix + 'apic[55]': { 'x':[-352.948,-352.323,-351.955], 'y':[715.283,716.032,715.597], 'z':[-36.221,-38.168,-39.754], 'diam':[0.349,0.349,0.349] }, prefix + 'apic[131]': { 'x':[-394.546,-395.178,-396.816,-398.059,-397.235,-397.128,-397.378], 'y':[737.443,739.653,741.496,742.931,744.586,745.804,746.403], 'z':[-41.888,-40.861,-37.837,-35.203,-34.149,-33.312,-32.400], 'diam':[0.528,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[41]': { 'x':[-373.328,-372.916,-372.633,-371.503,-370.648,-369.763,-369.576,-368.603,-367.886,-367.894,-366.920,-366.165], 'y':[731.957,732.107,732.450,733.358,733.361,732.488,732.939,733.302,733.131,732.243,732.328,732.626], 'z':[-19.495,-18.466,-17.135,-14.191,-12.347,-12.156,-11.053,-9.863,-8.978,-8.057,-5.991,-4.049], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[50]': { 'x':[-371.908,-372.309,-372.937,-373.834,-374.959,-375.629,-376.311], 'y':[728.584,729.840,730.617,731.047,731.564,732.200,733.169], 'z':[-28.319,-29.607,-28.661,-27.823,-27.087,-25.832,-24.348], 'diam':[0.528,0.528,0.528,0.528,0.528,0.528,0.528] }, prefix + 'apic[2]': { 'x':[-365.814,-368.681,-369.788,-371.406], 'y':[717.747,716.931,718.424,719.126], 'z':[-58.901,-54.958,-53.035,-51.397], 'diam':[1.847,1.584,1.584,1.933] }, prefix + 'apic[54]': { 'x':[-365.713,-364.794,-362.683,-361.201,-359.872,-358.804,-357.848,-356.380,-355.525,-353.766,-353.747,-352.948], 'y':[723.216,722.433,722.539,721.362,720.292,719.760,719.542,718.712,717.942,717.817,714.841,715.283], 'z':[-29.929,-30.380,-30.793,-31.476,-32.613,-32.996,-33.401,-33.869,-34.407,-35.302,-35.166,-36.221], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[64]': { 'x':[-399.375,-398.949,-399.553,-399.921,-399.534,-399.055,-399.483,-399.929], 'y':[745.313,745.642,746.537,746.527,747.841,748.931,749.579,750.448], 'z':[-22.443,-20.947,-19.709,-18.472,-17.861,-17.348,-16.449,-15.017], 'diam':[0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[142]': { 'x':[-405.528,-406.701,-406.364,-406.662,-406.591], 'y':[741.655,742.240,743.432,744.356,745.500], 'z':[-49.825,-50.398,-51.126,-51.799,-52.130], 'diam':[0.349,0.179,0.179,0.179,0.179] }, prefix + 'apic[92]': { 'x':[-366.046,-365.415,-364.489,-363.874,-363.707,-364.266,-364.450,-365.429,-365.583], 'y':[719.602,719.723,719.788,719.926,720.335,719.706,719.971,721.388,722.216], 'z':[-24.003,-22.716,-21.068,-20.212,-19.074,-17.789,-16.837,-14.735,-12.958], 'diam':[0.613,0.528,0.613,0.613,0.613,0.613,0.613,0.528,0.528] }, prefix + 'apic[18]': { 'x':[-374.024,-373.888,-374.047], 'y':[715.198,714.772,713.597], 'z':[-38.925,-37.744,-36.870], 'diam':[0.877,1.056,1.056] }, prefix + 'apic[13]': { 'x':[-349.325,-347.331,-346.054,-345.056,-342.992,-341.074,-340.066], 'y':[719.230,718.763,718.732,718.538,718.594,719.015,719.613], 'z':[-30.168,-28.903,-28.790,-28.614,-27.790,-26.946,-26.354], 'diam':[0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[39]': { 'x':[-371.908,-371.971,-372.031,-373.102,-372.570], 'y':[728.584,729.114,730.297,730.468,730.628], 'z':[-28.319,-27.122,-25.843,-23.092,-21.545], 'diam':[0.528,0.528,0.528,0.528,0.528] }, prefix + 'apic[105]': { 'x':[-389.321,-390.872,-393.230,-394.618,-396.495,-397.479,-399.359,-399.787,-400.428,-401.421,-402.452], 'y':[727.188,728.427,728.388,728.865,729.325,729.974,731.639,732.220,732.834,733.481,733.848], 'z':[-42.050,-41.305,-40.826,-40.309,-39.867,-39.531,-38.747,-37.997,-36.897,-36.561,-36.376], 'diam':[0.349,0.264,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[20]': { 'x':[-371.023,-370.904,-369.504,-368.649,-367.762,-366.881,-366.462,-366.015,-365.121], 'y':[715.203,713.839,712.684,711.914,711.232,710.620,710.628,710.137,711.058], 'z':[-34.276,-33.412,-34.011,-34.549,-34.357,-33.825,-32.826,-31.468,-31.344], 'diam':[0.877,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528] }, prefix + 'apic[95]': { 'x':[-356.531,-356.357,-356.211,-356.847,-357.411,-358.043,-358.371,-358.373,-358.634,-359.241,-359.446,-359.670], 'y':[719.306,719.576,720.009,720.683,721.485,722.612,723.484,724.753,725.350,726.192,726.729,728.162], 'z':[-4.255,-2.374,-1.081,-0.433,0.168,1.329,2.493,4.341,5.251,6.353,7.364,8.825], 'diam':[0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[66]': { 'x':[-398.247,-400.434,-401.322], 'y':[742.846,743.042,743.117], 'z':[-24.556,-24.298,-23.836], 'diam':[0.349,0.264,0.264] }, prefix + 'apic[70]': { 'x':[-375.082,-376.862], 'y':[723.155,723.172], 'z':[-47.527,-46.307], 'diam':[1.234,0.706] }, prefix + 'apic[78]': { 'x':[-389.242,-389.545,-388.952,-389.614,-390.274,-390.847,-391.293,-391.250,-391.190,-391.189,-391.486,-391.589,-390.671,-388.347,-386.753,-385.610,-385.313,-384.984,-384.001,-383.552], 'y':[737.183,735.720,733.874,733.561,734.323,734.985,734.122,736.084,737.218,737.671,737.249,737.279,737.752,737.795,738.020,737.726,736.788,734.907,734.454,733.489], 'z':[-16.218,-13.950,-13.821,-12.543,-11.407,-10.686,-9.825,-9.253,-8.996,-7.876,-6.916,-5.461,-4.066,-1.801,-0.859,0.388,1.668,2.830,3.889,4.727], 'diam':[0.613,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[93]': { 'x':[-365.583,-364.150,-363.331,-362.285], 'y':[722.216,721.800,721.663,721.533], 'z':[-12.958,-11.684,-10.733,-9.374], 'diam':[0.528,0.442,0.442,0.442] }, prefix + 'apic[62]': { 'x':[-378.506,-380.569,-381.467,-382.632,-384.092,-385.209,-386.393,-388.285,-389.493,-390.521,-391.530,-392.829,-393.886,-394.462,-395.274,-396.035,-397.312,-398.247], 'y':[727.022,727.879,728.886,729.984,731.203,732.263,733.444,733.643,734.731,735.347,736.427,737.673,738.514,739.576,740.314,740.502,741.987,742.846], 'z':[-41.156,-40.311,-39.264,-38.405,-37.744,-36.764,-35.594,-34.708,-33.653,-33.310,-32.279,-31.289,-30.422,-28.716,-27.909,-27.083,-25.326,-24.556], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[136]': { 'x':[-406.717,-406.842,-406.977,-407.200,-408.059,-409.312,-410.009,-411.043,-411.962,-412.473], 'y':[739.828,741.628,742.776,744.472,746.314,747.375,748.252,749.408,750.198,751.598], 'z':[-42.726,-41.140,-40.697,-39.503,-37.905,-37.289,-36.712,-35.956,-35.512,-35.486], 'diam':[0.264,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[117]': { 'x':[-365.814,-367.647,-369.685,-370.483,-371.252,-372.316,-375.201,-377.544,-378.792,-380.006,-381.261,-382.274], 'y':[717.747,719.096,719.119,720.159,720.974,721.842,724.816,724.496,725.215,726.053,727.121,727.857], 'z':[-58.901,-58.352,-57.224,-55.925,-55.151,-54.724,-53.864,-52.659,-52.857,-52.752,-52.129,-51.928], 'diam':[1.847,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.877,0.877,0.877,0.877] }, prefix + 'apic[9]': { 'x':[-359.362,-356.640,-355.265,-354.352], 'y':[715.202,714.247,713.181,712.601], 'z':[-36.885,-37.383,-37.494,-37.760], 'diam':[0.264,0.264,0.264,0.264] }, prefix + 'dend[8]': { 'x':[-295.384,-296.495,-296.116,-296.992,-298.077,-299.122,-300.559,-300.436,-299.709,-298.724,-298.273,-297.775,-297.079,-296.956,-296.054,-295.490,-294.830], 'y':[727.861,729.288,730.273,730.870,731.347,731.089,731.140,735.000,735.886,737.148,738.291,739.347,740.327,741.610,742.826,743.422,745.482], 'z':[-103.483,-104.712,-106.145,-106.773,-106.760,-106.621,-105.551,-104.625,-104.605,-104.497,-104.729,-104.954,-104.936,-105.431,-106.151,-106.776,-106.725], 'diam':[1.847,1.669,1.669,1.669,1.669,1.669,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.762,1.762,1.584] }, prefix + 'apic[102]': { 'x':[-383.489,-385.468], 'y':[724.129,724.833], 'z':[-44.607,-44.329], 'diam':[0.613,0.349] }, prefix + 'apic[128]': { 'x':[-399.616,-401.798,-402.972,-403.609,-403.999,-404.388], 'y':[745.693,745.255,745.453,747.194,748.202,749.145], 'z':[-30.891,-30.008,-30.181,-29.852,-28.906,-27.685], 'diam':[0.349,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[132]': { 'x':[-390.228,-391.727,-394.791,-395.800], 'y':[733.473,734.070,734.329,733.524], 'z':[-48.183,-49.096,-49.622,-49.182], 'diam':[0.792,0.706,0.528,0.528] }, prefix + 'dend[13]': { 'x':[-282.502,-281.179,-279.068,-274.478,-270.034,-267.279,-265.304,-263.436,-261.995,-260.552,-259.455,-256.293,-253.906,-250.930,-249.019,-247.267,-245.526,-243.939,-242.562,-240.274,-238.721,-236.088,-230.280,-228.669,-226.304,-222.644,-219.207,-217.921,-215.100,-208.235,-204.413,-202.147,-200.018,-198.458,-197.445,-196.573,-195.415,-191.684,-187.133,-182.885,-181.461,-180.007,-178.388,-176.229,-175.254], 'y':[721.731,722.004,723.160,724.226,724.383,725.578,725.697,725.942,726.813,726.959,727.027,727.705,729.561,729.834,730.007,730.099,730.249,731.363,731.823,733.516,734.054,733.441,733.966,734.152,735.442,735.854,736.203,736.349,737.546,738.344,740.001,739.138,739.435,739.589,739.736,739.886,739.781,740.257,740.750,740.146,740.713,740.905,741.130,741.030,740.302], 'z':[-73.572,-71.566,-70.034,-67.165,-65.426,-64.572,-64.516,-64.602,-64.593,-64.875,-65.110,-64.913,-65.462,-65.199,-64.920,-65.492,-65.483,-65.106,-64.616,-64.007,-63.245,-62.318,-61.707,-61.030,-60.615,-59.171,-57.778,-57.273,-55.282,-52.483,-50.745,-48.811,-47.342,-47.024,-46.245,-44.674,-42.222,-38.913,-35.537,-32.516,-30.047,-29.169,-28.034,-25.932,-22.899], 'diam':[0.613,0.264,0.264,0.264,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179] }, prefix + 'apic[127]': { 'x':[-399.616,-400.125,-401.188,-402.693,-403.063,-404.029,-405.162,-405.961,-406.889,-407.999,-408.825,-409.895,-411.317,-412.380,-414.016,-416.057], 'y':[745.693,746.627,747.490,747.541,748.467,748.010,747.465,748.104,749.220,749.996,750.788,751.048,750.530,749.923,749.656,750.351], 'z':[-30.891,-30.175,-29.754,-28.309,-27.250,-26.340,-25.308,-24.373,-23.269,-21.605,-19.879,-18.613,-17.488,-16.518,-16.074,-15.280], 'diam':[0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[21]': { 'x':[-365.121,-363.474], 'y':[711.058,708.950], 'z':[-31.344,-30.479], 'diam':[0.528,0.442] }, prefix + 'apic[15]': { 'x':[-357.306,-357.953,-358.543,-358.307,-357.732,-356.809,-356.076], 'y':[721.905,722.583,723.532,723.877,725.751,726.027,726.511], 'z':[-32.611,-31.955,-30.569,-29.507,-26.441,-25.210,-24.398], 'diam':[0.349,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[114]': { 'x':[-376.862,-379.421,-380.552,-383.412,-385.811,-386.994,-388.388,-389.631,-392.895,-394.120,-394.255,-395.800,-396.692,-398.766,-399.803,-401.202,-402.064,-403.169,-404.794,-405.774,-406.868,-407.931], 'y':[723.172,724.228,724.759,725.283,726.433,726.483,726.359,727.152,729.428,729.721,731.952,731.709,732.381,733.725,734.770,734.440,734.624,734.576,733.158,733.727,733.887,734.348], 'z':[-46.307,-46.385,-46.866,-47.067,-46.666,-46.106,-46.158,-46.032,-45.480,-45.010,-44.703,-43.578,-42.575,-42.272,-42.288,-41.140,-40.379,-39.449,-38.574,-37.948,-37.611,-37.540], 'diam':[0.706,0.264,0.264,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179] }, prefix + 'apic[124]': { 'x':[-395.218,-396.161], 'y':[740.049,740.635], 'z':[-36.531,-35.502], 'diam':[0.613,0.528] }, prefix + 'apic[56]': { 'x':[-352.948,-351.273,-350.249,-348.228,-348.113,-348.197,-347.632,-347.377,-346.946,-346.441,-345.613,-344.655,-344.943], 'y':[715.283,714.230,713.474,713.651,712.519,711.057,709.772,708.714,707.468,706.862,705.982,704.961,703.928], 'z':[-36.221,-36.445,-36.823,-36.410,-35.304,-34.842,-34.922,-35.743,-37.199,-37.864,-38.714,-39.081,-38.677], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[82]': { 'x':[-405.902,-407.297,-408.848], 'y':[732.221,732.785,733.089], 'z':[-32.098,-33.094,-32.949], 'diam':[0.264,0.179,0.179] }, prefix + 'apic[130]': { 'x':[-396.161,-398.034,-397.334,-397.495], 'y':[740.635,740.416,740.900,740.822], 'z':[-35.501,-35.141,-37.336,-38.423], 'diam':[0.528,0.442,0.442,0.442] }, prefix + 'apic[94]': { 'x':[-362.285,-361.149,-359.575,-358.524,-357.804,-356.531], 'y':[721.533,721.113,720.106,719.504,718.726,719.306], 'z':[-9.374,-8.588,-8.560,-7.890,-6.945,-4.255], 'diam':[0.442,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[126]': { 'x':[-398.619,-399.738,-399.616], 'y':[742.819,744.346,745.693], 'z':[-31.263,-30.987,-30.891], 'diam':[0.528,0.349,0.349] }, prefix + 'apic[3]': { 'x':[-371.406,-372.417,-372.673], 'y':[719.126,716.462,717.133], 'z':[-51.397,-47.815,-46.593], 'diam':[1.933,1.320,1.320] }, prefix + 'apic[115]': { 'x':[-407.931,-408.319,-408.983,-409.267,-410.037,-410.232], 'y':[734.348,734.773,734.294,733.803,733.106,731.915], 'z':[-37.540,-38.974,-40.124,-41.483,-42.736,-43.652], 'diam':[0.179,0.179,0.179,0.179,0.179,0.179] }, prefix + 'apic[108]': { 'x':[-389.321,-389.530,-389.118,-388.421], 'y':[727.188,727.856,726.793,727.252], 'z':[-42.050,-40.572,-39.254,-38.429], 'diam':[0.349,0.264,0.264,0.264] }, prefix + 'apic[109]': { 'x':[-387.519,-387.667,-387.601,-385.286,-384.275,-384.196,-383.470], 'y':[726.008,723.804,722.659,723.001,721.928,721.093,720.237], 'z':[-43.616,-41.851,-41.171,-41.428,-41.689,-41.134,-40.508], 'diam':[0.442,0.179,0.179,0.179,0.179,0.179,0.179] }, prefix + 'apic[31]': { 'x':[-371.023,-369.996,-368.275,-366.578,-364.028,-362.378,-360.430,-359.537,-358.501,-357.324,-355.998,-354.672,-353.303,-352.256,-351.262,-349.685,-348.048,-346.503,-345.326,-344.393,-342.099,-340.425,-339.322,-338.832,-338.595,-338.475], 'y':[715.203,715.492,714.918,714.227,713.160,713.006,712.710,712.563,711.978,711.327,710.644,709.959,709.768,709.245,708.781,708.300,707.690,706.771,706.252,706.123,705.165,705.637,706.128,706.994,707.596,708.870], 'z':[-34.276,-32.378,-31.056,-30.040,-28.583,-27.587,-26.725,-25.688,-25.449,-25.181,-24.752,-24.325,-24.147,-23.752,-23.472,-23.214,-22.729,-22.822,-22.693,-21.846,-20.846,-19.484,-17.307,-16.548,-15.746,-14.759], 'diam':[0.877,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'dend[4]': { 'x':[-300.796,-303.420,-304.396,-304.639,-304.904,-305.925,-307.246,-308.656,-311.137,-312.165,-313.188,-314.124,-314.766,-315.566,-315.748,-315.600,-315.493,-315.699,-315.748,-316.649], 'y':[716.093,710.231,710.087,709.975,710.842,711.041,711.141,711.319,711.187,711.050,711.441,711.362,711.243,711.238,711.308,712.082,712.817,713.528,714.129,714.484], 'z':[-93.880,-94.683,-95.573,-96.661,-98.055,-98.288,-97.644,-97.725,-98.699,-99.365,-99.730,-100.270,-101.097,-102.895,-104.329,-105.392,-106.339,-107.942,-109.158,-111.225], 'diam':[2.639,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056] }, prefix + 'apic[77]': { 'x':[-385.814,-387.864,-388.670,-390.076,-391.455,-392.138,-394.062,-395.158,-395.490,-396.204,-395.997,-397.187,-398.152], 'y':[746.839,748.160,748.352,749.396,750.519,751.189,752.030,752.532,753.696,754.445,755.114,756.660,757.438], 'z':[9.799,9.776,8.974,9.268,9.705,9.326,9.728,10.287,10.139,10.241,8.948,8.536,7.960], 'diam':[0.528,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[42]': { 'x':[-366.165,-365.089], 'y':[732.626,732.271], 'z':[-4.049,-3.214], 'diam':[0.349,0.349] }, prefix + 'apic[104]': { 'x':[-387.519,-388.274,-389.321], 'y':[726.008,726.607,727.188], 'z':[-43.616,-43.183,-42.050], 'diam':[0.442,0.264,0.349] }, prefix + 'apic[118]': { 'x':[-382.274,-384.573,-386.892,-388.468,-390.228], 'y':[727.857,729.727,731.663,733.064,733.473], 'z':[-51.928,-50.990,-49.939,-49.003,-48.183], 'diam':[0.877,1.056,0.792,0.792,0.792] }, prefix + 'apic[16]': { 'x':[-364.098,-365.222,-365.893,-365.640,-365.187,-364.924,-364.947,-364.845,-365.211,-366.166,-366.718,-367.281], 'y':[717.234,718.621,718.444,718.480,718.203,718.504,718.257,718.524,718.969,719.106,720.415,721.020], 'z':[-39.614,-38.003,-36.096,-34.491,-33.549,-32.212,-31.174,-30.159,-29.187,-27.900,-26.029,-25.451], 'diam':[0.706,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'dend[0]': { 'x':[-307.800,-307.179,-306.302,-306.083,-305.433,-305.160,-305.222,-304.997,-304.725,-304.760,-304.916,-304.505,-304.196,-305.303,-305.149,-305.921,-306.550,-306.430,-305.491,-305.073,-304.928,-304.692,-303.934,-303.942,-303.311,-302.670,-302.124,-301.481,-303.920,-304.030,-305.719,-306.337,-306.162,-305.845,-305.569,-305.424], 'y':[701.708,699.574,698.042,695.047,693.418,691.963,690.876,689.630,688.650,686.805,684.562,683.449,682.118,681.327,680.556,679.886,679.065,677.874,676.568,675.648,674.719,673.539,672.196,670.924,669.433,668.320,666.684,665.968,663.779,662.632,662.993,662.763,661.298,660.494,658.850,657.846], 'z':[-88.086,-88.520,-88.244,-87.580,-87.601,-87.742,-88.323,-88.410,-88.532,-88.895,-89.767,-88.696,-87.877,-87.823,-86.974,-87.010,-87.310,-87.318,-86.801,-86.787,-87.166,-87.545,-87.312,-88.116,-88.144,-87.922,-88.616,-89.352,-87.629,-86.651,-86.348,-87.263,-86.915,-86.321,-86.107,-86.353], 'diam':[2.111,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706] }, prefix + 'apic[30]': { 'x':[-365.121,-366.309,-367.132,-368.091,-368.656,-369.181,-369.119,-370.042,-370.639,-371.795,-373.048,-374.080,-374.673,-375.869,-377.759,-378.720], 'y':[711.058,711.498,712.628,712.844,713.499,713.697,713.946,714.720,715.024,715.585,715.645,716.135,716.893,718.224,718.344,718.231], 'z':[-31.344,-29.195,-27.424,-26.412,-25.076,-23.402,-22.212,-20.551,-19.677,-19.827,-19.521,-18.862,-17.477,-15.663,-14.487,-14.134], 'diam':[0.528,0.085,0.085,0.085,0.085,0.085,0.085,0.085,0.085,0.085,0.085,0.085,0.085,0.085,0.085,0.085] }, prefix + 'apic[24]': { 'x':[-359.839,-357.861,-356.382,-355.325,-354.069,-352.798,-350.928,-349.584,-348.536,-347.195,-346.434,-346.325,-344.670,-343.459,-341.726,-340.545,-338.510,-337.481], 'y':[708.648,707.673,707.210,706.873,707.477,707.517,706.996,706.426,705.919,705.026,703.478,702.475,702.192,701.844,701.207,700.881,700.126,699.833], 'z':[-26.957,-26.368,-24.825,-23.813,-23.258,-22.834,-22.217,-22.092,-22.306,-22.820,-22.635,-22.279,-23.122,-23.755,-23.955,-24.418,-25.199,-25.666], 'diam':[0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[26]': { 'x':[-362.344,-361.044,-359.445,-359.718,-358.479,-357.623,-356.858], 'y':[708.536,707.290,707.408,706.088,704.423,703.564,702.880], 'z':[-29.530,-30.521,-31.256,-30.925,-29.946,-29.593,-29.899], 'diam':[0.528,0.442,0.442,0.442,0.442,0.442,0.442] }, prefix + 'apic[11]': { 'x':[-362.553,-360.713,-359.161,-358.146,-357.358,-357.306], 'y':[717.930,718.424,718.829,718.997,719.890,721.905], 'z':[-39.618,-38.090,-37.388,-35.363,-33.925,-32.611], 'diam':[0.442,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[25]': { 'x':[-359.839,-362.730,-363.058], 'y':[708.648,709.793,712.303], 'z':[-26.957,-27.056,-28.228], 'diam':[0.264,0.264,0.264] }, prefix + 'apic[76]': { 'x':[-385.814,-385.050,-384.423,-384.739,-384.753,-384.541,-384.017,-382.640,-382.233,-381.434,-381.072,-380.494,-379.211,-378.434,-377.220,-375.562,-373.409,-371.705,-370.298], 'y':[746.839,746.885,746.938,747.673,747.939,749.302,750.256,751.094,751.909,752.912,753.445,754.150,754.104,754.153,754.170,754.718,755.134,755.118,755.149], 'z':[9.799,11.124,12.899,14.198,15.296,16.674,19.393,23.645,25.377,27.728,29.310,30.742,32.057,32.775,34.152,35.366,37.665,38.784,39.721], 'diam':[0.528,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[85]': { 'x':[-399.225,-398.068,-397.897,-397.019], 'y':[733.084,734.722,735.526,736.193], 'z':[-25.820,-24.604,-23.279,-22.718], 'diam':[0.349,0.264,0.264,0.264] }, prefix + 'apic[12]': { 'x':[-357.306,-355.747,-354.298,-352.999,-351.725,-350.264,-349.325], 'y':[721.905,721.142,720.205,720.362,720.262,719.496,719.230], 'z':[-32.611,-31.972,-32.145,-32.009,-31.451,-30.993,-30.168], 'diam':[0.349,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[98]': { 'x':[-365.583,-367.074,-369.466,-371.117,-372.070,-372.910,-375.096,-374.840,-373.944], 'y':[722.216,723.660,724.526,725.943,727.492,728.858,730.465,731.599,732.184], 'z':[-12.958,-11.771,-10.673,-9.816,-9.388,-9.066,-9.542,-9.288,-8.601], 'diam':[0.528,0.442,0.442,0.442,0.349,0.349,0.264,0.264,0.264] }, prefix + 'apic[17]': { 'x':[-372.673,-373.356,-374.241,-373.789,-372.972,-373.175,-374.024,-374.024], 'y':[717.133,718.444,718.162,717.255,715.986,714.858,714.745,715.198], 'z':[-46.593,-44.449,-42.837,-41.843,-42.279,-40.911,-40.045,-38.925], 'diam':[1.320,0.877,0.877,0.877,0.877,0.877,0.877,0.877] }, }
true
true
f725a28db4c34f0091289d14f2db993acdf9d82d
9,405
py
Python
core/addons/api/__init__.py
photos-network/core
dae64af83dccfa37fc0923370072a360da941c28
[ "Apache-2.0" ]
4
2020-12-30T12:48:46.000Z
2022-03-29T17:44:00.000Z
core/addons/api/__init__.py
photos-network/core
dae64af83dccfa37fc0923370072a360da941c28
[ "Apache-2.0" ]
null
null
null
core/addons/api/__init__.py
photos-network/core
dae64af83dccfa37fc0923370072a360da941c28
[ "Apache-2.0" ]
2
2021-01-24T19:13:53.000Z
2021-11-02T16:43:25.000Z
"""REST API implementation.""" import json import logging import os import pathlib from datetime import datetime from aiohttp import web from core.addons.api.dto.details import Details from core.addons.api.dto.location import Location from core.addons.api.dto.photo import PhotoDetailsResponse, PhotoEncoder, PhotoResponse from core.addons.api.dto.photo_response import PhotosResponse from core.base import Session from core.core import ApplicationCore from core.persistency.dto.photo import Photo from core.webserver.request import KEY_USER_ID, RequestView from core.webserver.status import HTTP_CREATED, HTTP_OK _LOGGER = logging.getLogger(__name__) logging.basicConfig(level=logging.DEBUG) async def async_setup(core: ApplicationCore, config: dict) -> bool: """Set up addon to core application.""" if config is not None and "cors" in config: is_cors_enabled = config["cors"] else: is_cors_enabled = False _LOGGER.debug(f"enable cors: {is_cors_enabled}") core.http.register_request(APIStatusView()) core.http.register_request(PhotosView()) core.http.register_request(PhotoDetailsView()) core.http.register_request(PhotoView()) core.http.register_request(AlbumView()) return True class APIStatusView(RequestView): """View to handle Status requests.""" requires_auth = False url = "/api" name = "api:status" async def get(self, core: ApplicationCore, request: web.Request): """Retrieve if API is running.""" return self.json_message("API running.") async def head(self, core: ApplicationCore, request: web.Request): """Retrieve if API is running.""" return self.json_message("API running.") class PhotosView(RequestView): """View to handle photos requests.""" url = "/api/photos" name = "api:photo" async def get(self, core: ApplicationCore, request: web.Request) -> web.Response: """Get a list of all photo resources.""" _LOGGER.debug("GET /api/photos") await core.authentication.check_permission(request, "library:read") user_id = await core.http.get_user_id(request) if user_id is None: raise web.HTTPForbidden() limit = 50 if "limit" in request.query: limit = int(request.query["limit"]) offset = 0 if "offset" in request.query: offset = int(request.query["offset"]) _LOGGER.debug( f"read {limit} photos for user_id {user_id} beginning with {offset}" ) user_photos = await core.storage.read_photos(user_id, offset, limit) results = [] _LOGGER.debug(f"found {len(user_photos)} photos") for photo in user_photos: results.append( PhotoResponse( id=photo.uuid, name=photo.filename, image_url=f"{core.config.external_url}:{core.config.port}/api/file/{photo.uuid}", date_added=photo.date_added, date_taken=photo.date_taken, ) ) response = PhotosResponse( offset=offset, limit=limit, size=len(results), results=results ) return web.Response( text=json.dumps(response, cls=PhotoEncoder), content_type="application/json" ) class PhotoDetailsView(RequestView): """View to handle single photo requests.""" url = "/api/photo/{entity_id}" name = "api:photo" async def get( self, core: ApplicationCore, request: web.Request, entity_id: str ) -> web.Response: """Return an entity.""" _LOGGER.debug(f"GET /api/photo/{entity_id}") # TODO: add user_id to check if user has access to image photo = await core.storage.read_photo(entity_id) if photo is None: raise web.HTTPNotFound # photo owner # TODO: get first-/lastname of owner # owner = await core.authentication _LOGGER.debug(f"photo {photo.uuid}") file = os.path.join(photo.directory, photo.filename) _LOGGER.debug(f"get additional data for {file} / {os.path.exists(file)}") # photo creation time fname = pathlib.Path(file) mtime = datetime.fromtimestamp(fname.stat().st_mtime) ctime = datetime.fromtimestamp(fname.stat().st_ctime) # photo location location = None latitude = await core.storage.read("latitude") longitude = await core.storage.read("longitude") if latitude is not None and longitude is not None: altitude = await core.storage.read("altitude") if altitude is not None: location = Location( latitude=latitude, longitude=longitude, altitude=altitude ) else: location = Location( latitude=latitude, longitude=longitude, altitude="0.0" ) # photo tags tags = await core.storage.read("tags") result = PhotoDetailsResponse( id=photo.uuid, name=photo.filename, owner=photo.owner, created_at=ctime.isoformat(), modified_at=mtime.isoformat(), details=Details( camera="Nikon Z7", lens="Nikkor 200mm F1.8", focal_length="200", iso="400", shutter_speed="1/2000", aperture="4.0", ), tags=tags, location=location, image_url=f"{core.config.external_url}/api/file/{entity_id}", ) return web.Response( text=json.dumps(result, cls=PhotoEncoder), content_type="application/json" ) class PhotoView(RequestView): """View to handle photo file requests.""" requires_auth = True url = "/api/file/{entity_id}" name = "api:file" async def get( self, core: ApplicationCore, request: web.Request, entity_id: str ) -> web.Response: """Return an entity.""" _LOGGER.debug(f"GET /api/file/{entity_id}") # TODO: parse params max-with / max-height =wmax-width-hmax-height (=w2048-h1024) # -wmax-width (preserving the aspect ratio) # -hmax-height (preserving the aspect ratio) # -c crop images to max-width / max-height # -d remove exif data result = Session.query(Photo).filter(Photo.uuid == entity_id).first() if result: file = os.path.join(result.directory, result.filename) if os.path.exists(os.path.join(file)): return web.FileResponse(path=file, status=200) else: raise web.HTTPNotFound() else: raise web.HTTPNotFound() async def post(self, core: ApplicationCore, request: web.Request) -> web.Response: """Upload new photo resource.""" user = request[KEY_USER_ID] reader = await request.multipart() field = await reader.next() assert field.name == "data" original_filename = field.filename _LOGGER.warning(f"request: {original_filename}") # TODO: get storage directory for user path = os.path.join(f"./data/users/{user}/", original_filename) if os.path.exists(path): # TODO: handle filename already exists _LOGGER.warning(f"file already exists! {path}") filename = original_filename size = 0 with open(os.path.join(f"./data/users/{user}/", filename), "wb") as f: while True: chunk = await field.read_chunk() # 8192 bytes by default. if not chunk: break size += len(chunk) f.write(chunk) _LOGGER.error(f"added {filename} to data directory of {user}.") # TODO: add new filepath to database # TODO: return unique_id from database new_entity_id = 123456 new_entity_created = True status_code = HTTP_CREATED if new_entity_created else HTTP_OK resp = self.json_message( f"File successfully added with ID: {new_entity_id}", status_code ) resp.headers.add("Location", f"/api/photo/{new_entity_id}") return resp async def delete(self, core: ApplicationCore, request: web.Request, entity_id: str): """Delete an entity.""" _LOGGER.debug(f"DELETE /api/file/{entity_id}") # TODO: delete entity return self.json_message(f"return DELETE {entity_id}") class AlbumsView(RequestView): """View to handle albums requests.""" requires_auth = False url = "/api/album/" name = "api:albums" async def get(self, request: web.Request) -> web.Response: """Retrieve if API is running.""" return self.json_message("return Albums") class AlbumView(RequestView): """View to handle single album requests.""" requires_auth = False url = "/api/album/{entity_id}" name = "api:album" async def get(self, request: web.Request, entity_id) -> web.Response: """Retrieve if API is running.""" return self.json_message(f"return Album {entity_id}") async def post(self, request: web.Request) -> web.Response: """Create a new album.""" return self.json_message("create a new Album")
32.543253
101
0.612547
import json import logging import os import pathlib from datetime import datetime from aiohttp import web from core.addons.api.dto.details import Details from core.addons.api.dto.location import Location from core.addons.api.dto.photo import PhotoDetailsResponse, PhotoEncoder, PhotoResponse from core.addons.api.dto.photo_response import PhotosResponse from core.base import Session from core.core import ApplicationCore from core.persistency.dto.photo import Photo from core.webserver.request import KEY_USER_ID, RequestView from core.webserver.status import HTTP_CREATED, HTTP_OK _LOGGER = logging.getLogger(__name__) logging.basicConfig(level=logging.DEBUG) async def async_setup(core: ApplicationCore, config: dict) -> bool: if config is not None and "cors" in config: is_cors_enabled = config["cors"] else: is_cors_enabled = False _LOGGER.debug(f"enable cors: {is_cors_enabled}") core.http.register_request(APIStatusView()) core.http.register_request(PhotosView()) core.http.register_request(PhotoDetailsView()) core.http.register_request(PhotoView()) core.http.register_request(AlbumView()) return True class APIStatusView(RequestView): requires_auth = False url = "/api" name = "api:status" async def get(self, core: ApplicationCore, request: web.Request): return self.json_message("API running.") async def head(self, core: ApplicationCore, request: web.Request): return self.json_message("API running.") class PhotosView(RequestView): url = "/api/photos" name = "api:photo" async def get(self, core: ApplicationCore, request: web.Request) -> web.Response: _LOGGER.debug("GET /api/photos") await core.authentication.check_permission(request, "library:read") user_id = await core.http.get_user_id(request) if user_id is None: raise web.HTTPForbidden() limit = 50 if "limit" in request.query: limit = int(request.query["limit"]) offset = 0 if "offset" in request.query: offset = int(request.query["offset"]) _LOGGER.debug( f"read {limit} photos for user_id {user_id} beginning with {offset}" ) user_photos = await core.storage.read_photos(user_id, offset, limit) results = [] _LOGGER.debug(f"found {len(user_photos)} photos") for photo in user_photos: results.append( PhotoResponse( id=photo.uuid, name=photo.filename, image_url=f"{core.config.external_url}:{core.config.port}/api/file/{photo.uuid}", date_added=photo.date_added, date_taken=photo.date_taken, ) ) response = PhotosResponse( offset=offset, limit=limit, size=len(results), results=results ) return web.Response( text=json.dumps(response, cls=PhotoEncoder), content_type="application/json" ) class PhotoDetailsView(RequestView): url = "/api/photo/{entity_id}" name = "api:photo" async def get( self, core: ApplicationCore, request: web.Request, entity_id: str ) -> web.Response: _LOGGER.debug(f"GET /api/photo/{entity_id}") photo = await core.storage.read_photo(entity_id) if photo is None: raise web.HTTPNotFound _LOGGER.debug(f"photo {photo.uuid}") file = os.path.join(photo.directory, photo.filename) _LOGGER.debug(f"get additional data for {file} / {os.path.exists(file)}") fname = pathlib.Path(file) mtime = datetime.fromtimestamp(fname.stat().st_mtime) ctime = datetime.fromtimestamp(fname.stat().st_ctime) location = None latitude = await core.storage.read("latitude") longitude = await core.storage.read("longitude") if latitude is not None and longitude is not None: altitude = await core.storage.read("altitude") if altitude is not None: location = Location( latitude=latitude, longitude=longitude, altitude=altitude ) else: location = Location( latitude=latitude, longitude=longitude, altitude="0.0" ) tags = await core.storage.read("tags") result = PhotoDetailsResponse( id=photo.uuid, name=photo.filename, owner=photo.owner, created_at=ctime.isoformat(), modified_at=mtime.isoformat(), details=Details( camera="Nikon Z7", lens="Nikkor 200mm F1.8", focal_length="200", iso="400", shutter_speed="1/2000", aperture="4.0", ), tags=tags, location=location, image_url=f"{core.config.external_url}/api/file/{entity_id}", ) return web.Response( text=json.dumps(result, cls=PhotoEncoder), content_type="application/json" ) class PhotoView(RequestView): requires_auth = True url = "/api/file/{entity_id}" name = "api:file" async def get( self, core: ApplicationCore, request: web.Request, entity_id: str ) -> web.Response: _LOGGER.debug(f"GET /api/file/{entity_id}") result = Session.query(Photo).filter(Photo.uuid == entity_id).first() if result: file = os.path.join(result.directory, result.filename) if os.path.exists(os.path.join(file)): return web.FileResponse(path=file, status=200) else: raise web.HTTPNotFound() else: raise web.HTTPNotFound() async def post(self, core: ApplicationCore, request: web.Request) -> web.Response: user = request[KEY_USER_ID] reader = await request.multipart() field = await reader.next() assert field.name == "data" original_filename = field.filename _LOGGER.warning(f"request: {original_filename}") path = os.path.join(f"./data/users/{user}/", original_filename) if os.path.exists(path): _LOGGER.warning(f"file already exists! {path}") filename = original_filename size = 0 with open(os.path.join(f"./data/users/{user}/", filename), "wb") as f: while True: chunk = await field.read_chunk() if not chunk: break size += len(chunk) f.write(chunk) _LOGGER.error(f"added {filename} to data directory of {user}.") new_entity_id = 123456 new_entity_created = True status_code = HTTP_CREATED if new_entity_created else HTTP_OK resp = self.json_message( f"File successfully added with ID: {new_entity_id}", status_code ) resp.headers.add("Location", f"/api/photo/{new_entity_id}") return resp async def delete(self, core: ApplicationCore, request: web.Request, entity_id: str): _LOGGER.debug(f"DELETE /api/file/{entity_id}") return self.json_message(f"return DELETE {entity_id}") class AlbumsView(RequestView): requires_auth = False url = "/api/album/" name = "api:albums" async def get(self, request: web.Request) -> web.Response: return self.json_message("return Albums") class AlbumView(RequestView): requires_auth = False url = "/api/album/{entity_id}" name = "api:album" async def get(self, request: web.Request, entity_id) -> web.Response: return self.json_message(f"return Album {entity_id}") async def post(self, request: web.Request) -> web.Response: return self.json_message("create a new Album")
true
true
f725a39885307cc168891a50213872ddbdd21689
1,475
py
Python
_unittests/ut_module/test_code_style.py
sdpython/papierstat
f69de884c59ada30b58224dca39f2a44d92122c1
[ "MIT" ]
7
2019-03-21T09:52:31.000Z
2021-01-17T16:56:27.000Z
_unittests/ut_module/test_code_style.py
sdpython/papierstat
f69de884c59ada30b58224dca39f2a44d92122c1
[ "MIT" ]
33
2018-02-08T23:56:57.000Z
2021-02-10T23:55:43.000Z
_unittests/ut_module/test_code_style.py
sdpython/papierstat
f69de884c59ada30b58224dca39f2a44d92122c1
[ "MIT" ]
1
2021-02-11T09:16:33.000Z
2021-02-11T09:16:33.000Z
""" @brief test log(time=150s) """ import os import unittest from pyquickhelper.loghelper import fLOG from pyquickhelper.pycode import check_pep8, ExtTestCase class TestCodeStyle(ExtTestCase): """Test style.""" def test_style_src(self): thi = os.path.abspath(os.path.dirname(__file__)) src_ = os.path.normpath(os.path.join(thi, "..", "..", "src")) check_pep8(src_, fLOG=fLOG, pylint_ignore=('C0103', 'C1801', 'R0201', 'R1705', 'W0108', 'W0613', 'C0111', 'W0223', 'W0201', 'W0212', 'C0415', 'C0209'), skip=["Parameters differ from overridden 'fit' method", "Module 'numpy.random' has no 'RandomState' member", "Instance of 'SkLearnParameters' has no '", " in module 'sklearn.cluster._k_means'", "Instance of 'Struct' has no '", ]) def test_style_test(self): thi = os.path.abspath(os.path.dirname(__file__)) test = os.path.normpath(os.path.join(thi, "..", )) check_pep8(test, fLOG=fLOG, neg_pattern="temp_.*", pylint_ignore=('C0103', 'C1801', 'R0201', 'R1705', 'W0108', 'W0613', 'C0111', 'W0612', 'E0632', 'C0415', 'C0209'), skip=["Instance of 'tuple' has no ", ]) if __name__ == "__main__": unittest.main()
38.815789
88
0.520678
import os import unittest from pyquickhelper.loghelper import fLOG from pyquickhelper.pycode import check_pep8, ExtTestCase class TestCodeStyle(ExtTestCase): def test_style_src(self): thi = os.path.abspath(os.path.dirname(__file__)) src_ = os.path.normpath(os.path.join(thi, "..", "..", "src")) check_pep8(src_, fLOG=fLOG, pylint_ignore=('C0103', 'C1801', 'R0201', 'R1705', 'W0108', 'W0613', 'C0111', 'W0223', 'W0201', 'W0212', 'C0415', 'C0209'), skip=["Parameters differ from overridden 'fit' method", "Module 'numpy.random' has no 'RandomState' member", "Instance of 'SkLearnParameters' has no '", " in module 'sklearn.cluster._k_means'", "Instance of 'Struct' has no '", ]) def test_style_test(self): thi = os.path.abspath(os.path.dirname(__file__)) test = os.path.normpath(os.path.join(thi, "..", )) check_pep8(test, fLOG=fLOG, neg_pattern="temp_.*", pylint_ignore=('C0103', 'C1801', 'R0201', 'R1705', 'W0108', 'W0613', 'C0111', 'W0612', 'E0632', 'C0415', 'C0209'), skip=["Instance of 'tuple' has no ", ]) if __name__ == "__main__": unittest.main()
true
true
f725a3fd1b003a319b8f8190e60431bedbbcf49d
1,698
py
Python
src/LossFunctions/ActionCrossEntropy.py
Marcel-Rodekamp/MLP
349ac8e10679e2ec53980908c580902996a493e7
[ "MIT" ]
1
2021-06-15T09:01:09.000Z
2021-06-15T09:01:09.000Z
src/LossFunctions/ActionCrossEntropy.py
Marcel-Rodekamp/MLP
349ac8e10679e2ec53980908c580902996a493e7
[ "MIT" ]
null
null
null
src/LossFunctions/ActionCrossEntropy.py
Marcel-Rodekamp/MLP
349ac8e10679e2ec53980908c580902996a493e7
[ "MIT" ]
null
null
null
import torch class ActionCrossEntropyFunction(torch.autograd.Function): @staticmethod def forward(self,input,target,action,force = None): self.mb_size,self.dim = input.size() # save the force for backward self.force = force # get action difference action_input = torch.tensor( [action(input[i_mb,:].numpy()) for i_mb in range(self.mb_size)], dtype = input.dtype ) action_target = torch.tensor( [action(target[i_mb,:].numpy()) for i_mb in range(self.mb_size)], dtype = input.dtype ) output = action_target * action_input.log() + (1-action_target) * (1-action_input).log() self.save_for_backward(input,action_input,action_target,output) output = torch.sqrt(output.real**2+output.imag**2) # average over batch and return output = torch.mean(output) return output @staticmethod def backward(self,grad_output): input,action_input,action_target,cross_entropy = self.saved_tensors action_grad_input = -torch.tensor( [self.force(input[i_mb,:].numpy()) for i_mb in range(self.mb_size)], dtype = input.dtype ) grad = torch.unsqueeze( cross_entropy.conj()*((action_target)/(action_input) + (1-action_target)/(1-action_input)), -1 ) * action_grad_input return grad.conj(),None,None,None ActionCrossEntropyFunc = ActionCrossEntropyFunction.apply class ActionCrossEntropy(torch.nn.Module): def __init__(self,action): super(ActionCrossEntropy, self).__init__() self.action = action.eval self.force = action.force def forward(self, input, target): return ActionCrossEntropyFunc(input,target,self.action,self.force)
36.913043
148
0.689046
import torch class ActionCrossEntropyFunction(torch.autograd.Function): @staticmethod def forward(self,input,target,action,force = None): self.mb_size,self.dim = input.size() self.force = force action_input = torch.tensor( [action(input[i_mb,:].numpy()) for i_mb in range(self.mb_size)], dtype = input.dtype ) action_target = torch.tensor( [action(target[i_mb,:].numpy()) for i_mb in range(self.mb_size)], dtype = input.dtype ) output = action_target * action_input.log() + (1-action_target) * (1-action_input).log() self.save_for_backward(input,action_input,action_target,output) output = torch.sqrt(output.real**2+output.imag**2) output = torch.mean(output) return output @staticmethod def backward(self,grad_output): input,action_input,action_target,cross_entropy = self.saved_tensors action_grad_input = -torch.tensor( [self.force(input[i_mb,:].numpy()) for i_mb in range(self.mb_size)], dtype = input.dtype ) grad = torch.unsqueeze( cross_entropy.conj()*((action_target)/(action_input) + (1-action_target)/(1-action_input)), -1 ) * action_grad_input return grad.conj(),None,None,None ActionCrossEntropyFunc = ActionCrossEntropyFunction.apply class ActionCrossEntropy(torch.nn.Module): def __init__(self,action): super(ActionCrossEntropy, self).__init__() self.action = action.eval self.force = action.force def forward(self, input, target): return ActionCrossEntropyFunc(input,target,self.action,self.force)
true
true
f725a5330ea476bf3d80b1dcb996e9b5875e2f37
918
py
Python
setup.py
NgHoangDat/lescode
f19d8f2ca47aee947d2b2d88e5008ce4a58faeb6
[ "MIT" ]
1
2020-06-17T03:33:58.000Z
2020-06-17T03:33:58.000Z
setup.py
NgHoangDat/lescode
f19d8f2ca47aee947d2b2d88e5008ce4a58faeb6
[ "MIT" ]
null
null
null
setup.py
NgHoangDat/lescode
f19d8f2ca47aee947d2b2d88e5008ce4a58faeb6
[ "MIT" ]
null
null
null
import setuptools with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() __VERSION__ = "0.2.10" setuptools.setup( name="lescode", packages=setuptools.find_packages(), version=__VERSION__, author="nghoangdat", author_email="18.hoang.dat.12@gmail.com", description="quiver", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/NgHoangDat/lescode.git", download_url=f"https://github.com/NgHoangDat/lescode/archive/v{__VERSION__}.tar.gz", classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], python_requires='>=3.6', install_requires=[ 'dataclasses; python_version=="3.6"', 'msgpack', 'python-dateutil', 'pyyaml', 'toolz' ] )
27
88
0.641612
import setuptools with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() __VERSION__ = "0.2.10" setuptools.setup( name="lescode", packages=setuptools.find_packages(), version=__VERSION__, author="nghoangdat", author_email="18.hoang.dat.12@gmail.com", description="quiver", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/NgHoangDat/lescode.git", download_url=f"https://github.com/NgHoangDat/lescode/archive/v{__VERSION__}.tar.gz", classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], python_requires='>=3.6', install_requires=[ 'dataclasses; python_version=="3.6"', 'msgpack', 'python-dateutil', 'pyyaml', 'toolz' ] )
true
true
f725a7c0a43b428ee68f9ed16d64cc59f6ac188b
11,328
py
Python
haystack/utils/squad_data.py
ArzelaAscoIi/haystack
be8f50c9e3de4e264b3f345f5f4b9c9ec518ed08
[ "Apache-2.0" ]
1
2022-02-15T04:32:41.000Z
2022-02-15T04:32:41.000Z
haystack/utils/squad_data.py
ArzelaAscoIi/haystack
be8f50c9e3de4e264b3f345f5f4b9c9ec518ed08
[ "Apache-2.0" ]
null
null
null
haystack/utils/squad_data.py
ArzelaAscoIi/haystack
be8f50c9e3de4e264b3f345f5f4b9c9ec518ed08
[ "Apache-2.0" ]
null
null
null
from typing import List import logging import json import random import pandas as pd from tqdm import tqdm from haystack.schema import Document, Label from haystack.modeling.data_handler.processor import _read_squad_file logging.basicConfig() logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) tqdm.pandas() COLUMN_NAMES = ["title", "context", "question", "id", "answer_text", "answer_start", "is_impossible"] class SquadData: """ This class is designed to manipulate data that is in SQuAD format """ def __init__(self, squad_data): """ :param squad_data: SQuAD format data, either as a dict with a `data` key, or just a list of SQuAD documents """ if type(squad_data) == dict: self.version = squad_data.get("version") self.data = squad_data["data"] elif type(squad_data) == list: self.version = None self.data = squad_data self.df = self.to_df(self.data) def merge_from_file(self, filename: str): """Merge the contents of a SQuAD format json file with the data stored in this object""" new_data = json.load(open(filename))["data"] self.merge(new_data) def merge(self, new_data: List): """ Merge data in SQuAD format with the data stored in this object :param new_data: A list of SQuAD document data """ df_new = self.to_df(new_data) self.df = pd.concat([df_new, self.df]) self.data = self.df_to_data(self.df) @classmethod def from_file(cls, filename: str): """ Create a SquadData object by providing the name of a SQuAD format json file """ data = json.load(open(filename)) return cls(data) def save(self, filename: str): """ Write the data stored in this object to a json file. """ with open(filename, "w") as f: squad_data = {"version": self.version, "data": self.data} json.dump(squad_data, f, indent=2) def to_dpr_dataset(self): raise NotImplementedError( "SquadData.to_dpr_dataset() not yet implemented. " "For now, have a look at the script at haystack/retriever/squad_to_dpr.py" ) def to_document_objs(self): """ Export all paragraphs stored in this object to haystack.Document objects. """ df_docs = self.df[["title", "context"]] df_docs = df_docs.drop_duplicates() record_dicts = df_docs.to_dict("records") documents = [Document(content=rd["context"], id=rd["title"]) for rd in record_dicts] return documents # TODO refactor to new Label objects def to_label_objs(self): """ Export all labels stored in this object to haystack.Label objects. """ df_labels = self.df[["id", "question", "answer_text", "answer_start"]] record_dicts = df_labels.to_dict("records") labels = [ Label( query=rd["question"], answer=rd["answer_text"], is_correct_answer=True, is_correct_document=True, id=rd["id"], origin=rd.get("origin", "SquadData tool"), document_id=rd.get("document_id", None), ) for rd in record_dicts ] return labels @staticmethod def to_df(data): """Convert a list of SQuAD document dictionaries into a pandas dataframe (each row is one annotation)""" flat = [] for document in data: title = document["title"] for paragraph in document["paragraphs"]: context = paragraph["context"] for question in paragraph["qas"]: q = question["question"] id = question["id"] is_impossible = question["is_impossible"] # For no_answer samples if len(question["answers"]) == 0: flat.append( { "title": title, "context": context, "question": q, "id": id, "answer_text": "", "answer_start": None, "is_impossible": is_impossible, } ) # For span answer samples else: for answer in question["answers"]: answer_text = answer["text"] answer_start = answer["answer_start"] flat.append( { "title": title, "context": context, "question": q, "id": id, "answer_text": answer_text, "answer_start": answer_start, "is_impossible": is_impossible, } ) df = pd.DataFrame.from_records(flat) return df def count(self, unit="questions"): """ Count the samples in the data. Choose from unit = "paragraphs", "questions", "answers", "no_answers", "span_answers" """ c = 0 for document in self.data: for paragraph in document["paragraphs"]: if unit == "paragraphs": c += 1 for question in paragraph["qas"]: if unit == "questions": c += 1 # Count no_answers if len(question["answers"]) == 0: if unit in ["answers", "no_answers"]: c += 1 # Count span answers else: for answer in question["answers"]: if unit in ["answers", "span_answers"]: c += 1 return c @classmethod def df_to_data(cls, df): """ Convert a dataframe into SQuAD format data (list of SQuAD document dictionaries). """ logger.info("Converting data frame to squad format data") # Aggregate the answers of each question logger.info("Aggregating the answers of each question") df_grouped_answers = df.groupby(["title", "context", "question", "id", "is_impossible"]) df_aggregated_answers = ( df[["title", "context", "question", "id", "is_impossible"]].drop_duplicates().reset_index() ) answers = df_grouped_answers.progress_apply(cls._aggregate_answers).rename("answers") answers = pd.DataFrame(answers).reset_index() df_aggregated_answers = pd.merge(df_aggregated_answers, answers) # Aggregate the questions of each passage logger.info("Aggregating the questions of each paragraphs of each document") df_grouped_questions = df_aggregated_answers.groupby(["title", "context"]) df_aggregated_questions = df[["title", "context"]].drop_duplicates().reset_index() questions = df_grouped_questions.progress_apply(cls._aggregate_questions).rename("qas") questions = pd.DataFrame(questions).reset_index() df_aggregated_questions = pd.merge(df_aggregated_questions, questions) logger.info("Aggregating the paragraphs of each document") df_grouped_paragraphs = df_aggregated_questions.groupby(["title"]) df_aggregated_paragraphs = df[["title"]].drop_duplicates().reset_index() paragraphs = df_grouped_paragraphs.progress_apply(cls._aggregate_passages).rename("paragraphs") paragraphs = pd.DataFrame(paragraphs).reset_index() df_aggregated_paragraphs = pd.merge(df_aggregated_paragraphs, paragraphs) df_aggregated_paragraphs = df_aggregated_paragraphs[["title", "paragraphs"]] ret = df_aggregated_paragraphs.to_dict("records") return ret @staticmethod def _aggregate_passages(x): x = x[["context", "qas"]] ret = x.to_dict("records") return ret @staticmethod def _aggregate_questions(x): x = x[["question", "id", "answers", "is_impossible"]] ret = x.to_dict("records") return ret @staticmethod def _aggregate_answers(x): x = x[["answer_text", "answer_start"]] x = x.rename(columns={"answer_text": "text"}) # Span anwser try: x["answer_start"] = x["answer_start"].astype(int) ret = x.to_dict("records") # No answer except ValueError: ret = [] return ret def set_data(self, data): self.data = data self.df = self.to_df(data) def sample_questions(self, n): """ Return a sample of n questions in SQuAD format (list of SQuAD document dictionaries) Note, that if the same question is asked on multiple different passages, this fn treats that as a single question """ all_questions = self.get_all_questions() sampled_questions = random.sample(all_questions, n) df_sampled = self.df[self.df["question"].isin(sampled_questions)] return self.df_to_data(df_sampled) def get_all_paragraphs(self): """ Return all paragraph strings. """ return self.df["context"].unique().tolist() def get_all_questions(self): """ Return all question strings. Note that if the same question appears for different paragraphs, it will be returned multiple times by this fn """ df_questions = self.df[["title", "context", "question"]] df_questions = df_questions.drop_duplicates() questions = df_questions["question"].tolist() return questions def get_all_document_titles(self): """Return all document title strings""" return self.df["title"].unique().tolist() if __name__ == "__main__": # Download the SQuAD dataset if it isn't at target directory _read_squad_file("../data/squad20/train-v2.0.json") filename1 = "../data/squad20/train-v2.0.json" filename2 = "../data/squad20/dev-v2.0.json" # Load file1 and take a sample of 10000 questions sd = SquadData.from_file(filename1) sample1 = sd.sample_questions(n=10000) # Set sd to now contain the sample of 10000 questions sd.set_data(sample1) # Merge sd with file2 and take a sample of 100 questions sd.merge_from_file(filename2) sample2 = sd.sample_questions(n=100) sd.set_data(sample2) # Save this sample of 100 sd.save("../data/squad20/sample.json") paragraphs = sd.get_all_paragraphs() questions = sd.get_all_questions() titles = sd.get_all_document_titles() documents = sd.to_document_objs() labels = sd.to_label_objs() n_qs = sd.count(unit="questions") n_as = sd.count(unit="no_answers") n_ps = sd.count(unit="paragraphs") print(n_qs) print(n_as) print(n_ps)
36.779221
124
0.566561
from typing import List import logging import json import random import pandas as pd from tqdm import tqdm from haystack.schema import Document, Label from haystack.modeling.data_handler.processor import _read_squad_file logging.basicConfig() logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) tqdm.pandas() COLUMN_NAMES = ["title", "context", "question", "id", "answer_text", "answer_start", "is_impossible"] class SquadData: def __init__(self, squad_data): if type(squad_data) == dict: self.version = squad_data.get("version") self.data = squad_data["data"] elif type(squad_data) == list: self.version = None self.data = squad_data self.df = self.to_df(self.data) def merge_from_file(self, filename: str): new_data = json.load(open(filename))["data"] self.merge(new_data) def merge(self, new_data: List): df_new = self.to_df(new_data) self.df = pd.concat([df_new, self.df]) self.data = self.df_to_data(self.df) @classmethod def from_file(cls, filename: str): data = json.load(open(filename)) return cls(data) def save(self, filename: str): with open(filename, "w") as f: squad_data = {"version": self.version, "data": self.data} json.dump(squad_data, f, indent=2) def to_dpr_dataset(self): raise NotImplementedError( "SquadData.to_dpr_dataset() not yet implemented. " "For now, have a look at the script at haystack/retriever/squad_to_dpr.py" ) def to_document_objs(self): df_docs = self.df[["title", "context"]] df_docs = df_docs.drop_duplicates() record_dicts = df_docs.to_dict("records") documents = [Document(content=rd["context"], id=rd["title"]) for rd in record_dicts] return documents def to_label_objs(self): df_labels = self.df[["id", "question", "answer_text", "answer_start"]] record_dicts = df_labels.to_dict("records") labels = [ Label( query=rd["question"], answer=rd["answer_text"], is_correct_answer=True, is_correct_document=True, id=rd["id"], origin=rd.get("origin", "SquadData tool"), document_id=rd.get("document_id", None), ) for rd in record_dicts ] return labels @staticmethod def to_df(data): flat = [] for document in data: title = document["title"] for paragraph in document["paragraphs"]: context = paragraph["context"] for question in paragraph["qas"]: q = question["question"] id = question["id"] is_impossible = question["is_impossible"] if len(question["answers"]) == 0: flat.append( { "title": title, "context": context, "question": q, "id": id, "answer_text": "", "answer_start": None, "is_impossible": is_impossible, } ) else: for answer in question["answers"]: answer_text = answer["text"] answer_start = answer["answer_start"] flat.append( { "title": title, "context": context, "question": q, "id": id, "answer_text": answer_text, "answer_start": answer_start, "is_impossible": is_impossible, } ) df = pd.DataFrame.from_records(flat) return df def count(self, unit="questions"): c = 0 for document in self.data: for paragraph in document["paragraphs"]: if unit == "paragraphs": c += 1 for question in paragraph["qas"]: if unit == "questions": c += 1 if len(question["answers"]) == 0: if unit in ["answers", "no_answers"]: c += 1 else: for answer in question["answers"]: if unit in ["answers", "span_answers"]: c += 1 return c @classmethod def df_to_data(cls, df): logger.info("Converting data frame to squad format data") logger.info("Aggregating the answers of each question") df_grouped_answers = df.groupby(["title", "context", "question", "id", "is_impossible"]) df_aggregated_answers = ( df[["title", "context", "question", "id", "is_impossible"]].drop_duplicates().reset_index() ) answers = df_grouped_answers.progress_apply(cls._aggregate_answers).rename("answers") answers = pd.DataFrame(answers).reset_index() df_aggregated_answers = pd.merge(df_aggregated_answers, answers) logger.info("Aggregating the questions of each paragraphs of each document") df_grouped_questions = df_aggregated_answers.groupby(["title", "context"]) df_aggregated_questions = df[["title", "context"]].drop_duplicates().reset_index() questions = df_grouped_questions.progress_apply(cls._aggregate_questions).rename("qas") questions = pd.DataFrame(questions).reset_index() df_aggregated_questions = pd.merge(df_aggregated_questions, questions) logger.info("Aggregating the paragraphs of each document") df_grouped_paragraphs = df_aggregated_questions.groupby(["title"]) df_aggregated_paragraphs = df[["title"]].drop_duplicates().reset_index() paragraphs = df_grouped_paragraphs.progress_apply(cls._aggregate_passages).rename("paragraphs") paragraphs = pd.DataFrame(paragraphs).reset_index() df_aggregated_paragraphs = pd.merge(df_aggregated_paragraphs, paragraphs) df_aggregated_paragraphs = df_aggregated_paragraphs[["title", "paragraphs"]] ret = df_aggregated_paragraphs.to_dict("records") return ret @staticmethod def _aggregate_passages(x): x = x[["context", "qas"]] ret = x.to_dict("records") return ret @staticmethod def _aggregate_questions(x): x = x[["question", "id", "answers", "is_impossible"]] ret = x.to_dict("records") return ret @staticmethod def _aggregate_answers(x): x = x[["answer_text", "answer_start"]] x = x.rename(columns={"answer_text": "text"}) try: x["answer_start"] = x["answer_start"].astype(int) ret = x.to_dict("records") except ValueError: ret = [] return ret def set_data(self, data): self.data = data self.df = self.to_df(data) def sample_questions(self, n): all_questions = self.get_all_questions() sampled_questions = random.sample(all_questions, n) df_sampled = self.df[self.df["question"].isin(sampled_questions)] return self.df_to_data(df_sampled) def get_all_paragraphs(self): return self.df["context"].unique().tolist() def get_all_questions(self): df_questions = self.df[["title", "context", "question"]] df_questions = df_questions.drop_duplicates() questions = df_questions["question"].tolist() return questions def get_all_document_titles(self): return self.df["title"].unique().tolist() if __name__ == "__main__": _read_squad_file("../data/squad20/train-v2.0.json") filename1 = "../data/squad20/train-v2.0.json" filename2 = "../data/squad20/dev-v2.0.json" # Load file1 and take a sample of 10000 questions sd = SquadData.from_file(filename1) sample1 = sd.sample_questions(n=10000) # Set sd to now contain the sample of 10000 questions sd.set_data(sample1) # Merge sd with file2 and take a sample of 100 questions sd.merge_from_file(filename2) sample2 = sd.sample_questions(n=100) sd.set_data(sample2) # Save this sample of 100 sd.save("../data/squad20/sample.json") paragraphs = sd.get_all_paragraphs() questions = sd.get_all_questions() titles = sd.get_all_document_titles() documents = sd.to_document_objs() labels = sd.to_label_objs() n_qs = sd.count(unit="questions") n_as = sd.count(unit="no_answers") n_ps = sd.count(unit="paragraphs") print(n_qs) print(n_as) print(n_ps)
true
true
f725a83f718d805f89f9a0c04adb8de750d17bf3
7,720
py
Python
tests/test_settings.py
zbyte64/django-dockit
8d00a46cb0b6237de622fcb6816067078106a0c4
[ "BSD-3-Clause" ]
5
2015-02-25T17:01:48.000Z
2021-06-03T07:46:47.000Z
tests/test_settings.py
zbyte64/django-dockit
8d00a46cb0b6237de622fcb6816067078106a0c4
[ "BSD-3-Clause" ]
1
2015-03-11T15:19:55.000Z
2015-04-13T04:14:24.000Z
tests/test_settings.py
zbyte64/django-dockit
8d00a46cb0b6237de622fcb6816067078106a0c4
[ "BSD-3-Clause" ]
null
null
null
# Django settings for {{ project_name }} project. import os PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': ':memory:', # Or path to database file if using sqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # On Unix systems, a value of None will cause Django to use the same # timezone as the operating system. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale USE_L10N = True # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media') # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = '/media/' # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = '' # URL prefix for static files. # Example: "http://media.lawrence.com/static/" STATIC_URL = '/static/' # URL prefix for admin static files -- CSS, JavaScript and images. # Make sure to use a trailing slash. # Examples: "http://foo.com/static/admin/", "/static/admin/". ADMIN_MEDIA_PREFIX = '/static/admin/' # Additional locations of static files STATICFILES_DIRS = ( # Put strings here, like "/home/html/static" or "C:/www/django/static". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # Make this unique, and don't share it with anybody. SECRET_KEY = 'NOTASECRET' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) ROOT_URLCONF = 'tests.urls' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'dockit', 'dockit.backends.djangodocument', # Uncomment the next line to enable the admin: 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', ] DOCKIT_BACKENDS = { 'default': { 'ENGINE': 'dockit.backends.djangodocument.backend.ModelDocumentStorage', }, 'djangodocument': { 'ENGINE': 'dockit.backends.djangodocument.backend.ModelDocumentStorage', }, } DOCKIT_INDEX_BACKENDS = { 'default': { 'ENGINE': 'dockit.backends.djangodocument.backend.ModelIndexStorage', }, 'djangodocument': { 'ENGINE': 'dockit.backends.djangodocument.backend.ModelIndexStorage', }, } try: import pymongo except ImportError: pass else: from pymongo.errors import ConnectionFailure try: pymongo.MongoClient('localhost', 27017) except ConnectionFailure: pass else: INSTALLED_APPS.append('dockit.backends.mongo') DOCKIT_BACKENDS['mongo'] = { 'ENGINE':'dockit.backends.mongo.backend.MongoDocumentStorage', 'HOST':'localhost', 'DB':'testdb', 'PORT': 27017, } DOCKIT_INDEX_BACKENDS['mongo'] = { 'ENGINE':'dockit.backends.mongo.backend.MongoIndexStorage', 'HOST':'localhost', 'DB':'testdb', 'PORT': 27017, } if 'TRAVIS' in os.environ: DOCKIT_BACKENDS['mongo'] = {'ENGINE':'dockit.backends.mongo.backend.MongoDocumentStorage', 'USER':'travis', 'PASSWORD':'test', 'DB':'mydb_test', 'HOST':'127.0.0.1', 'PORT':27017,} DOCKIT_INDEX_BACKENDS['mongo'] = {'ENGINE':'dockit.backends.mongo.backend.MongoIndexStorage', 'USER':'travis', 'PASSWORD':'test', 'DB':'mydb_test', 'HOST':'127.0.0.1', 'PORT':27017,} if 'dockit.backends.mongo' not in INSTALLED_APPS: INSTALLED_APPS.append('dockit.backends.mongo') if os.environ.get('TASK_BACKEND', None) == 'celery': DOCKIT_INDEX_BACKENDS['djangodocument']['INDEX_TASKS'] = 'dockit.backends.djangodocument.tasks.CeleryIndexTasks' INSTALLED_APPS += ["djcelery"] CELERY_ALWAYS_EAGER = True import djcelery djcelery.setup_loader() if os.environ.get('TASK_BACKEND', None) == 'ztask': DOCKIT_INDEX_BACKENDS['djangodocument']['INDEX_TASKS'] = 'dockit.backends.djangodocument.tasks.ZTaskIndexTasks' INSTALLED_APPS += ["django_ztask"] ZTASKD_ALWAYS_EAGER = True # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } }
34.618834
122
0.651684
import os PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } TIME_ZONE = 'America/Chicago' LANGUAGE_CODE = 'en-us' SITE_ID = 1 USE_I18N = True USE_L10N = True MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media') MEDIA_URL = '/media/' # in apps' "static/" subdirectories and in STATICFILES_DIRS. STATIC_ROOT = '' STATIC_URL = '/static/' ADMIN_MEDIA_PREFIX = '/static/admin/' STATICFILES_DIRS = ( ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # Make this unique, and don't share it with anybody. SECRET_KEY = 'NOTASECRET' TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) ROOT_URLCONF = 'tests.urls' TEMPLATE_DIRS = ( ) INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'dockit', 'dockit.backends.djangodocument', # Uncomment the next line to enable the admin: 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', ] DOCKIT_BACKENDS = { 'default': { 'ENGINE': 'dockit.backends.djangodocument.backend.ModelDocumentStorage', }, 'djangodocument': { 'ENGINE': 'dockit.backends.djangodocument.backend.ModelDocumentStorage', }, } DOCKIT_INDEX_BACKENDS = { 'default': { 'ENGINE': 'dockit.backends.djangodocument.backend.ModelIndexStorage', }, 'djangodocument': { 'ENGINE': 'dockit.backends.djangodocument.backend.ModelIndexStorage', }, } try: import pymongo except ImportError: pass else: from pymongo.errors import ConnectionFailure try: pymongo.MongoClient('localhost', 27017) except ConnectionFailure: pass else: INSTALLED_APPS.append('dockit.backends.mongo') DOCKIT_BACKENDS['mongo'] = { 'ENGINE':'dockit.backends.mongo.backend.MongoDocumentStorage', 'HOST':'localhost', 'DB':'testdb', 'PORT': 27017, } DOCKIT_INDEX_BACKENDS['mongo'] = { 'ENGINE':'dockit.backends.mongo.backend.MongoIndexStorage', 'HOST':'localhost', 'DB':'testdb', 'PORT': 27017, } if 'TRAVIS' in os.environ: DOCKIT_BACKENDS['mongo'] = {'ENGINE':'dockit.backends.mongo.backend.MongoDocumentStorage', 'USER':'travis', 'PASSWORD':'test', 'DB':'mydb_test', 'HOST':'127.0.0.1', 'PORT':27017,} DOCKIT_INDEX_BACKENDS['mongo'] = {'ENGINE':'dockit.backends.mongo.backend.MongoIndexStorage', 'USER':'travis', 'PASSWORD':'test', 'DB':'mydb_test', 'HOST':'127.0.0.1', 'PORT':27017,} if 'dockit.backends.mongo' not in INSTALLED_APPS: INSTALLED_APPS.append('dockit.backends.mongo') if os.environ.get('TASK_BACKEND', None) == 'celery': DOCKIT_INDEX_BACKENDS['djangodocument']['INDEX_TASKS'] = 'dockit.backends.djangodocument.tasks.CeleryIndexTasks' INSTALLED_APPS += ["djcelery"] CELERY_ALWAYS_EAGER = True import djcelery djcelery.setup_loader() if os.environ.get('TASK_BACKEND', None) == 'ztask': DOCKIT_INDEX_BACKENDS['djangodocument']['INDEX_TASKS'] = 'dockit.backends.djangodocument.tasks.ZTaskIndexTasks' INSTALLED_APPS += ["django_ztask"] ZTASKD_ALWAYS_EAGER = True # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } }
true
true
f725a8967049f2e2f616b7777ed95915bf059305
82
py
Python
src/yeelight_atmosphere/__init__.py
NikSavilov/yeelight-atmosphere
8860c2869380be50a6305b5b2aa77ed3636145d3
[ "MIT" ]
null
null
null
src/yeelight_atmosphere/__init__.py
NikSavilov/yeelight-atmosphere
8860c2869380be50a6305b5b2aa77ed3636145d3
[ "MIT" ]
7
2021-11-13T13:07:21.000Z
2021-11-19T16:30:37.000Z
src/yeelight_atmosphere/__init__.py
NikSavilov/yeelight-atmosphere
8860c2869380be50a6305b5b2aa77ed3636145d3
[ "MIT" ]
null
null
null
""" Package allows to interact with Yeelight bulbs. """ __author__ = "Savilov N."
16.4
47
0.707317
__author__ = "Savilov N."
true
true
f725a9201795c774934495e6a45ebb15b68ea359
5,930
py
Python
doc/conf.py
open-dynamic-robot-initiative/mw_dual_motor_torque_ctrl
765b2ac852952d0643caec652b2b92e9d7d18dd9
[ "BSD-3-Clause" ]
10
2020-07-06T01:06:58.000Z
2022-03-13T23:37:46.000Z
doc/conf.py
open-dynamic-robot-initiative/mw_dual_motor_torque_ctrl
765b2ac852952d0643caec652b2b92e9d7d18dd9
[ "BSD-3-Clause" ]
4
2019-08-30T06:37:14.000Z
2021-10-05T12:28:39.000Z
doc/conf.py
open-dynamic-robot-initiative/mw_dual_motor_torque_ctrl
765b2ac852952d0643caec652b2b92e9d7d18dd9
[ "BSD-3-Clause" ]
5
2021-01-01T16:03:55.000Z
2022-02-17T22:02:35.000Z
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # ODRI Motor Board Firmware for CAN Communication documentation build # configuration file, created by sphinx-quickstart on Thu Aug 12 17:06:32 2021. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # # import os # import sys # sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ "sphinx.ext.intersphinx", "sphinx.ext.todo", "sphinx.ext.mathjax", "sphinx.ext.githubpages", ] # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = ".rst" # The master toctree document. master_doc = "index" # General information about the project. # project = "ODRI Motor Board Firmware for CAN Communication" project = "ODRI Firmware for CAN" copyright = "2021, Max Planck Gesellschaft" author = "Felix Widmaier" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = "1.0.0" # The full version, including alpha/beta/rc tags. release = "1.0.0" # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] # The name of the Pygments (syntax highlighting) style to use. pygments_style = "sphinx" # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = True # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = "alabaster" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ["_static"] # Custom sidebar templates, must be a dictionary that maps document names # to template names. # # This is required for the alabaster theme # refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars html_sidebars = { "**": [ "about.html", "navigation.html", "relations.html", # needs 'show_related': True theme option to display "searchbox.html", ] } # -- Options for HTMLHelp output ------------------------------------------ # Output file base name for HTML help builder. htmlhelp_basename = "ODRIMotorBoardFirmwareforCANCommunicationdoc" # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ( master_doc, "ODRIMotorBoardFirmwareforCANCommunication.tex", "ODRI Motor Board Firmware for CAN Communication Documentation", "Felix Widmaier", "manual", ), ] # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ( master_doc, "odrimotorboardfirmwareforcancommunication", "ODRI Motor Board Firmware for CAN Communication Documentation", [author], 1, ) ] # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ( master_doc, "ODRIMotorBoardFirmwareforCANCommunication", "ODRI Motor Board Firmware for CAN Communication Documentation", author, "ODRIMotorBoardFirmwareforCANCommunication", "One line description of project.", "Miscellaneous", ), ] # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {"https://docs.python.org/": None}
30.885417
79
0.679764
extensions = [ "sphinx.ext.intersphinx", "sphinx.ext.todo", "sphinx.ext.mathjax", "sphinx.ext.githubpages", ] templates_path = ["_templates"] source_suffix = ".rst" master_doc = "index" project = "ODRI Firmware for CAN" copyright = "2021, Max Planck Gesellschaft" author = "Felix Widmaier" # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = "1.0.0" # The full version, including alpha/beta/rc tags. release = "1.0.0" # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] # The name of the Pygments (syntax highlighting) style to use. pygments_style = "sphinx" # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = True # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = "alabaster" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ["_static"] # Custom sidebar templates, must be a dictionary that maps document names # to template names. # # This is required for the alabaster theme # refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars html_sidebars = { "**": [ "about.html", "navigation.html", "relations.html", # needs 'show_related': True theme option to display "searchbox.html", ] } # -- Options for HTMLHelp output ------------------------------------------ # Output file base name for HTML help builder. htmlhelp_basename = "ODRIMotorBoardFirmwareforCANCommunicationdoc" # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ( master_doc, "ODRIMotorBoardFirmwareforCANCommunication.tex", "ODRI Motor Board Firmware for CAN Communication Documentation", "Felix Widmaier", "manual", ), ] # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ( master_doc, "odrimotorboardfirmwareforcancommunication", "ODRI Motor Board Firmware for CAN Communication Documentation", [author], 1, ) ] # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ( master_doc, "ODRIMotorBoardFirmwareforCANCommunication", "ODRI Motor Board Firmware for CAN Communication Documentation", author, "ODRIMotorBoardFirmwareforCANCommunication", "One line description of project.", "Miscellaneous", ), ] # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {"https://docs.python.org/": None}
true
true
f725a9a56796d9cae327f43226b54d5c38fbe39b
312
py
Python
language_bar/language_bar.py
lxgreen/wm
ae38e9ab280147f568e1dcbc54bdda908ab9f97c
[ "MIT" ]
null
null
null
language_bar/language_bar.py
lxgreen/wm
ae38e9ab280147f568e1dcbc54bdda908ab9f97c
[ "MIT" ]
null
null
null
language_bar/language_bar.py
lxgreen/wm
ae38e9ab280147f568e1dcbc54bdda908ab9f97c
[ "MIT" ]
null
null
null
#!/usr/bin/python import subprocess def main(): layout_map = {"us":"EN", "il":"HE", "ru":"RU"} layout = subprocess.Popen("/home/lxgreen/scripts/wm" "/language_bar/xkb-switch", stdout=subprocess.PIPE).stdout.read() print layout_map[layout[:2]] if __name__ == '__main__': main()
22.285714
56
0.61859
import subprocess def main(): layout_map = {"us":"EN", "il":"HE", "ru":"RU"} layout = subprocess.Popen("/home/lxgreen/scripts/wm" "/language_bar/xkb-switch", stdout=subprocess.PIPE).stdout.read() print layout_map[layout[:2]] if __name__ == '__main__': main()
false
true
f725a9c6f543a4459d5a893dca60433b20e32993
4,539
py
Python
sort.py
sagittarian/personal-sort
c7875141b4e15173e4a4a2267a23ff8236e6d729
[ "MIT" ]
null
null
null
sort.py
sagittarian/personal-sort
c7875141b4e15173e4a4a2267a23ff8236e6d729
[ "MIT" ]
null
null
null
sort.py
sagittarian/personal-sort
c7875141b4e15173e4a4a2267a23ff8236e6d729
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 '''A simple implementation of a sorting algorithm, meant to allow people to manually rank a list of items using whatever subjective or objective criteria they want. This program can be called as a script and used interactively. You can provide the list of things to sort as command line arguments, or if there are no arguments provided, you can provide the list in stdin, one item per line. Example run: $ ./sort.py 'ice cream' falafel hamburgers pizza Which is greater, falafel or ice cream (<, =, or >)? < Which is greater, hamburgers or ice cream (<, =, or >)? < Which is greater, hamburgers or falafel (<, =, or >)? > Which is greater, pizza or hamburgers (<, =, or >)? > Which is greater, pizza or ice cream (<, =, or >)? < * ice cream * pizza * hamburgers * falafel Author: Adam Mesha <adam@mesha.org> License: MIT ''' from functools import cmp_to_key class memoize: '''We really want to be sure that we don't ask people to compare the same two items twice, so we cache the result. ''' def __init__(self, func): self.func = func self.cache = {} def __call__(self, *args): key = tuple(args) if key not in self.cache: self.cache[key] = self.func(*args) return self.cache[key] @memoize def cmpfunc(a, b): result = None s = 'Which is greater, {a} or {b} (<, =, or >)? '.format(a=a, b=b) while result is None or result not in '<=>': result = input(s).strip() return '<=>'.index(result) - 1 keyfunc = cmp_to_key(cmpfunc) def binary_insertion_sort(seq, keyfunc): '''Insertion sort, using binary search to insert each element. Runs in O(n**2) time, but the use case is when a human is manually deciding on the ordering, so the most important thing is to reduce the number of comparisons. ''' def mv(srcidx, dstidx): while srcidx > dstidx: seq[srcidx], seq[srcidx - 1] = seq[srcidx - 1], seq[srcidx] srcidx -= 1 i = 1 while i < len(seq): lower = 0; upper = i while lower < upper: j = (upper + lower) // 2 key1, key2 = keyfunc(seq[i]), keyfunc(seq[j]) if key1 == key2: mv(i, j+1) # XXX this is not stable i += 1 break if key1 < key2: upper = j else: # > lower = j + 1 else: mv(i, upper) i += 1 class SortableWithHeuristic: def __init__(self, val, heur): self.val = val self.heur = heur def __str__(self): return '{val}: {heur}'.format(val=self.val, heur=self.heur) def __repr__(self): return '{}(val={}, heur={})'.format(self.__class__.__name__, repr(self.val), repr(self.heur)) def get_heuristic_func(val): result = None s = 'Give an approximate numeric score to item {}: '.format(val) while result is None: try: result = float(input(s).strip()) except ValueError: pass return result def heuristic_sort(seq, get_heuristic_func, cmpfunc): def swap(a, b): seq[a], seq[b] = seq[b], seq[a] idx = 0 while idx < len(seq): val = seq[idx] heur = get_heuristic_func(val) seq[idx] = SortableWithHeuristic(val, heur) # find the current location j = idx while j > 0 and seq[j].heur < seq[j-1].heur: swap(j, j-1) j -= 1 moved = False while j < idx and cmpfunc(seq[j].val, seq[j+1].val) == 1: swap(j, j+1) j += 1 moved = True if not moved: while j > 0 and cmpfunc(seq[j].val, seq[j-1].val) == -1: swap(j, j-1) j -= 1 if 0 < j < idx: seq[j].heur = (seq[j-1].heur + seq[j+1].heur) / 2 elif idx > 0: if j == 0 and seq[j].heur > seq[j+1].heur: seq[j].heur = seq[j+1].heur - 1 elif j == idx and seq[j].heur < seq[j-1].heur: seq[j].heur = seq[j-1].heur + 1 idx += 1 def main(): import sys seq = [] if len(sys.argv) > 1: seq.extend(sys.argv[1:]) if not seq: seq.extend(x.strip() for x in sys.stdin.readlines()) heuristic_sort(seq, get_heuristic_func, cmpfunc) print('\n'.join('* {}'.format(item) for item in reversed(seq))) if __name__ == '__main__': main()
28.192547
72
0.548579
from functools import cmp_to_key class memoize: def __init__(self, func): self.func = func self.cache = {} def __call__(self, *args): key = tuple(args) if key not in self.cache: self.cache[key] = self.func(*args) return self.cache[key] @memoize def cmpfunc(a, b): result = None s = 'Which is greater, {a} or {b} (<, =, or >)? '.format(a=a, b=b) while result is None or result not in '<=>': result = input(s).strip() return '<=>'.index(result) - 1 keyfunc = cmp_to_key(cmpfunc) def binary_insertion_sort(seq, keyfunc): def mv(srcidx, dstidx): while srcidx > dstidx: seq[srcidx], seq[srcidx - 1] = seq[srcidx - 1], seq[srcidx] srcidx -= 1 i = 1 while i < len(seq): lower = 0; upper = i while lower < upper: j = (upper + lower) // 2 key1, key2 = keyfunc(seq[i]), keyfunc(seq[j]) if key1 == key2: mv(i, j+1) i += 1 break if key1 < key2: upper = j else: lower = j + 1 else: mv(i, upper) i += 1 class SortableWithHeuristic: def __init__(self, val, heur): self.val = val self.heur = heur def __str__(self): return '{val}: {heur}'.format(val=self.val, heur=self.heur) def __repr__(self): return '{}(val={}, heur={})'.format(self.__class__.__name__, repr(self.val), repr(self.heur)) def get_heuristic_func(val): result = None s = 'Give an approximate numeric score to item {}: '.format(val) while result is None: try: result = float(input(s).strip()) except ValueError: pass return result def heuristic_sort(seq, get_heuristic_func, cmpfunc): def swap(a, b): seq[a], seq[b] = seq[b], seq[a] idx = 0 while idx < len(seq): val = seq[idx] heur = get_heuristic_func(val) seq[idx] = SortableWithHeuristic(val, heur) j = idx while j > 0 and seq[j].heur < seq[j-1].heur: swap(j, j-1) j -= 1 moved = False while j < idx and cmpfunc(seq[j].val, seq[j+1].val) == 1: swap(j, j+1) j += 1 moved = True if not moved: while j > 0 and cmpfunc(seq[j].val, seq[j-1].val) == -1: swap(j, j-1) j -= 1 if 0 < j < idx: seq[j].heur = (seq[j-1].heur + seq[j+1].heur) / 2 elif idx > 0: if j == 0 and seq[j].heur > seq[j+1].heur: seq[j].heur = seq[j+1].heur - 1 elif j == idx and seq[j].heur < seq[j-1].heur: seq[j].heur = seq[j-1].heur + 1 idx += 1 def main(): import sys seq = [] if len(sys.argv) > 1: seq.extend(sys.argv[1:]) if not seq: seq.extend(x.strip() for x in sys.stdin.readlines()) heuristic_sort(seq, get_heuristic_func, cmpfunc) print('\n'.join('* {}'.format(item) for item in reversed(seq))) if __name__ == '__main__': main()
true
true
f725a9f9f6417c88c9e26be77336dc65fc531a7b
1,577
py
Python
preprocessing/homography_converter/uNetXST_homographies/2_F.py
LimJiaJing/Cam2BEV
8177e13f7a3662daee28cce62f35b85f500941c0
[ "MIT" ]
335
2020-05-11T07:24:01.000Z
2022-03-31T08:14:22.000Z
preprocessing/homography_converter/uNetXST_homographies/2_F.py
hoanganhpham1006/Cam2BEV
f788a9f58b464bc7b114e5a0dd1afcd6683f10e3
[ "MIT" ]
23
2020-07-12T23:42:31.000Z
2022-03-26T09:42:01.000Z
preprocessing/homography_converter/uNetXST_homographies/2_F.py
hoanganhpham1006/Cam2BEV
f788a9f58b464bc7b114e5a0dd1afcd6683f10e3
[ "MIT" ]
63
2020-05-11T16:27:56.000Z
2022-03-17T17:11:18.000Z
# ============================================================================== # MIT License # # Copyright 2020 Institute for Automotive Engineering of RWTH Aachen University. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # ============================================================================== import numpy as np # for dataset 2_F H = [ np.array([[0.03506686613905922, 27.971438297785962, -0.17694724954191404], [0.3821882391578238, 9.481642330993019e-17, 5.46222110929461], [25.000001047737943, 6.202207287472715e-15, 27.000001047737943]]) # front ]
50.870968
213
0.698795
import numpy as np H = [ np.array([[0.03506686613905922, 27.971438297785962, -0.17694724954191404], [0.3821882391578238, 9.481642330993019e-17, 5.46222110929461], [25.000001047737943, 6.202207287472715e-15, 27.000001047737943]]) ]
true
true
f725ab2fdd412236541d778007d38e8624e6c5f3
1,105
py
Python
gcloud/periodictask/apps.py
springborland/bk-sops
a9057672c10efb5f2414a805a30ead4092429c76
[ "Apache-2.0" ]
1
2021-05-19T04:31:34.000Z
2021-05-19T04:31:34.000Z
gcloud/periodictask/apps.py
sighttviewliu/bk-sops
6bf2f38bd93990f20f7c3a4decafc310e09e679c
[ "Apache-2.0" ]
null
null
null
gcloud/periodictask/apps.py
sighttviewliu/bk-sops
6bf2f38bd93990f20f7c3a4decafc310e09e679c
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2020 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://opensource.org/licenses/MIT Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from django.apps import AppConfig class PeriodicTaskConfig(AppConfig): name = "gcloud.periodictask" verbose_name = "GcloudPeriodicTask" def ready(self): from .signals.handlers import ( # noqa pre_periodic_task_start_handler, periodic_task_history_post_save_handler, periodic_task_start_failed_handler, )
40.925926
115
0.755656
from django.apps import AppConfig class PeriodicTaskConfig(AppConfig): name = "gcloud.periodictask" verbose_name = "GcloudPeriodicTask" def ready(self): from .signals.handlers import ( pre_periodic_task_start_handler, periodic_task_history_post_save_handler, periodic_task_start_failed_handler, )
true
true
f725abd59251190289dabcf79ac0661b33697890
1,839
py
Python
alembic/versions/4f53ec506661_add_study_template.py
jonathanzong/dmca
70157cff983310e5951024aa80e99e7a5404d758
[ "MIT" ]
2
2022-02-16T22:50:06.000Z
2022-02-21T19:38:02.000Z
alembic/versions/4f53ec506661_add_study_template.py
jonathanzong/dmca
70157cff983310e5951024aa80e99e7a5404d758
[ "MIT" ]
2
2022-02-01T05:48:07.000Z
2022-02-01T05:49:29.000Z
alembic/versions/4f53ec506661_add_study_template.py
jonathanzong/bartleby
70157cff983310e5951024aa80e99e7a5404d758
[ "MIT" ]
null
null
null
"""add study template Revision ID: 4f53ec506661 Revises: 4302608638bc Create Date: 2018-05-23 15:44:01.450488 """ # revision identifiers, used by Alembic. revision = '4f53ec506661' down_revision = '4302608638bc' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa def upgrade(engine_name): globals()["upgrade_%s" % engine_name]() def downgrade(engine_name): globals()["downgrade_%s" % engine_name]() def upgrade_development(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('twitter_user_recruitment_tweet_attempt', sa.Column('study_template', sa.String(length=64), nullable=True)) # ### end Alembic commands ### def downgrade_development(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('twitter_user_recruitment_tweet_attempt', 'study_template') # ### end Alembic commands ### def upgrade_test(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('twitter_user_recruitment_tweet_attempt', sa.Column('study_template', sa.String(length=64), nullable=True)) # ### end Alembic commands ### def downgrade_test(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('twitter_user_recruitment_tweet_attempt', 'study_template') # ### end Alembic commands ### def upgrade_production(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('twitter_user_recruitment_tweet_attempt', sa.Column('study_template', sa.String(length=64), nullable=True)) # ### end Alembic commands ### def downgrade_production(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('twitter_user_recruitment_tweet_attempt', 'study_template') # ### end Alembic commands ###
28.292308
125
0.712887
revision = '4f53ec506661' down_revision = '4302608638bc' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa def upgrade(engine_name): globals()["upgrade_%s" % engine_name]() def downgrade(engine_name): globals()["downgrade_%s" % engine_name]() def upgrade_development():
true
true
f725acb2361d7d3cd6f93696255dbd053911f91e
18,253
py
Python
iotbx/regression/tst_map_model_manager_3.py
TiankunZhou/cctbx_project
373f302f00c12d7239f8e37e3165e62bc1d852cc
[ "BSD-3-Clause-LBNL" ]
null
null
null
iotbx/regression/tst_map_model_manager_3.py
TiankunZhou/cctbx_project
373f302f00c12d7239f8e37e3165e62bc1d852cc
[ "BSD-3-Clause-LBNL" ]
null
null
null
iotbx/regression/tst_map_model_manager_3.py
TiankunZhou/cctbx_project
373f302f00c12d7239f8e37e3165e62bc1d852cc
[ "BSD-3-Clause-LBNL" ]
null
null
null
from __future__ import absolute_import, division, print_function from cctbx.array_family import flex import os, sys from libtbx.utils import Sorry from libtbx.test_utils import approx_equal from mmtbx.model import manager as model_manager from iotbx.data_manager import DataManager def exercise(file_name, out = sys.stdout): # Set up source data if not os.path.isfile(file_name): raise Sorry("Missing the file: %s" %(file_name)+"\n") print ("Reading from %s" %(file_name)) from iotbx.map_manager import map_manager m = map_manager(file_name) # make a little model sites_cart = flex.vec3_double( ((8, 10, 12), (14, 15, 16))) model = model_manager.from_sites_cart( atom_name = ' CA ', resname = 'ALA', chain_id = 'A', b_iso = 30., occ = 1., scatterer = 'C', sites_cart = sites_cart, crystal_symmetry = m.crystal_symmetry()) # make a map_model_manager with lots of maps and model and ncs from iotbx.map_model_manager import map_model_manager from mmtbx.ncs.ncs import ncs ncs_object=ncs() ncs_object.set_unit_ncs() mask_mm=m.deep_copy() mask_mm.set_is_mask(True) mam = map_model_manager( map_manager = m, ncs_object = ncs_object, map_manager_1 = m.deep_copy(), map_manager_2 = m.deep_copy(), extra_map_manager_list = [m.deep_copy(),m.deep_copy(),m.deep_copy()], extra_map_manager_id_list = ["extra_1","extra_2","map_manager_mask"], model = model.deep_copy(),) print (mam.map_manager()) print (mam.model()) print (mam.map_manager_1()) print (mam.map_manager_2()) print (mam.map_manager_mask()) print (mam.map_manager().ncs_object()) all_map_names=mam.map_id_list() for id in all_map_names: print("Map_manager %s: %s " %(id,mam.get_map_manager_by_id(id))) dm = DataManager(['model','miller_array', 'real_map', 'phil','ncs_spec']) dm.set_overwrite(True) # Create a model with ncs from iotbx.regression.ncs.tst_ncs import pdb_str_5 file_name='tst_mam.pdb' f=open(file_name,'w') print (pdb_str_5, file = f) f.close() # Generate map data from this model (it has ncs) mmm=map_model_manager() mmm.generate_map(box_cushion=0, file_name=file_name,n_residues=500) ncs_mam=mmm.deep_copy() ncs_mam_copy=mmm.deep_copy() # Make sure this model has 126 sites (42 sites times 3-fold ncs) assert ncs_mam.model().get_sites_cart().size() == 126 assert approx_equal (ncs_mam.model().get_sites_cart()[0], (23.560999999999996, 8.159, 10.660000000000002)) # Get just unique part (42 sites) unique_mam=ncs_mam.extract_all_maps_around_model(select_unique_by_ncs=True) assert unique_mam.model().get_sites_cart().size() == 42 assert approx_equal (unique_mam.model().get_sites_cart()[0], (18.740916666666664, 13.1794, 16.10544)) # Make sure that the extraction did not change the original but does change # the extracted part assert (unique_mam.model().get_sites_cart()[0] != ncs_mam.model().get_sites_cart()[0]) # it was a deep copy so original stays # Shift back the extracted part and make sure it matches the original now shifted_back_unique_model=mmm.get_model_from_other(unique_mam.deep_copy()) assert approx_equal (shifted_back_unique_model.get_sites_cart()[0], (23.560999999999996, 8.158999999999997, 10.66)) # Change the extracted model sites_cart=unique_mam.model().get_sites_cart() sites_cart[0]=(1,1,1) unique_mam.model().get_hierarchy().atoms().set_xyz(sites_cart) # Note; setting xyz in hierarchy does not set xrs by itself. do that now: unique_mam.model().set_sites_cart_from_hierarchy(multiply_ncs=False) # Make sure we really changed it assert approx_equal (unique_mam.model().get_sites_cart()[0], (1,1,1)) # Now propagate all the changes in this unique part to entire original model # using NCS ncs_mam.propagate_model_from_other(other = unique_mam, model_id = 'model', other_model_id = 'model') # ...and check that copy 1 and copy 2 both change assert approx_equal (ncs_mam.model().get_sites_cart()[0], (5.820083333333333, -4.020400000000001, -4.445440000000001)) assert approx_equal (ncs_mam.model().get_sites_cart()[42], (38.41904613024224, 17.233251085893276, 2.5547442135142524)) # Find ncs from map or model nn=ncs_mam_copy nn.write_map('ncs.ccp4') nn.write_model('ncs.pdb') ncs_object=nn.get_ncs_from_model() dm.write_ncs_spec_file(ncs_object,'ncs.ncs_spec') print ("NCS from map",ncs_object) nn.set_ncs_object(ncs_object) print ("NCS now: ",nn.ncs_object()) nn.get_ncs_from_map(ncs_object=ncs_object) print ("ncs cc:",nn.ncs_cc()) assert approx_equal(nn.ncs_cc(),0.961915979834,eps=0.01) # Make a deep_copy dc=mam.deep_copy() new_mam=mam.deep_copy() assert mam.map_manager().map_data()[0]==new_mam.map_manager().map_data()[0] # Make a customized_copy new_mam=mam.customized_copy(model_dict={'model':mam.model()}) assert new_mam.model() is mam.model() assert not new_mam.map_dict() is mam.map_dict() new_mam=mam.customized_copy(model_dict={'model':mam.model()}, map_dict=mam.map_dict()) assert new_mam.model() is mam.model() assert new_mam.map_dict() is mam.map_dict() print (mam) # Add a map mam = dc.deep_copy() print (mam.map_id_list()) assert len(mam.map_id_list()) == 6 mam.add_map_manager_by_id(mam.map_manager().deep_copy(),'new_map_manager') print (mam.map_id_list()) assert len(mam.map_id_list()) == 7 # duplicate a map mam = dc.deep_copy() print (mam.map_id_list()) assert len(mam.map_id_list()) == 6 mam.duplicate_map_manager('map_manager','new_map_manager') print (mam.map_id_list()) assert len(mam.map_id_list()) == 7 # resolution_filter a map mam = dc.deep_copy() print (mam.map_id_list()) mam.duplicate_map_manager('map_manager','new_map_manager') mam.resolution_filter(map_id='new_map_manager',d_min=3.5,d_max=6) # Add a model mam = dc.deep_copy() print (mam.model_id_list()) assert len(mam.model_id_list()) == 1 mam.add_model_by_id(mam.model().deep_copy(),'new_model') print (mam.model_id_list()) assert len(mam.model_id_list()) == 2 # Initialize a map mam1=new_mam.deep_copy() mam1.initialize_maps(map_value=6) assert mam1.map_manager().map_data()[225] == 6 # Create mask around density and apply to all maps mam1=new_mam.deep_copy() mam1.mask_all_maps_around_density(solvent_content=0.5, soft_mask=True,) s = (mam1.get_map_manager_by_id('mask').map_data() > 0.5) assert approx_equal( (s.count(True),s.size()), (1024,2048)) # Create mask around edges and apply to all maps mam1=new_mam.deep_copy() mam1.mask_all_maps_around_edges() s = (mam1.get_map_manager_by_id('mask').map_data() > 0.5) assert approx_equal( (s.count(True),s.size()), (1176,2048)) # Create a soft mask around model and apply to all maps new_mam.mask_all_maps_around_atoms(mask_atoms_atom_radius=8, soft_mask=True) s = (new_mam.get_map_manager_by_id('mask').map_data() > 0.5) assert approx_equal( (s.count(True),s.size()), (1944,2048)) # Create a soft mask around model and do not do anything with it new_mam.create_mask_around_atoms(mask_atoms_atom_radius=8, soft_mask=True) s = (new_mam.get_map_manager_by_id('mask').map_data() > 0.5) assert approx_equal( (s.count(True),s.size()), (1944,2048)) # Create a soft mask around model and do not do anything with it, wrapping =true dummy_mam=new_mam.deep_copy() dummy_mam.map_manager().set_wrapping(True) dummy_mam.create_mask_around_atoms(mask_atoms_atom_radius=8, soft_mask=True) s = (dummy_mam.get_map_manager_by_id('mask').map_data() > 0.5) assert approx_equal( (s.count(True),s.size()), (1944,2048)) # Create a sharp mask around model and do not do anything with it new_mam.create_mask_around_atoms(soft_mask=False, mask_atoms_atom_radius=8) s = (new_mam.get_map_manager_by_id('mask').map_data() > 0.5) assert approx_equal( (s.count(True),s.size()), (138,2048)) # Mask around edges and do not do anything with it mam=dc.deep_copy() mam.create_mask_around_edges() s = (mam.get_map_manager_by_id('mask').map_data() > 0.5) assert approx_equal( (s.count(True),s.size()), (1176,2048)) # Mask around density and to not do anything with it mam=dc.deep_copy() mam.create_mask_around_density(soft_mask=False) s = (mam.get_map_manager_by_id('mask').map_data() > 0.5) assert approx_equal( (s.count(True),s.size()), (1000,2048)) # Apply the current mask to one map mam.apply_mask_to_map('map_manager') s = (mam.map_manager().map_data() > 0.) assert approx_equal( (s.count(True),s.size()), (640,2048)) s = (mam.map_manager().map_data() != 0.) assert approx_equal( (s.count(True),s.size()), (1000,2048)) assert approx_equal ((mam.map_manager().map_data()[225]),-0.0418027862906) # Apply any mask to one map mam.apply_mask_to_map('map_manager',mask_id='mask') s = (mam.map_manager().map_data() > 0.) assert approx_equal( (s.count(True),s.size()), (640,2048)) s = (mam.map_manager().map_data() != 0.) assert approx_equal( (s.count(True),s.size()), (1000,2048)) assert approx_equal ((mam.map_manager().map_data()[225]),-0.0418027862906) # Apply the mask to all maps mam.apply_mask_to_maps() s = (mam.map_manager().map_data() > 0.) assert approx_equal( (s.count(True),s.size()), (640,2048)) s = (mam.map_manager().map_data() != 0.) assert approx_equal( (s.count(True),s.size()), (1000,2048)) assert approx_equal ((mam.map_manager().map_data()[225]),-0.0418027862906) # Apply the mask to all maps, setting outside value to mean inside mam.apply_mask_to_maps(set_outside_to_mean_inside=True) s = (mam.map_manager().map_data() > 0.) assert approx_equal( (s.count(True),s.size()), (1688,2048)) s = (mam.map_manager().map_data() != 0.) assert approx_equal( (s.count(True),s.size()), (2048,2048)) assert approx_equal ((mam.map_manager().map_data()[2047]),-0.0759598612785) s = (mam.get_map_manager_by_id('mask').map_data() > 0).as_1d() inside = mam.map_manager().map_data().as_1d().select(s) outside = mam.map_manager().map_data().as_1d().select(~s) assert approx_equal ((inside.min_max_mean().max,outside.min_max_mean().max), (0.335603952408,0.0239064293122)) # Make a new map and model, get mam and box with selection mmm=map_model_manager() mmm.generate_map(box_cushion=0,wrapping=True) mam=mmm mam_dc=mam.deep_copy() new_mm_1=mam.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1.map_data().all()), ((18, 25, 20),(18, 25, 20))) # Get local fsc or randomized map dc=mam_dc.deep_copy() dc.map_manager().set_wrapping(False) map_coeffs = dc.map_manager().map_as_fourier_coefficients(d_min=3) from cctbx.development.create_models_or_maps import generate_map new_mm_1 = generate_map(map_coeffs=map_coeffs, d_min=3, low_resolution_real_space_noise_fraction=1, high_resolution_real_space_noise_fraction=50, map_manager=dc.map_manager(), random_seed=124321) new_mm_2 = generate_map(map_coeffs=map_coeffs, d_min=3, low_resolution_real_space_noise_fraction=1, high_resolution_real_space_noise_fraction=50, map_manager=dc.map_manager(), random_seed=734119) dc.add_map_manager_by_id(new_mm_1,'map_manager_1') dc.add_map_manager_by_id(new_mm_2,'map_manager_2') cc=dc.map_map_cc() fsc_curve=dc.map_map_fsc() dc.set_log(sys.stdout) dc.local_fsc(n_boxes = 1) # Get map-map FSC dc=mam_dc.deep_copy() dc.duplicate_map_manager(map_id='map_manager',new_map_id='filtered') dc.resolution_filter(d_min=3.5, d_max=10, map_id='filtered') dc.create_mask_around_atoms() fsc_curve=dc.map_map_fsc( map_id_1='map_manager',map_id_2='filtered',mask_id='mask', resolution=3.5,fsc_cutoff = 0.97) assert approx_equal(fsc_curve.d_min, 3.93793648601,eps=0.01) assert approx_equal (fsc_curve.fsc.fsc[-1],0.707536576779) # Get map-map CC dc=mam_dc.deep_copy() dc.duplicate_map_manager(map_id='map_manager',new_map_id='filtered') dc.resolution_filter(d_min=3.5, d_max=6, map_id='filtered') cc=dc.map_map_cc('map_manager','filtered') assert approx_equal(cc , 0.676687646486) # Get map-map CC with mask dc=mam_dc.deep_copy() dc.duplicate_map_manager(map_id='map_manager',new_map_id='filtered') dc.create_mask_around_density(mask_id='filtered') cc=dc.map_map_cc('map_manager','filtered',mask_id='mask') assert approx_equal(cc , 0.422523947639) # box around model mam=mam_dc.deep_copy() mam.box_all_maps_around_model_and_shift_origin( selection_string="resseq 221:221") new_mm_1=mam.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1.map_data().all()), ((18, 25, 20),(24, 20, 20))) # extract_around_model (get new mam) new_mam_dc=mam_dc.extract_all_maps_around_model( selection_string="resseq 221:221") new_mm_1a=new_mam_dc.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1a.map_data().all()), ((18, 25, 20),(24, 20, 20))) assert approx_equal(new_mm_1.map_data(),new_mm_1a.map_data()) # box around_density mam2=mam_dc.deep_copy() mam2.box_all_maps_around_density_and_shift_origin(box_cushion=0) new_mm_2=mam2.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_2.map_data().all()), ((18, 25, 20),(16, 23, 18))) # extract_around_density (get new mam) mam2=mam_dc.deep_copy() mam2_b=mam2.extract_all_maps_around_density(box_cushion=0) new_mm_2=mam2_b.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_2.map_data().all()), ((18, 25, 20),(16, 23, 18))) # Repeat as map_model_manager: mmm=mam_dc.as_map_model_manager().deep_copy() mmm.box_all_maps_around_model_and_shift_origin( selection_string="resseq 221:221") new_mm_1a=mmm.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1a.map_data().all()), ((24, 20, 20),(24, 20, 20))) assert approx_equal(new_mm_1.map_data(),new_mm_1a.map_data()) # box around density mam.box_all_maps_around_density_and_shift_origin(box_cushion=0) new_mm_1=mam.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1.map_data().all()), ((24, 20 , 20),(22, 18, 18))) # extract around density (get new mam) mam1=mam_dc.deep_copy() mam1.extract_all_maps_around_density(box_cushion=0) new_mm_1=mam1.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1.map_data().all()), ((24, 20 , 20),(18, 25, 20))) # create mask around density, then box around mask (i.e., box around density) mam.create_mask_around_density(soft_mask=False) mam.box_all_maps_around_mask_and_shift_origin(box_cushion=3) new_mm_1=mam.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1.map_data().all()), ((24, 20 , 20),(22, 18, 18))) # box with bounds mam.box_all_maps_with_bounds_and_shift_origin(lower_bounds=(10,10,10), upper_bounds=(15,15,15)) new_mm_1=mam.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1.map_data().all()), ((24, 20, 20),(6, 6, 6))) # extract with bounds mam=mam_dc.deep_copy() mam_1=mam.extract_all_maps_with_bounds(lower_bounds=(10,10,10), upper_bounds=(15,15,15)) new_mm_1=mam_1.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1.map_data().all()), ((24, 20, 20),(6, 6, 6))) # box with unique mam=mam_dc.deep_copy() mam.box_all_maps_around_unique_and_shift_origin( molecular_mass=2500,resolution=3) new_mm_1=mam.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1.map_data().all()), ((24, 20, 20),(18, 25, 20))) # extract with unique mam=mam_dc.deep_copy() mam_1=mam.extract_all_maps_around_unique( molecular_mass=2500,resolution=3) new_mm_1=mam_1.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1.map_data().all()), ((24, 20, 20),(18, 25, 20))) # extract a box and then restore model into same reference as current mam mam=mam_dc.deep_copy() mam.box_all_maps_with_bounds_and_shift_origin(lower_bounds=(2,2,2), upper_bounds=(17,17,17)) print("mam:",mam.model().get_sites_cart()[0],mam.map_manager().origin_is_zero()) # extract a box box_mam=mam.extract_all_maps_with_bounds(lower_bounds=(10,10,10), upper_bounds=(15,15,15)) box_model=box_mam.model() matched_box_model=mam.get_model_from_other(box_mam) assert approx_equal(matched_box_model.get_sites_cart()[0],mam.model().get_sites_cart()[0]) # Convert a map to fourier coefficients mam=mam_dc.deep_copy() ma=mam.map_as_fourier_coefficients(d_min=3) assert approx_equal(ma.d_min(),3.01655042414) mam.add_map_from_fourier_coefficients(ma, map_id='new_map_manager') cc=flex.linear_correlation( mam.get_map_manager_by_id('map_manager').map_data().as_1d(), mam.get_map_manager_by_id('new_map_manager').map_data().as_1d()).coefficient() assert (cc >= 0.99) # Get map-model CC dc=mam_dc.extract_all_maps_around_model( selection_string="(name ca or name cb or name c or name o) "+ "and resseq 221:221", box_cushion=0) cc=dc.map_model_cc(resolution=3) assert approx_equal (cc, 0.817089390421) # Remove model outside map dc.remove_model_outside_map(boundary=0) assert (mam_dc.model().get_sites_cart().size(), dc.model().get_sites_cart().size()) == (86, 4) # shift a model to match the map dc=mam_dc.extract_all_maps_around_model( selection_string="(name ca or name cb or name c or name o) "+ "and resseq 221:221", box_cushion=0) actual_model=dc.model().deep_copy() working_model=dc.model().deep_copy() working_model.set_shift_cart((0,0,0)) working_model.set_sites_cart(working_model.get_sites_cart()-actual_model.shift_cart()) dc.shift_any_model_to_match(working_model) assert approx_equal (actual_model.get_sites_cart()[0],working_model.get_sites_cart()[0]) if __name__ == "__main__": args = sys.argv[1:] import libtbx.load_env if not args: file_name = libtbx.env.under_dist( module_name = "iotbx", path = "ccp4_map/tst_input.map") args = [file_name] if libtbx.env.has_module("phenix"): exercise(file_name = args[0]) else: print("Skipped: Requires phenix module") print ("OK")
38.027083
92
0.718402
from __future__ import absolute_import, division, print_function from cctbx.array_family import flex import os, sys from libtbx.utils import Sorry from libtbx.test_utils import approx_equal from mmtbx.model import manager as model_manager from iotbx.data_manager import DataManager def exercise(file_name, out = sys.stdout): if not os.path.isfile(file_name): raise Sorry("Missing the file: %s" %(file_name)+"\n") print ("Reading from %s" %(file_name)) from iotbx.map_manager import map_manager m = map_manager(file_name) sites_cart = flex.vec3_double( ((8, 10, 12), (14, 15, 16))) model = model_manager.from_sites_cart( atom_name = ' CA ', resname = 'ALA', chain_id = 'A', b_iso = 30., occ = 1., scatterer = 'C', sites_cart = sites_cart, crystal_symmetry = m.crystal_symmetry()) from iotbx.map_model_manager import map_model_manager from mmtbx.ncs.ncs import ncs ncs_object=ncs() ncs_object.set_unit_ncs() mask_mm=m.deep_copy() mask_mm.set_is_mask(True) mam = map_model_manager( map_manager = m, ncs_object = ncs_object, map_manager_1 = m.deep_copy(), map_manager_2 = m.deep_copy(), extra_map_manager_list = [m.deep_copy(),m.deep_copy(),m.deep_copy()], extra_map_manager_id_list = ["extra_1","extra_2","map_manager_mask"], model = model.deep_copy(),) print (mam.map_manager()) print (mam.model()) print (mam.map_manager_1()) print (mam.map_manager_2()) print (mam.map_manager_mask()) print (mam.map_manager().ncs_object()) all_map_names=mam.map_id_list() for id in all_map_names: print("Map_manager %s: %s " %(id,mam.get_map_manager_by_id(id))) dm = DataManager(['model','miller_array', 'real_map', 'phil','ncs_spec']) dm.set_overwrite(True) from iotbx.regression.ncs.tst_ncs import pdb_str_5 file_name='tst_mam.pdb' f=open(file_name,'w') print (pdb_str_5, file = f) f.close() mmm=map_model_manager() mmm.generate_map(box_cushion=0, file_name=file_name,n_residues=500) ncs_mam=mmm.deep_copy() ncs_mam_copy=mmm.deep_copy() assert ncs_mam.model().get_sites_cart().size() == 126 assert approx_equal (ncs_mam.model().get_sites_cart()[0], (23.560999999999996, 8.159, 10.660000000000002)) unique_mam=ncs_mam.extract_all_maps_around_model(select_unique_by_ncs=True) assert unique_mam.model().get_sites_cart().size() == 42 assert approx_equal (unique_mam.model().get_sites_cart()[0], (18.740916666666664, 13.1794, 16.10544)) assert (unique_mam.model().get_sites_cart()[0] != ncs_mam.model().get_sites_cart()[0]) shifted_back_unique_model=mmm.get_model_from_other(unique_mam.deep_copy()) assert approx_equal (shifted_back_unique_model.get_sites_cart()[0], (23.560999999999996, 8.158999999999997, 10.66)) sites_cart=unique_mam.model().get_sites_cart() sites_cart[0]=(1,1,1) unique_mam.model().get_hierarchy().atoms().set_xyz(sites_cart) unique_mam.model().set_sites_cart_from_hierarchy(multiply_ncs=False) assert approx_equal (unique_mam.model().get_sites_cart()[0], (1,1,1)) ncs_mam.propagate_model_from_other(other = unique_mam, model_id = 'model', other_model_id = 'model') assert approx_equal (ncs_mam.model().get_sites_cart()[0], (5.820083333333333, -4.020400000000001, -4.445440000000001)) assert approx_equal (ncs_mam.model().get_sites_cart()[42], (38.41904613024224, 17.233251085893276, 2.5547442135142524)) nn=ncs_mam_copy nn.write_map('ncs.ccp4') nn.write_model('ncs.pdb') ncs_object=nn.get_ncs_from_model() dm.write_ncs_spec_file(ncs_object,'ncs.ncs_spec') print ("NCS from map",ncs_object) nn.set_ncs_object(ncs_object) print ("NCS now: ",nn.ncs_object()) nn.get_ncs_from_map(ncs_object=ncs_object) print ("ncs cc:",nn.ncs_cc()) assert approx_equal(nn.ncs_cc(),0.961915979834,eps=0.01) dc=mam.deep_copy() new_mam=mam.deep_copy() assert mam.map_manager().map_data()[0]==new_mam.map_manager().map_data()[0] new_mam=mam.customized_copy(model_dict={'model':mam.model()}) assert new_mam.model() is mam.model() assert not new_mam.map_dict() is mam.map_dict() new_mam=mam.customized_copy(model_dict={'model':mam.model()}, map_dict=mam.map_dict()) assert new_mam.model() is mam.model() assert new_mam.map_dict() is mam.map_dict() print (mam) mam = dc.deep_copy() print (mam.map_id_list()) assert len(mam.map_id_list()) == 6 mam.add_map_manager_by_id(mam.map_manager().deep_copy(),'new_map_manager') print (mam.map_id_list()) assert len(mam.map_id_list()) == 7 mam = dc.deep_copy() print (mam.map_id_list()) assert len(mam.map_id_list()) == 6 mam.duplicate_map_manager('map_manager','new_map_manager') print (mam.map_id_list()) assert len(mam.map_id_list()) == 7 mam = dc.deep_copy() print (mam.map_id_list()) mam.duplicate_map_manager('map_manager','new_map_manager') mam.resolution_filter(map_id='new_map_manager',d_min=3.5,d_max=6) mam = dc.deep_copy() print (mam.model_id_list()) assert len(mam.model_id_list()) == 1 mam.add_model_by_id(mam.model().deep_copy(),'new_model') print (mam.model_id_list()) assert len(mam.model_id_list()) == 2 mam1=new_mam.deep_copy() mam1.initialize_maps(map_value=6) assert mam1.map_manager().map_data()[225] == 6 mam1=new_mam.deep_copy() mam1.mask_all_maps_around_density(solvent_content=0.5, soft_mask=True,) s = (mam1.get_map_manager_by_id('mask').map_data() > 0.5) assert approx_equal( (s.count(True),s.size()), (1024,2048)) mam1=new_mam.deep_copy() mam1.mask_all_maps_around_edges() s = (mam1.get_map_manager_by_id('mask').map_data() > 0.5) assert approx_equal( (s.count(True),s.size()), (1176,2048)) new_mam.mask_all_maps_around_atoms(mask_atoms_atom_radius=8, soft_mask=True) s = (new_mam.get_map_manager_by_id('mask').map_data() > 0.5) assert approx_equal( (s.count(True),s.size()), (1944,2048)) new_mam.create_mask_around_atoms(mask_atoms_atom_radius=8, soft_mask=True) s = (new_mam.get_map_manager_by_id('mask').map_data() > 0.5) assert approx_equal( (s.count(True),s.size()), (1944,2048)) dummy_mam=new_mam.deep_copy() dummy_mam.map_manager().set_wrapping(True) dummy_mam.create_mask_around_atoms(mask_atoms_atom_radius=8, soft_mask=True) s = (dummy_mam.get_map_manager_by_id('mask').map_data() > 0.5) assert approx_equal( (s.count(True),s.size()), (1944,2048)) new_mam.create_mask_around_atoms(soft_mask=False, mask_atoms_atom_radius=8) s = (new_mam.get_map_manager_by_id('mask').map_data() > 0.5) assert approx_equal( (s.count(True),s.size()), (138,2048)) mam=dc.deep_copy() mam.create_mask_around_edges() s = (mam.get_map_manager_by_id('mask').map_data() > 0.5) assert approx_equal( (s.count(True),s.size()), (1176,2048)) mam=dc.deep_copy() mam.create_mask_around_density(soft_mask=False) s = (mam.get_map_manager_by_id('mask').map_data() > 0.5) assert approx_equal( (s.count(True),s.size()), (1000,2048)) mam.apply_mask_to_map('map_manager') s = (mam.map_manager().map_data() > 0.) assert approx_equal( (s.count(True),s.size()), (640,2048)) s = (mam.map_manager().map_data() != 0.) assert approx_equal( (s.count(True),s.size()), (1000,2048)) assert approx_equal ((mam.map_manager().map_data()[225]),-0.0418027862906) mam.apply_mask_to_map('map_manager',mask_id='mask') s = (mam.map_manager().map_data() > 0.) assert approx_equal( (s.count(True),s.size()), (640,2048)) s = (mam.map_manager().map_data() != 0.) assert approx_equal( (s.count(True),s.size()), (1000,2048)) assert approx_equal ((mam.map_manager().map_data()[225]),-0.0418027862906) mam.apply_mask_to_maps() s = (mam.map_manager().map_data() > 0.) assert approx_equal( (s.count(True),s.size()), (640,2048)) s = (mam.map_manager().map_data() != 0.) assert approx_equal( (s.count(True),s.size()), (1000,2048)) assert approx_equal ((mam.map_manager().map_data()[225]),-0.0418027862906) mam.apply_mask_to_maps(set_outside_to_mean_inside=True) s = (mam.map_manager().map_data() > 0.) assert approx_equal( (s.count(True),s.size()), (1688,2048)) s = (mam.map_manager().map_data() != 0.) assert approx_equal( (s.count(True),s.size()), (2048,2048)) assert approx_equal ((mam.map_manager().map_data()[2047]),-0.0759598612785) s = (mam.get_map_manager_by_id('mask').map_data() > 0).as_1d() inside = mam.map_manager().map_data().as_1d().select(s) outside = mam.map_manager().map_data().as_1d().select(~s) assert approx_equal ((inside.min_max_mean().max,outside.min_max_mean().max), (0.335603952408,0.0239064293122)) mmm=map_model_manager() mmm.generate_map(box_cushion=0,wrapping=True) mam=mmm mam_dc=mam.deep_copy() new_mm_1=mam.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1.map_data().all()), ((18, 25, 20),(18, 25, 20))) dc=mam_dc.deep_copy() dc.map_manager().set_wrapping(False) map_coeffs = dc.map_manager().map_as_fourier_coefficients(d_min=3) from cctbx.development.create_models_or_maps import generate_map new_mm_1 = generate_map(map_coeffs=map_coeffs, d_min=3, low_resolution_real_space_noise_fraction=1, high_resolution_real_space_noise_fraction=50, map_manager=dc.map_manager(), random_seed=124321) new_mm_2 = generate_map(map_coeffs=map_coeffs, d_min=3, low_resolution_real_space_noise_fraction=1, high_resolution_real_space_noise_fraction=50, map_manager=dc.map_manager(), random_seed=734119) dc.add_map_manager_by_id(new_mm_1,'map_manager_1') dc.add_map_manager_by_id(new_mm_2,'map_manager_2') cc=dc.map_map_cc() fsc_curve=dc.map_map_fsc() dc.set_log(sys.stdout) dc.local_fsc(n_boxes = 1) dc=mam_dc.deep_copy() dc.duplicate_map_manager(map_id='map_manager',new_map_id='filtered') dc.resolution_filter(d_min=3.5, d_max=10, map_id='filtered') dc.create_mask_around_atoms() fsc_curve=dc.map_map_fsc( map_id_1='map_manager',map_id_2='filtered',mask_id='mask', resolution=3.5,fsc_cutoff = 0.97) assert approx_equal(fsc_curve.d_min, 3.93793648601,eps=0.01) assert approx_equal (fsc_curve.fsc.fsc[-1],0.707536576779) dc=mam_dc.deep_copy() dc.duplicate_map_manager(map_id='map_manager',new_map_id='filtered') dc.resolution_filter(d_min=3.5, d_max=6, map_id='filtered') cc=dc.map_map_cc('map_manager','filtered') assert approx_equal(cc , 0.676687646486) dc=mam_dc.deep_copy() dc.duplicate_map_manager(map_id='map_manager',new_map_id='filtered') dc.create_mask_around_density(mask_id='filtered') cc=dc.map_map_cc('map_manager','filtered',mask_id='mask') assert approx_equal(cc , 0.422523947639) mam=mam_dc.deep_copy() mam.box_all_maps_around_model_and_shift_origin( selection_string="resseq 221:221") new_mm_1=mam.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1.map_data().all()), ((18, 25, 20),(24, 20, 20))) new_mam_dc=mam_dc.extract_all_maps_around_model( selection_string="resseq 221:221") new_mm_1a=new_mam_dc.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1a.map_data().all()), ((18, 25, 20),(24, 20, 20))) assert approx_equal(new_mm_1.map_data(),new_mm_1a.map_data()) mam2=mam_dc.deep_copy() mam2.box_all_maps_around_density_and_shift_origin(box_cushion=0) new_mm_2=mam2.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_2.map_data().all()), ((18, 25, 20),(16, 23, 18))) mam2=mam_dc.deep_copy() mam2_b=mam2.extract_all_maps_around_density(box_cushion=0) new_mm_2=mam2_b.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_2.map_data().all()), ((18, 25, 20),(16, 23, 18))) mmm=mam_dc.as_map_model_manager().deep_copy() mmm.box_all_maps_around_model_and_shift_origin( selection_string="resseq 221:221") new_mm_1a=mmm.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1a.map_data().all()), ((24, 20, 20),(24, 20, 20))) assert approx_equal(new_mm_1.map_data(),new_mm_1a.map_data()) mam.box_all_maps_around_density_and_shift_origin(box_cushion=0) new_mm_1=mam.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1.map_data().all()), ((24, 20 , 20),(22, 18, 18))) mam1=mam_dc.deep_copy() mam1.extract_all_maps_around_density(box_cushion=0) new_mm_1=mam1.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1.map_data().all()), ((24, 20 , 20),(18, 25, 20))) mam.create_mask_around_density(soft_mask=False) mam.box_all_maps_around_mask_and_shift_origin(box_cushion=3) new_mm_1=mam.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1.map_data().all()), ((24, 20 , 20),(22, 18, 18))) mam.box_all_maps_with_bounds_and_shift_origin(lower_bounds=(10,10,10), upper_bounds=(15,15,15)) new_mm_1=mam.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1.map_data().all()), ((24, 20, 20),(6, 6, 6))) mam=mam_dc.deep_copy() mam_1=mam.extract_all_maps_with_bounds(lower_bounds=(10,10,10), upper_bounds=(15,15,15)) new_mm_1=mam_1.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1.map_data().all()), ((24, 20, 20),(6, 6, 6))) mam=mam_dc.deep_copy() mam.box_all_maps_around_unique_and_shift_origin( molecular_mass=2500,resolution=3) new_mm_1=mam.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1.map_data().all()), ((24, 20, 20),(18, 25, 20))) mam=mam_dc.deep_copy() mam_1=mam.extract_all_maps_around_unique( molecular_mass=2500,resolution=3) new_mm_1=mam_1.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1.map_data().all()), ((24, 20, 20),(18, 25, 20))) mam=mam_dc.deep_copy() mam.box_all_maps_with_bounds_and_shift_origin(lower_bounds=(2,2,2), upper_bounds=(17,17,17)) print("mam:",mam.model().get_sites_cart()[0],mam.map_manager().origin_is_zero()) box_mam=mam.extract_all_maps_with_bounds(lower_bounds=(10,10,10), upper_bounds=(15,15,15)) box_model=box_mam.model() matched_box_model=mam.get_model_from_other(box_mam) assert approx_equal(matched_box_model.get_sites_cart()[0],mam.model().get_sites_cart()[0]) mam=mam_dc.deep_copy() ma=mam.map_as_fourier_coefficients(d_min=3) assert approx_equal(ma.d_min(),3.01655042414) mam.add_map_from_fourier_coefficients(ma, map_id='new_map_manager') cc=flex.linear_correlation( mam.get_map_manager_by_id('map_manager').map_data().as_1d(), mam.get_map_manager_by_id('new_map_manager').map_data().as_1d()).coefficient() assert (cc >= 0.99) dc=mam_dc.extract_all_maps_around_model( selection_string="(name ca or name cb or name c or name o) "+ "and resseq 221:221", box_cushion=0) cc=dc.map_model_cc(resolution=3) assert approx_equal (cc, 0.817089390421) dc.remove_model_outside_map(boundary=0) assert (mam_dc.model().get_sites_cart().size(), dc.model().get_sites_cart().size()) == (86, 4) dc=mam_dc.extract_all_maps_around_model( selection_string="(name ca or name cb or name c or name o) "+ "and resseq 221:221", box_cushion=0) actual_model=dc.model().deep_copy() working_model=dc.model().deep_copy() working_model.set_shift_cart((0,0,0)) working_model.set_sites_cart(working_model.get_sites_cart()-actual_model.shift_cart()) dc.shift_any_model_to_match(working_model) assert approx_equal (actual_model.get_sites_cart()[0],working_model.get_sites_cart()[0]) if __name__ == "__main__": args = sys.argv[1:] import libtbx.load_env if not args: file_name = libtbx.env.under_dist( module_name = "iotbx", path = "ccp4_map/tst_input.map") args = [file_name] if libtbx.env.has_module("phenix"): exercise(file_name = args[0]) else: print("Skipped: Requires phenix module") print ("OK")
true
true
f725ad5a075727936af4a26120e61b5c25cd3bc9
193,257
py
Python
backend/mips_to_c/src/translate.py
Rainchus/decomp.me
607aab29a18656dcbc0443505ef2944c10afa085
[ "MIT" ]
null
null
null
backend/mips_to_c/src/translate.py
Rainchus/decomp.me
607aab29a18656dcbc0443505ef2944c10afa085
[ "MIT" ]
null
null
null
backend/mips_to_c/src/translate.py
Rainchus/decomp.me
607aab29a18656dcbc0443505ef2944c10afa085
[ "MIT" ]
null
null
null
import abc from collections import defaultdict from contextlib import contextmanager from dataclasses import dataclass, field, replace import math import struct import sys import traceback import typing from typing import ( AbstractSet, Callable, Collection, DefaultDict, Dict, Iterator, List, Mapping, Optional, Set, Tuple, Union, ) from .c_types import CType, TypeMap from .demangle_codewarrior import parse as demangle_codewarrior_parse, CxxSymbol from .error import DecompFailure, static_assert_unreachable from .flow_graph import ( ArchFlowGraph, FlowGraph, Function, Node, ReturnNode, SwitchNode, TerminalNode, locs_clobbered_until_dominator, ) from .ir_pattern import IrPattern, simplify_ir_patterns from .options import CodingStyle, Formatter, Options, Target from .parse_file import AsmData, AsmDataEntry from .parse_instruction import ( ArchAsm, Argument, AsmAddressMode, AsmGlobalSymbol, AsmLiteral, BinOp, Instruction, InstrProcessingFailure, Macro, Register, StackLocation, current_instr, ) from .types import ( AccessPath, FunctionParam, FunctionSignature, StructDeclaration, Type, TypePool, ) InstrSet = Collection[str] InstrMap = Mapping[str, Callable[["InstrArgs"], "Expression"]] StmtInstrMap = Mapping[str, Callable[["InstrArgs"], "Statement"]] CmpInstrMap = Mapping[str, Callable[["InstrArgs"], "Condition"]] StoreInstrMap = Mapping[str, Callable[["InstrArgs"], Optional["StoreStmt"]]] MaybeInstrMap = Mapping[str, Callable[["InstrArgs"], Optional["Expression"]]] PairInstrMap = Mapping[str, Callable[["InstrArgs"], Tuple["Expression", "Expression"]]] ImplicitInstrMap = Mapping[str, Tuple[Register, Callable[["InstrArgs"], "Expression"]]] PpcCmpInstrMap = Mapping[str, Callable[["InstrArgs", str], "Expression"]] class Arch(ArchFlowGraph): instrs_ignore: InstrSet = set() instrs_store: StoreInstrMap = {} instrs_store_update: StoreInstrMap = {} instrs_load_update: InstrMap = {} instrs_branches: CmpInstrMap = {} instrs_float_branches: InstrSet = set() instrs_float_comp: CmpInstrMap = {} instrs_ppc_compare: PpcCmpInstrMap = {} instrs_jumps: InstrSet = set() instrs_fn_call: InstrSet = set() instrs_no_dest: StmtInstrMap = {} instrs_hi_lo: PairInstrMap = {} instrs_source_first: InstrMap = {} instrs_destination_first: InstrMap = {} instrs_implicit_destination: ImplicitInstrMap = {} @abc.abstractmethod def function_abi( self, fn_sig: FunctionSignature, likely_regs: Dict[Register, bool], *, for_call: bool, ) -> "Abi": """ Compute stack positions/registers used by a function based on its type information. Also computes a list of registers that may contain arguments, if the function has varargs or an unknown/incomplete type. """ ... @abc.abstractmethod def function_return(self, expr: "Expression") -> Dict[Register, "Expression"]: """ Compute register location(s) & values that will hold the return value of the function call `expr`. This must have a value for each register in `all_return_regs` in order to stay consistent with `Instruction.outputs`. This is why we can't use the function's return type, even though it may be more accurate. """ ... # These are defined here to avoid a circular import in flow_graph.py ir_patterns: List[IrPattern] = [] def simplify_ir(self, flow_graph: FlowGraph) -> None: simplify_ir_patterns(self, flow_graph, self.ir_patterns) ASSOCIATIVE_OPS: Set[str] = {"+", "&&", "||", "&", "|", "^", "*"} COMPOUND_ASSIGNMENT_OPS: Set[str] = {"+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>"} PSEUDO_FUNCTION_OPS: Set[str] = {"MULT_HI", "MULTU_HI", "DMULT_HI", "DMULTU_HI", "CLZ"} def as_type(expr: "Expression", type: Type, silent: bool) -> "Expression": type = type.weaken_void_ptr() ptr_target_type = type.get_pointer_target() if expr.type.unify(type): if silent or isinstance(expr, Literal): return expr elif ptr_target_type is not None: ptr_target_type_size = ptr_target_type.get_size_bytes() field_path, field_type, _ = expr.type.get_deref_field( 0, target_size=ptr_target_type_size ) if field_path is not None and field_type.unify(ptr_target_type): expr = AddressOf( StructAccess( struct_var=expr, offset=0, target_size=ptr_target_type_size, field_path=field_path, stack_info=None, type=field_type, ), type=type, ) if silent: return expr return Cast(expr=expr, reinterpret=True, silent=False, type=type) def as_f32(expr: "Expression") -> "Expression": return as_type(expr, Type.f32(), True) def as_f64(expr: "Expression") -> "Expression": return as_type(expr, Type.f64(), True) def as_sintish(expr: "Expression", *, silent: bool = False) -> "Expression": return as_type(expr, Type.sintish(), silent) def as_uintish(expr: "Expression") -> "Expression": return as_type(expr, Type.uintish(), False) def as_u32(expr: "Expression") -> "Expression": return as_type(expr, Type.u32(), False) def as_s64(expr: "Expression", *, silent: bool = False) -> "Expression": return as_type(expr, Type.s64(), silent) def as_u64(expr: "Expression", *, silent: bool = False) -> "Expression": return as_type(expr, Type.u64(), silent) def as_intish(expr: "Expression") -> "Expression": return as_type(expr, Type.intish(), True) def as_int64(expr: "Expression") -> "Expression": return as_type(expr, Type.int64(), True) def as_intptr(expr: "Expression") -> "Expression": return as_type(expr, Type.intptr(), True) def as_ptr(expr: "Expression") -> "Expression": return as_type(expr, Type.ptr(), True) def as_function_ptr(expr: "Expression") -> "Expression": return as_type(expr, Type.ptr(Type.function()), True) @dataclass class StackInfo: function: Function global_info: "GlobalInfo" flow_graph: FlowGraph allocated_stack_size: int = 0 is_leaf: bool = True is_variadic: bool = False uses_framepointer: bool = False subroutine_arg_top: int = 0 callee_save_regs: Set[Register] = field(default_factory=set) callee_save_reg_region: Tuple[int, int] = (0, 0) unique_type_map: Dict[Tuple[str, object], "Type"] = field(default_factory=dict) local_vars: List["LocalVar"] = field(default_factory=list) temp_vars: List["EvalOnceStmt"] = field(default_factory=list) phi_vars: List["PhiExpr"] = field(default_factory=list) reg_vars: Dict[Register, "RegisterVar"] = field(default_factory=dict) used_reg_vars: Set[Register] = field(default_factory=set) arguments: List["PassedInArg"] = field(default_factory=list) temp_name_counter: Dict[str, int] = field(default_factory=dict) nonzero_accesses: Set["Expression"] = field(default_factory=set) param_names: Dict[int, str] = field(default_factory=dict) stack_pointer_type: Optional[Type] = None replace_first_arg: Optional[Tuple[str, Type]] = None weak_stack_var_types: Dict[int, Type] = field(default_factory=dict) weak_stack_var_locations: Set[int] = field(default_factory=set) def temp_var(self, prefix: str) -> str: counter = self.temp_name_counter.get(prefix, 0) + 1 self.temp_name_counter[prefix] = counter return prefix + (f"_{counter}" if counter > 1 else "") def in_subroutine_arg_region(self, location: int) -> bool: if self.global_info.arch.arch == Target.ArchEnum.PPC: return False if self.is_leaf: return False assert self.subroutine_arg_top is not None return location < self.subroutine_arg_top def in_callee_save_reg_region(self, location: int) -> bool: lower_bound, upper_bound = self.callee_save_reg_region if lower_bound <= location < upper_bound: return True # PPC saves LR in the header of the previous stack frame if ( self.global_info.arch.arch == Target.ArchEnum.PPC and location == self.allocated_stack_size + 4 ): return True return False def location_above_stack(self, location: int) -> bool: return location >= self.allocated_stack_size def add_known_param(self, offset: int, name: Optional[str], type: Type) -> None: # A common pattern in C for OOP-style polymorphism involves casting a general "base" struct # to a specific "class" struct, where the first member of the class struct is the base struct. # # For the first argument of the function, if it is a pointer to a base struct, and there # exists a class struct named after the first part of the function name, assume that # this pattern is being used. Internally, treat the argument as a pointer to the *class* # struct, even though it is only a pointer to the *base* struct in the provided context. if offset == 0 and type.is_pointer() and self.replace_first_arg is None: namespace = self.function.name.partition("_")[0] base_struct_type = type.get_pointer_target() self_struct = self.global_info.typepool.get_struct_by_tag_name( namespace, self.global_info.typemap ) if ( self_struct is not None and base_struct_type is not None and base_struct_type.is_struct() ): # Check if `self_struct_type` contains a `base_struct_type` at offset 0 self_struct_type = Type.struct(self_struct) field_path, field_type, _ = self_struct_type.get_field( offset=0, target_size=base_struct_type.get_size_bytes() ) if ( field_path is not None and field_type.unify(base_struct_type) and not self_struct_type.unify(base_struct_type) ): # Success, it looks like `self_struct_type` extends `base_struct_type`. # By default, name the local var `self`, unless the argument name is `thisx` then use `this` self.replace_first_arg = (name or "_self", type) name = "this" if name == "thisx" else "self" type = Type.ptr(Type.struct(self_struct)) if name: self.param_names[offset] = name _, arg = self.get_argument(offset) self.add_argument(arg) arg.type.unify(type) def get_param_name(self, offset: int) -> Optional[str]: return self.param_names.get(offset) def add_local_var(self, var: "LocalVar") -> None: if any(v.value == var.value for v in self.local_vars): return self.local_vars.append(var) # Make sure the local vars stay sorted in order on the stack. self.local_vars.sort(key=lambda v: v.value) def add_argument(self, arg: "PassedInArg") -> None: if any(a.value == arg.value for a in self.arguments): return self.arguments.append(arg) self.arguments.sort(key=lambda a: a.value) def get_argument(self, location: int) -> Tuple["Expression", "PassedInArg"]: real_location = location & -4 arg = PassedInArg( real_location, copied=True, stack_info=self, type=self.unique_type_for("arg", real_location, Type.any_reg()), ) if real_location == location - 3: return as_type(arg, Type.int_of_size(8), True), arg if real_location == location - 2: return as_type(arg, Type.int_of_size(16), True), arg return arg, arg def record_struct_access(self, ptr: "Expression", location: int) -> None: if location: self.nonzero_accesses.add(unwrap_deep(ptr)) def has_nonzero_access(self, ptr: "Expression") -> bool: return unwrap_deep(ptr) in self.nonzero_accesses def unique_type_for(self, category: str, key: object, default: Type) -> "Type": key = (category, key) if key not in self.unique_type_map: self.unique_type_map[key] = default return self.unique_type_map[key] def saved_reg_symbol(self, reg_name: str) -> "GlobalSymbol": sym_name = "saved_reg_" + reg_name type = self.unique_type_for("saved_reg", sym_name, Type.any_reg()) return GlobalSymbol(symbol_name=sym_name, type=type) def should_save(self, expr: "Expression", offset: Optional[int]) -> bool: expr = early_unwrap(expr) if isinstance(expr, GlobalSymbol) and ( expr.symbol_name.startswith("saved_reg_") or expr.symbol_name == "sp" ): return True if ( isinstance(expr, PassedInArg) and not expr.copied and (offset is None or offset == self.allocated_stack_size + expr.value) ): return True return False def get_stack_var(self, location: int, *, store: bool) -> "Expression": # See `get_stack_info` for explanation if self.in_callee_save_reg_region(location): # Some annoying bookkeeping instruction. To avoid # further special-casing, just return whatever - it won't matter. return LocalVar(location, type=Type.any_reg(), path=None) elif self.location_above_stack(location): ret, arg = self.get_argument(location - self.allocated_stack_size) if not store: self.add_argument(arg) return ret elif self.in_subroutine_arg_region(location): return SubroutineArg(location, type=Type.any_reg()) else: # Local variable assert self.stack_pointer_type is not None field_path, field_type, _ = self.stack_pointer_type.get_deref_field( location, target_size=None ) # Some variables on the stack are compiler-managed, and aren't declared # in the original source. These variables can have different types inside # different blocks, so we track their types but assume that they may change # on each store. # TODO: Because the types are tracked in StackInfo instead of RegInfo, it is # possible that a load could incorrectly use a weak type from a sibling node # instead of a parent node. A more correct implementation would use similar # logic to the PhiExpr system. In practice however, storing types in StackInfo # works well enough because nodes are traversed approximately depth-first. # TODO: Maybe only do this for certain configurable regions? # Get the previous type stored in `location` previous_stored_type = self.weak_stack_var_types.get(location) if previous_stored_type is not None: # Check if the `field_type` is compatible with the type of the last store if not previous_stored_type.unify(field_type): # The types weren't compatible: mark this `location` as "weak" # This marker is only used to annotate the output self.weak_stack_var_locations.add(location) if store: # If there's already been a store to `location`, then return a fresh type field_type = Type.any_field() else: # Use the type of the last store instead of the one from `get_deref_field()` field_type = previous_stored_type # Track the type last stored at `location` if store: self.weak_stack_var_types[location] = field_type return LocalVar(location, type=field_type, path=field_path) def maybe_get_register_var(self, reg: Register) -> Optional["RegisterVar"]: return self.reg_vars.get(reg) def add_register_var(self, reg: Register, name: str) -> None: type = Type.floatish() if reg.is_float() else Type.intptr() self.reg_vars[reg] = RegisterVar(reg=reg, type=type, name=name) def use_register_var(self, var: "RegisterVar") -> None: self.used_reg_vars.add(var.reg) def is_stack_reg(self, reg: Register) -> bool: if reg == self.global_info.arch.stack_pointer_reg: return True if reg == self.global_info.arch.frame_pointer_reg: return self.uses_framepointer return False def get_struct_type_map(self) -> Dict["Expression", Dict[int, Type]]: """Reorganize struct information in unique_type_map by var & offset""" struct_type_map: Dict[Expression, Dict[int, Type]] = {} for (category, key), type in self.unique_type_map.items(): if category != "struct": continue var, offset = typing.cast(Tuple[Expression, int], key) if var not in struct_type_map: struct_type_map[var] = {} struct_type_map[var][offset] = type return struct_type_map def __str__(self) -> str: return "\n".join( [ f"Stack info for function {self.function.name}:", f"Allocated stack size: {self.allocated_stack_size}", f"Leaf? {self.is_leaf}", f"Bounds of callee-saved vars region: {self.callee_save_reg_region}", f"Callee save registers: {self.callee_save_regs}", ] ) def get_stack_info( function: Function, global_info: "GlobalInfo", flow_graph: FlowGraph, ) -> StackInfo: arch = global_info.arch info = StackInfo(function, global_info, flow_graph) # The goal here is to pick out special instructions that provide information # about this function's stack setup. # # IDO puts local variables *above* the saved registers on the stack, but # GCC puts local variables *below* the saved registers. # To support both, we explicitly determine both the upper & lower bounds of the # saved registers. Then, we estimate the boundary of the subroutine arguments # by finding the lowest stack offset that is loaded from or computed. (This # assumes that the compiler will never reuse a section of stack for *both* # a local variable *and* a subroutine argument.) Anything within the stack frame, # but outside of these two regions, is considered a local variable. callee_saved_offsets: List[int] = [] # Track simple literal values stored into registers: MIPS compilers need a temp # reg to move the stack pointer more than 0x7FFF bytes. temp_reg_values: Dict[Register, int] = {} for inst in flow_graph.entry_node().block.instructions: arch_mnemonic = inst.arch_mnemonic(arch) if inst.mnemonic in arch.instrs_fn_call: break elif arch_mnemonic == "mips:addiu" and inst.args[0] == arch.stack_pointer_reg: # Moving the stack pointer on MIPS assert isinstance(inst.args[2], AsmLiteral) info.allocated_stack_size = abs(inst.args[2].signed_value()) elif ( arch_mnemonic == "mips:subu" and inst.args[0] == arch.stack_pointer_reg and inst.args[1] == arch.stack_pointer_reg and inst.args[2] in temp_reg_values ): # Moving the stack pointer more than 0x7FFF on MIPS # TODO: This instruction needs to be ignored later in translation, in the # same way that `addiu $sp, $sp, N` is ignored in handle_addi_real assert isinstance(inst.args[2], Register) info.allocated_stack_size = temp_reg_values[inst.args[2]] elif arch_mnemonic == "ppc:stwu" and inst.args[0] == arch.stack_pointer_reg: # Moving the stack pointer on PPC assert isinstance(inst.args[1], AsmAddressMode) assert isinstance(inst.args[1].lhs, AsmLiteral) info.allocated_stack_size = abs(inst.args[1].lhs.signed_value()) elif ( arch_mnemonic == "mips:move" and inst.args[0] == arch.frame_pointer_reg and inst.args[1] == arch.stack_pointer_reg ): # "move fp, sp" very likely means the code is compiled with frame # pointers enabled; thus fp should be treated the same as sp. info.uses_framepointer = True elif ( arch_mnemonic in [ "mips:sw", "mips:swc1", "mips:sdc1", "ppc:stw", "ppc:stmw", "ppc:stfd", "ppc:psq_st", ] and isinstance(inst.args[0], Register) and inst.args[0] in arch.saved_regs and isinstance(inst.args[1], AsmAddressMode) and inst.args[1].rhs == arch.stack_pointer_reg and ( inst.args[0] not in info.callee_save_regs or arch_mnemonic == "ppc:psq_st" ) ): # Initial saving of callee-save register onto the stack. if inst.args[0] in (arch.return_address_reg, Register("r0")): # Saving the return address on the stack. info.is_leaf = False # The registers & their stack accesses must be matched up in ArchAsm.parse for reg, mem in zip(inst.inputs, inst.outputs): if isinstance(reg, Register) and isinstance(mem, StackLocation): assert mem.symbolic_offset is None stack_offset = mem.offset if arch_mnemonic != "ppc:psq_st": # psq_st instructions store the same register as stfd, just # as packed singles instead. Prioritize the stfd. info.callee_save_regs.add(reg) callee_saved_offsets.append(stack_offset) elif arch_mnemonic == "ppc:mflr" and inst.args[0] == Register("r0"): info.is_leaf = False elif arch_mnemonic == "mips:li" and inst.args[0] in arch.temp_regs: assert isinstance(inst.args[0], Register) assert isinstance(inst.args[1], AsmLiteral) temp_reg_values[inst.args[0]] = inst.args[1].value elif ( arch_mnemonic == "mips:ori" and inst.args[0] == inst.args[1] and inst.args[0] in temp_reg_values ): assert isinstance(inst.args[0], Register) assert isinstance(inst.args[2], AsmLiteral) temp_reg_values[inst.args[0]] |= inst.args[2].value if not info.is_leaf: # Iterate over the whole function, not just the first basic block, # to estimate the boundary for the subroutine argument region info.subroutine_arg_top = info.allocated_stack_size for node in flow_graph.nodes: for inst in node.block.instructions: arch_mnemonic = inst.arch_mnemonic(arch) if ( arch_mnemonic in ["mips:lw", "mips:lwc1", "mips:ldc1", "ppc:lwz"] and isinstance(inst.args[1], AsmAddressMode) and inst.args[1].rhs == arch.stack_pointer_reg and inst.args[1].lhs_as_literal() >= 16 ): info.subroutine_arg_top = min( info.subroutine_arg_top, inst.args[1].lhs_as_literal() ) elif ( arch_mnemonic == "mips:addiu" and inst.args[0] != arch.stack_pointer_reg and inst.args[1] == arch.stack_pointer_reg and isinstance(inst.args[2], AsmLiteral) and inst.args[2].value < info.allocated_stack_size ): info.subroutine_arg_top = min( info.subroutine_arg_top, inst.args[2].value ) # Compute the bounds of the callee-saved register region, including padding if callee_saved_offsets: callee_saved_offsets.sort() bottom = callee_saved_offsets[0] # Both IDO & GCC save registers in two subregions: # (a) One for double-sized registers # (b) One for word-sized registers, padded to a multiple of 8 bytes # IDO has (a) lower than (b); GCC has (b) lower than (a) # Check that there are no gaps in this region, other than a single # 4-byte word between subregions. top = bottom internal_padding_added = False for offset in callee_saved_offsets: if offset != top: if not internal_padding_added and offset == top + 4: internal_padding_added = True else: raise DecompFailure( f"Gap in callee-saved word stack region. " f"Saved: {callee_saved_offsets}, " f"gap at: {offset} != {top}." ) top = offset + 4 info.callee_save_reg_region = (bottom, top) # Subroutine arguments must be at the very bottom of the stack, so they # must come after the callee-saved region info.subroutine_arg_top = min(info.subroutine_arg_top, bottom) # Use a struct to represent the stack layout. If the struct is provided in the context, # its fields will be used for variable types & names. stack_struct_name = f"_mips2c_stack_{function.name}" stack_struct = global_info.typepool.get_struct_by_tag_name( stack_struct_name, global_info.typemap ) if stack_struct is not None: if stack_struct.size != info.allocated_stack_size: raise DecompFailure( f"Function {function.name} has a provided stack type {stack_struct_name} " f"with size {stack_struct.size}, but the detected stack size was " f"{info.allocated_stack_size}." ) else: stack_struct = StructDeclaration.unknown( global_info.typepool, size=info.allocated_stack_size, tag_name=stack_struct_name, ) # Mark the struct as a stack struct so we never try to use a reference to the struct itself stack_struct.is_stack = True stack_struct.new_field_prefix = "sp" # This acts as the type of the $sp register info.stack_pointer_type = Type.ptr(Type.struct(stack_struct)) return info def format_hex(val: int) -> str: return format(val, "x").upper() def escape_byte(b: int) -> bytes: table = { b"\0": b"\\0", b"\b": b"\\b", b"\f": b"\\f", b"\n": b"\\n", b"\r": b"\\r", b"\t": b"\\t", b"\v": b"\\v", b"\\": b"\\\\", b'"': b'\\"', } bs = bytes([b]) if bs in table: return table[bs] if b < 0x20 or b in (0xFF, 0x7F): return f"\\x{b:02x}".encode("ascii") return bs @dataclass(eq=False) class Var: stack_info: StackInfo = field(repr=False) prefix: str num_usages: int = 0 name: Optional[str] = None def format(self, fmt: Formatter) -> str: if self.name is None: self.name = self.stack_info.temp_var(self.prefix) return self.name def __str__(self) -> str: return "<temp>" class Expression(abc.ABC): type: Type @abc.abstractmethod def dependencies(self) -> List["Expression"]: ... def use(self) -> None: """Mark an expression as "will occur in the output". Various subclasses override this to provide special behavior; for instance, EvalOnceExpr checks if it occurs more than once in the output and if so emits a temp. It is important to get the number of use() calls correct: * if use() is called but the expression is not emitted, it may cause function calls to be silently dropped. * if use() is not called but the expression is emitted, it may cause phi variables to be printed as unnamed-phi($reg), without any assignment to that phi. * if use() is called once but the expression is emitted twice, it may cause function calls to be duplicated.""" for expr in self.dependencies(): expr.use() @abc.abstractmethod def format(self, fmt: Formatter) -> str: ... def __str__(self) -> str: """Stringify an expression for debug purposes. The output can change depending on when this is called, e.g. because of EvalOnceExpr state. To avoid using it by accident, output is quoted.""" fmt = Formatter(debug=True) return '"' + self.format(fmt) + '"' class Condition(Expression): @abc.abstractmethod def negated(self) -> "Condition": ... class Statement(abc.ABC): @abc.abstractmethod def should_write(self) -> bool: ... @abc.abstractmethod def format(self, fmt: Formatter) -> str: ... def __str__(self) -> str: """Stringify a statement for debug purposes. The output can change depending on when this is called, e.g. because of EvalOnceExpr state. To avoid using it by accident, output is quoted.""" fmt = Formatter(debug=True) return '"' + self.format(fmt) + '"' @dataclass(frozen=True, eq=False) class ErrorExpr(Condition): desc: Optional[str] = None type: Type = field(default_factory=Type.any_reg) def dependencies(self) -> List[Expression]: return [] def negated(self) -> "Condition": return self def format(self, fmt: Formatter) -> str: if self.desc is not None: return f"MIPS2C_ERROR({self.desc})" return "MIPS2C_ERROR()" @dataclass(frozen=True) class CommentExpr(Expression): expr: Expression type: Type = field(compare=False) prefix: Optional[str] = None suffix: Optional[str] = None def dependencies(self) -> List[Expression]: return [self.expr] def format(self, fmt: Formatter) -> str: expr_str = self.expr.format(fmt) if fmt.coding_style.comment_style == CodingStyle.CommentStyle.NONE: return expr_str prefix_str = f"/* {self.prefix} */ " if self.prefix is not None else "" suffix_str = f" /* {self.suffix} */" if self.suffix is not None else "" return f"{prefix_str}{expr_str}{suffix_str}" @staticmethod def wrap( expr: Expression, prefix: Optional[str] = None, suffix: Optional[str] = None ) -> Expression: if prefix is None and suffix is None: return expr return CommentExpr(expr=expr, type=expr.type, prefix=prefix, suffix=suffix) @dataclass(frozen=True, eq=False) class SecondF64Half(Expression): type: Type = field(default_factory=Type.any_reg) def dependencies(self) -> List[Expression]: return [] def format(self, fmt: Formatter) -> str: return "(second half of f64)" @dataclass(frozen=True, eq=False) class CarryBit(Expression): type: Type = field(default_factory=Type.intish) def dependencies(self) -> List[Expression]: return [] def format(self, fmt: Formatter) -> str: return "MIPS2C_CARRY" @staticmethod def add_to(expr: Expression) -> "BinaryOp": return fold_divmod(BinaryOp.intptr(expr, "+", CarryBit())) @staticmethod def sub_from(expr: Expression) -> "BinaryOp": return BinaryOp.intptr(expr, "-", UnaryOp("!", CarryBit(), type=Type.intish())) @dataclass(frozen=True, eq=False) class BinaryOp(Condition): left: Expression op: str right: Expression type: Type @staticmethod def int(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_intish(left), op=op, right=as_intish(right), type=Type.intish() ) @staticmethod def int64(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_int64(left), op=op, right=as_int64(right), type=Type.int64() ) @staticmethod def intptr(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_intptr(left), op=op, right=as_intptr(right), type=Type.intptr() ) @staticmethod def icmp(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_intptr(left), op=op, right=as_intptr(right), type=Type.bool() ) @staticmethod def scmp(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_sintish(left, silent=True), op=op, right=as_sintish(right, silent=True), type=Type.bool(), ) @staticmethod def sintptr_cmp(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_type(left, Type.sintptr(), False), op=op, right=as_type(right, Type.sintptr(), False), type=Type.bool(), ) @staticmethod def ucmp(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_uintish(left), op=op, right=as_uintish(right), type=Type.bool() ) @staticmethod def uintptr_cmp(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_type(left, Type.uintptr(), False), op=op, right=as_type(right, Type.uintptr(), False), type=Type.bool(), ) @staticmethod def fcmp(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_f32(left), op=op, right=as_f32(right), type=Type.bool(), ) @staticmethod def dcmp(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_f64(left), op=op, right=as_f64(right), type=Type.bool(), ) @staticmethod def sint( left: Expression, op: str, right: Expression, *, silent: bool = False ) -> "BinaryOp": return BinaryOp( left=as_sintish(left, silent=silent), op=op, right=as_sintish(right, silent=silent), type=Type.s32(), ) @staticmethod def uint(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_uintish(left), op=op, right=as_uintish(right), type=Type.u32() ) @staticmethod def s64(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp(left=as_s64(left), op=op, right=as_s64(right), type=Type.s64()) @staticmethod def u64(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp(left=as_u64(left), op=op, right=as_u64(right), type=Type.u64()) @staticmethod def f32(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_f32(left), op=op, right=as_f32(right), type=Type.f32(), ) @staticmethod def f64(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_f64(left), op=op, right=as_f64(right), type=Type.f64(), ) def is_comparison(self) -> bool: return self.op in ["==", "!=", ">", "<", ">=", "<="] def is_floating(self) -> bool: return self.left.type.is_float() and self.right.type.is_float() def negated(self) -> "Condition": if ( self.op in ["&&", "||"] and isinstance(self.left, Condition) and isinstance(self.right, Condition) ): # DeMorgan's Laws return BinaryOp( left=self.left.negated(), op={"&&": "||", "||": "&&"}[self.op], right=self.right.negated(), type=Type.bool(), ) if not self.is_comparison() or ( self.is_floating() and self.op in ["<", ">", "<=", ">="] ): # Floating-point comparisons cannot be negated in any nice way, # due to nans. return UnaryOp("!", self, type=Type.bool()) return BinaryOp( left=self.left, op={"==": "!=", "!=": "==", ">": "<=", "<": ">=", ">=": "<", "<=": ">"}[ self.op ], right=self.right, type=Type.bool(), ) def dependencies(self) -> List[Expression]: return [self.left, self.right] def format(self, fmt: Formatter) -> str: left_expr = late_unwrap(self.left) right_expr = late_unwrap(self.right) if ( self.is_comparison() and isinstance(left_expr, Literal) and not isinstance(right_expr, Literal) ): return BinaryOp( left=right_expr, op=self.op.translate(str.maketrans("<>", "><")), right=left_expr, type=self.type, ).format(fmt) if ( not self.is_floating() and isinstance(right_expr, Literal) and right_expr.value < 0 ): if self.op == "+": neg = Literal(value=-right_expr.value, type=right_expr.type) sub = BinaryOp(op="-", left=left_expr, right=neg, type=self.type) return sub.format(fmt) if self.op in ("&", "|"): neg = Literal(value=~right_expr.value, type=right_expr.type) right = UnaryOp("~", neg, type=Type.any_reg()) expr = BinaryOp(op=self.op, left=left_expr, right=right, type=self.type) return expr.format(fmt) # For commutative, left-associative operations, strip unnecessary parentheses. lhs = left_expr.format(fmt) if ( isinstance(left_expr, BinaryOp) and left_expr.op == self.op and self.op in ASSOCIATIVE_OPS ): lhs = lhs[1:-1] # For certain operators, use base-10 (decimal) for the RHS if self.op in ("/", "%") and isinstance(right_expr, Literal): rhs = right_expr.format(fmt, force_dec=True) else: rhs = right_expr.format(fmt) # These aren't real operators (or functions); format them as a fn call if self.op in PSEUDO_FUNCTION_OPS: return f"{self.op}({lhs}, {rhs})" return f"({lhs} {self.op} {rhs})" @dataclass(frozen=True, eq=False) class TernaryOp(Expression): cond: Condition left: Expression right: Expression type: Type def dependencies(self) -> List[Expression]: return [self.cond, self.left, self.right] def format(self, fmt: Formatter) -> str: cond_str = simplify_condition(self.cond).format(fmt) left_str = self.left.format(fmt) right_str = self.right.format(fmt) return f"({cond_str} ? {left_str} : {right_str})" @dataclass(frozen=True, eq=False) class UnaryOp(Condition): op: str expr: Expression type: Type def dependencies(self) -> List[Expression]: return [self.expr] @staticmethod def sint(op: str, expr: Expression) -> "UnaryOp": expr = as_sintish(expr, silent=True) return UnaryOp( op=op, expr=expr, type=expr.type, ) def negated(self) -> "Condition": if self.op == "!" and isinstance(self.expr, (UnaryOp, BinaryOp)): return self.expr return UnaryOp("!", self, type=Type.bool()) def format(self, fmt: Formatter) -> str: # These aren't real operators (or functions); format them as a fn call if self.op in PSEUDO_FUNCTION_OPS: return f"{self.op}({self.expr.format(fmt)})" return f"{self.op}{self.expr.format(fmt)}" @dataclass(frozen=True, eq=False) class ExprCondition(Condition): expr: Expression type: Type is_negated: bool = False def dependencies(self) -> List[Expression]: return [self.expr] def negated(self) -> "Condition": return ExprCondition(self.expr, self.type, not self.is_negated) def format(self, fmt: Formatter) -> str: neg = "!" if self.is_negated else "" return f"{neg}{self.expr.format(fmt)}" @dataclass(frozen=True, eq=False) class CommaConditionExpr(Condition): statements: List["Statement"] condition: "Condition" type: Type = Type.bool() def dependencies(self) -> List[Expression]: assert False, "CommaConditionExpr should not be used within translate.py" return [] def negated(self) -> "Condition": return CommaConditionExpr(self.statements, self.condition.negated()) def format(self, fmt: Formatter) -> str: comma_joined = ", ".join( stmt.format(fmt).rstrip(";") for stmt in self.statements ) return f"({comma_joined}, {self.condition.format(fmt)})" @dataclass(frozen=True, eq=False) class Cast(Expression): expr: Expression type: Type reinterpret: bool = False silent: bool = True def dependencies(self) -> List[Expression]: return [self.expr] def use(self) -> None: # Try to unify, to make stringification output better. self.expr.type.unify(self.type) super().use() def needed_for_store(self) -> bool: if not self.reinterpret: # int <-> float casts should be emitted even for stores. return True if not self.expr.type.unify(self.type): # Emit casts when types fail to unify. return True return False def is_trivial(self) -> bool: return ( self.reinterpret and self.expr.type.is_float() == self.type.is_float() and is_trivial_expression(self.expr) ) def format(self, fmt: Formatter) -> str: if self.reinterpret and self.expr.type.is_float() != self.type.is_float(): # This shouldn't happen, but mark it in the output if it does. if fmt.valid_syntax: return ( f"MIPS2C_BITWISE({self.type.format(fmt)}, {self.expr.format(fmt)})" ) return f"(bitwise {self.type.format(fmt)}) {self.expr.format(fmt)}" if self.reinterpret and ( self.silent or (is_type_obvious(self.expr) and self.expr.type.unify(self.type)) ): return self.expr.format(fmt) if fmt.skip_casts: return self.expr.format(fmt) # Function casts require special logic because function calls have # higher precedence than casts fn_sig = self.type.get_function_pointer_signature() if fn_sig: prototype_sig = self.expr.type.get_function_pointer_signature() if not prototype_sig or not prototype_sig.unify_with_args(fn_sig): # A function pointer cast is required if the inner expr is not # a function pointer, or has incompatible argument types return f"(({self.type.format(fmt)}) {self.expr.format(fmt)})" if not prototype_sig.return_type.unify(fn_sig.return_type): # Only cast the return value of the call return f"({fn_sig.return_type.format(fmt)}) {self.expr.format(fmt)}" # No cast needed return self.expr.format(fmt) return f"({self.type.format(fmt)}) {self.expr.format(fmt)}" @dataclass(frozen=True, eq=False) class FuncCall(Expression): function: Expression args: List[Expression] type: Type def dependencies(self) -> List[Expression]: return self.args + [self.function] def format(self, fmt: Formatter) -> str: # TODO: The function type may have a different number of params than it had # when the FuncCall was created. Should we warn that there may be the wrong # number of arguments at this callsite? args = ", ".join(format_expr(arg, fmt) for arg in self.args) return f"{self.function.format(fmt)}({args})" @dataclass(frozen=True, eq=True) class LocalVar(Expression): value: int type: Type = field(compare=False) path: Optional[AccessPath] = field(compare=False) def dependencies(self) -> List[Expression]: return [] def format(self, fmt: Formatter) -> str: fallback_name = f"unksp{format_hex(self.value)}" if self.path is None: return fallback_name name = StructAccess.access_path_to_field_name(self.path, fmt) if name.startswith("->"): return name[2:] return fallback_name def toplevel_decl(self, fmt: Formatter) -> Optional[str]: """Return a declaration for this LocalVar, if required.""" # If len(self.path) > 2, then this local is an inner field of another # local, so it doesn't need to be declared. if ( self.path is None or len(self.path) != 2 or not isinstance(self.path[1], str) ): return None return self.type.to_decl(self.path[1], fmt) @dataclass(frozen=True, eq=False) class RegisterVar(Expression): reg: Register name: str type: Type def dependencies(self) -> List[Expression]: return [] def format(self, fmt: Formatter) -> str: return self.name @dataclass(frozen=True, eq=True) class PassedInArg(Expression): value: int copied: bool = field(compare=False) stack_info: StackInfo = field(compare=False, repr=False) type: Type = field(compare=False) def dependencies(self) -> List[Expression]: return [] def format(self, fmt: Formatter) -> str: assert self.value % 4 == 0 name = self.stack_info.get_param_name(self.value) return name or f"arg{format_hex(self.value // 4)}" @dataclass(frozen=True, eq=True) class SubroutineArg(Expression): value: int type: Type = field(compare=False) def dependencies(self) -> List[Expression]: return [] def format(self, fmt: Formatter) -> str: return f"subroutine_arg{format_hex(self.value // 4)}" @dataclass(eq=True, unsafe_hash=True) class StructAccess(Expression): # Represents struct_var->offset. # This has eq=True since it represents a live expression and not an access # at a certain point in time -- this sometimes helps get rid of phi nodes. # prevent_later_uses makes sure it's not used after writes/function calls # that may invalidate it. struct_var: Expression offset: int target_size: Optional[int] field_path: Optional[AccessPath] = field(compare=False) stack_info: Optional[StackInfo] = field(compare=False, repr=False) type: Type = field(compare=False) checked_late_field_path: bool = field(default=False, compare=False) def __post_init__(self) -> None: # stack_info is used to resolve field_path late assert ( self.stack_info is not None or self.field_path is not None ), "Must provide at least one of (stack_info, field_path)" self.assert_valid_field_path(self.field_path) @staticmethod def assert_valid_field_path(path: Optional[AccessPath]) -> None: assert path is None or ( path and isinstance(path[0], int) ), "The first element of the field path, if present, must be an int" @classmethod def access_path_to_field_name(cls, path: AccessPath, fmt: Formatter) -> str: """ Convert an access path into a dereferencing field name, like the following examples: - `[0, "foo", 3, "bar"]` into `"->foo[3].bar"` - `[0, 3, "bar"]` into `"[0][3].bar"` - `[0, 1, 2]` into `"[0][1][2]" - `[0]` into `"[0]"` The path must have at least one element, and the first element must be an int. """ cls.assert_valid_field_path(path) output = "" # Replace an initial "[0]." with "->" if len(path) >= 2 and path[0] == 0 and isinstance(path[1], str): output += f"->{path[1]}" path = path[2:] for p in path: if isinstance(p, str): output += f".{p}" elif isinstance(p, int): output += f"[{fmt.format_int(p)}]" else: static_assert_unreachable(p) return output def dependencies(self) -> List[Expression]: return [self.struct_var] def make_reference(self) -> Optional["StructAccess"]: field_path = self.late_field_path() if field_path and len(field_path) >= 2 and field_path[-1] == 0: return replace(self, field_path=field_path[:-1]) return None def late_field_path(self) -> Optional[AccessPath]: # If we didn't have a type at the time when the struct access was # constructed, but now we do, compute field name. if self.field_path is None and not self.checked_late_field_path: var = late_unwrap(self.struct_var) # Format var to recursively resolve any late_field_path it has to # potentially improve var.type before we look up our field name var.format(Formatter()) field_path, field_type, _ = var.type.get_deref_field( self.offset, target_size=self.target_size ) if field_path is not None: self.assert_valid_field_path(field_path) self.field_path = field_path self.type.unify(field_type) self.checked_late_field_path = True return self.field_path def late_has_known_type(self) -> bool: if self.late_field_path() is not None: return True assert ( self.stack_info is not None ), "StructAccess must have stack_info if field_path isn't set" if self.offset == 0: var = late_unwrap(self.struct_var) if ( not self.stack_info.has_nonzero_access(var) and isinstance(var, AddressOf) and isinstance(var.expr, GlobalSymbol) and var.expr.type_provided ): return True return False def format(self, fmt: Formatter) -> str: var = late_unwrap(self.struct_var) has_nonzero_access = False if self.stack_info is not None: has_nonzero_access = self.stack_info.has_nonzero_access(var) field_path = self.late_field_path() if field_path is not None and field_path != [0]: has_nonzero_access = True elif fmt.valid_syntax and (self.offset != 0 or has_nonzero_access): offset_str = fmt.format_int(self.offset) return f"MIPS2C_FIELD({var.format(fmt)}, {Type.ptr(self.type).format(fmt)}, {offset_str})" else: prefix = "unk" + ("_" if fmt.coding_style.unknown_underscore else "") field_path = [0, prefix + format_hex(self.offset)] field_name = self.access_path_to_field_name(field_path, fmt) # Rewrite `(&x)->y` to `x.y` by stripping `AddressOf` & setting deref=False deref = True if ( isinstance(var, AddressOf) and not var.expr.type.is_array() and field_name.startswith("->") ): var = var.expr field_name = field_name.replace("->", ".", 1) deref = False # Rewrite `x->unk0` to `*x` and `x.unk0` to `x`, unless has_nonzero_access if self.offset == 0 and not has_nonzero_access: return f"{'*' if deref else ''}{var.format(fmt)}" return f"{parenthesize_for_struct_access(var, fmt)}{field_name}" @dataclass(frozen=True, eq=True) class ArrayAccess(Expression): # Represents ptr[index]. eq=True for symmetry with StructAccess. ptr: Expression index: Expression type: Type = field(compare=False) def dependencies(self) -> List[Expression]: return [self.ptr, self.index] def format(self, fmt: Formatter) -> str: base = parenthesize_for_struct_access(self.ptr, fmt) index = format_expr(self.index, fmt) return f"{base}[{index}]" @dataclass(eq=False) class GlobalSymbol(Expression): symbol_name: str type: Type asm_data_entry: Optional[AsmDataEntry] = None symbol_in_context: bool = False type_provided: bool = False initializer_in_typemap: bool = False demangled_str: Optional[str] = None def dependencies(self) -> List[Expression]: return [] def is_string_constant(self) -> bool: ent = self.asm_data_entry if not ent or not ent.is_string: return False return len(ent.data) == 1 and isinstance(ent.data[0], bytes) def format_string_constant(self, fmt: Formatter) -> str: assert self.is_string_constant(), "checked by caller" assert self.asm_data_entry and isinstance(self.asm_data_entry.data[0], bytes) has_trailing_null = False data = self.asm_data_entry.data[0] while data and data[-1] == 0: data = data[:-1] has_trailing_null = True data = b"".join(map(escape_byte, data)) strdata = data.decode("utf-8", "backslashreplace") ret = f'"{strdata}"' if not has_trailing_null: ret += " /* not null-terminated */" return ret def format(self, fmt: Formatter) -> str: return self.symbol_name def potential_array_dim(self, element_size: int) -> Tuple[int, int]: """ Using the size of the symbol's `asm_data_entry` and a potential array element size, return the corresponding array dimension and number of "extra" bytes left at the end of the symbol's data. If the extra bytes are nonzero, then it's likely that `element_size` is incorrect. """ # If we don't have the .data/.rodata entry for this symbol, we can't guess # its array dimension. Jump tables are ignored and not treated as arrays. if self.asm_data_entry is None or self.asm_data_entry.is_jtbl: return 0, element_size min_data_size, max_data_size = self.asm_data_entry.size_range_bytes() if element_size > max_data_size: # The type is too big for the data (not an array) return 0, max_data_size # Check if it's possible that this symbol is not an array, and is just 1 element if min_data_size <= element_size <= max_data_size and not self.type.is_array(): return 1, 0 array_dim, extra_bytes = divmod(min_data_size, element_size) if extra_bytes != 0: # If it's not possible to make an exact multiple of element_size by incorporating # bytes from the padding, then indicate that in the return value. padding_bytes = element_size - extra_bytes if min_data_size + padding_bytes > max_data_size: return array_dim, extra_bytes # Include potential padding in the array. Although this is unlikely to match the original C, # it's much easier to manually remove all or some of these elements than to add them back in. return max_data_size // element_size, 0 @dataclass(frozen=True, eq=True) class Literal(Expression): value: int type: Type = field(compare=False, default_factory=Type.any) elide_cast: bool = field(compare=False, default=False) def dependencies(self) -> List[Expression]: return [] def format(self, fmt: Formatter, force_dec: bool = False) -> str: enum_name = self.type.get_enum_name(self.value) if enum_name is not None: return enum_name if self.type.is_likely_float(): if self.type.get_size_bits() == 64: return format_f64_imm(self.value) else: return format_f32_imm(self.value) + "f" if self.type.is_pointer() and self.value == 0: return "NULL" prefix = "" suffix = "" if not fmt.skip_casts and not self.elide_cast: if self.type.is_pointer(): prefix = f"({self.type.format(fmt)})" if self.type.is_unsigned(): suffix = "U" if force_dec: value = str(self.value) else: size_bits = self.type.get_size_bits() v = self.value # The top 2 bits are tested rather than just the sign bit # to help prevent N64 VRAM pointers (0x80000000+) turning negative if ( self.type.is_signed() and size_bits and v & (1 << (size_bits - 1)) and v > (3 << (size_bits - 2)) and v < 2 ** size_bits ): v -= 1 << size_bits value = fmt.format_int(v, size_bits=size_bits) return prefix + value + suffix def likely_partial_offset(self) -> bool: return self.value % 2 ** 15 in (0, 2 ** 15 - 1) and self.value < 0x1000000 @dataclass(frozen=True, eq=True) class AddressOf(Expression): expr: Expression type: Type = field(compare=False, default_factory=Type.ptr) def dependencies(self) -> List[Expression]: return [self.expr] def format(self, fmt: Formatter) -> str: if isinstance(self.expr, GlobalSymbol): if self.expr.is_string_constant(): return self.expr.format_string_constant(fmt) if self.expr.type.is_array(): return f"{self.expr.format(fmt)}" if self.expr.type.is_function(): # Functions are automatically converted to function pointers # without an explicit `&` by the compiler return f"{self.expr.format(fmt)}" if isinstance(self.expr, StructAccess): # Simplify `&x[0]` into `x` ref = self.expr.make_reference() if ref: return f"{ref.format(fmt)}" return f"&{self.expr.format(fmt)}" @dataclass(frozen=True) class Lwl(Expression): load_expr: Expression key: Tuple[int, object] type: Type = field(compare=False, default_factory=Type.any_reg) def dependencies(self) -> List[Expression]: return [self.load_expr] def format(self, fmt: Formatter) -> str: return f"MIPS2C_LWL({self.load_expr.format(fmt)})" @dataclass(frozen=True) class Load3Bytes(Expression): load_expr: Expression type: Type = field(compare=False, default_factory=Type.any_reg) def dependencies(self) -> List[Expression]: return [self.load_expr] def format(self, fmt: Formatter) -> str: if fmt.valid_syntax: return f"MIPS2C_FIRST3BYTES({self.load_expr.format(fmt)})" return f"(first 3 bytes) {self.load_expr.format(fmt)}" @dataclass(frozen=True) class UnalignedLoad(Expression): load_expr: Expression type: Type = field(compare=False, default_factory=Type.any_reg) def dependencies(self) -> List[Expression]: return [self.load_expr] def format(self, fmt: Formatter) -> str: if fmt.valid_syntax: return f"MIPS2C_UNALIGNED32({self.load_expr.format(fmt)})" return f"(unaligned s32) {self.load_expr.format(fmt)}" @dataclass(frozen=False, eq=False) class EvalOnceExpr(Expression): wrapped_expr: Expression var: Var type: Type # True for function calls/errors emit_exactly_once: bool # Mutable state: # True if this EvalOnceExpr should be totally transparent and not emit a variable, # It may dynamically change from true to false due to forced emissions. # Initially, it is based on is_trivial_expression. trivial: bool # True if this EvalOnceExpr must emit a variable (see RegMeta.force) forced_emit: bool = False # The number of expressions that depend on this EvalOnceExpr; we emit a variable # if this is > 1. num_usages: int = 0 def dependencies(self) -> List[Expression]: # (this is a bit iffy since state can change over time, but improves uses_expr) if self.need_decl(): return [] return [self.wrapped_expr] def use(self) -> None: self.num_usages += 1 if self.trivial or (self.num_usages == 1 and not self.emit_exactly_once): self.wrapped_expr.use() def force(self) -> None: # Transition to non-trivial, and mark as used multiple times to force a var. # TODO: If it was originally trivial, we may previously have marked its # wrappee used multiple times, even though we now know that it should # have been marked just once... We could fix that by moving marking of # trivial EvalOnceExpr's to the very end. At least the consequences of # getting this wrong are pretty mild -- it just causes extraneous var # emission in rare cases. self.trivial = False self.forced_emit = True self.use() self.use() def need_decl(self) -> bool: return self.num_usages > 1 and not self.trivial def format(self, fmt: Formatter) -> str: if not self.need_decl(): return self.wrapped_expr.format(fmt) else: return self.var.format(fmt) @dataclass(frozen=False, eq=False) class PhiExpr(Expression): reg: Register node: Node type: Type used_phis: List["PhiExpr"] name: Optional[str] = None num_usages: int = 0 replacement_expr: Optional[Expression] = None used_by: Optional["PhiExpr"] = None def dependencies(self) -> List[Expression]: return [] def get_var_name(self) -> str: return self.name or f"unnamed-phi({self.reg.register_name})" def use(self, from_phi: Optional["PhiExpr"] = None) -> None: if self.num_usages == 0: self.used_phis.append(self) self.used_by = from_phi self.num_usages += 1 if self.used_by != from_phi: self.used_by = None if self.replacement_expr is not None: self.replacement_expr.use() def propagates_to(self) -> "PhiExpr": """Compute the phi that stores to this phi should propagate to. This is usually the phi itself, but if the phi is only once for the purpose of computing another phi, we forward the store there directly. This is admittedly a bit sketchy, in case the phi is in scope here and used later on... but we have that problem with regular phi assignments as well.""" if self.used_by is None or self.replacement_expr is not None: return self return self.used_by.propagates_to() def format(self, fmt: Formatter) -> str: if self.replacement_expr: return self.replacement_expr.format(fmt) return self.get_var_name() @dataclass class SwitchControl: control_expr: Expression jump_table: Optional[GlobalSymbol] = None offset: int = 0 is_irregular: bool = False def matches_guard_condition(self, cond: Condition) -> bool: """ Return True if `cond` is one of: - `((control_expr + (-offset)) >= len(jump_table))`, if `offset != 0` - `(control_expr >= len(jump_table))`, if `offset == 0` These are the appropriate bounds checks before using `jump_table`. """ cmp_expr = simplify_condition(cond) if not isinstance(cmp_expr, BinaryOp) or cmp_expr.op not in (">=", ">"): return False cmp_exclusive = cmp_expr.op == ">" # The LHS may have been wrapped in a u32 cast left_expr = late_unwrap(cmp_expr.left) if isinstance(left_expr, Cast): left_expr = late_unwrap(left_expr.expr) if self.offset != 0: if ( not isinstance(left_expr, BinaryOp) or late_unwrap(left_expr.left) != late_unwrap(self.control_expr) or left_expr.op != "+" or late_unwrap(left_expr.right) != Literal(-self.offset) ): return False elif left_expr != late_unwrap(self.control_expr): return False right_expr = late_unwrap(cmp_expr.right) if ( self.jump_table is None or self.jump_table.asm_data_entry is None or not self.jump_table.asm_data_entry.is_jtbl or not isinstance(right_expr, Literal) ): return False # Count the number of labels (exclude padding bytes) jump_table_len = sum( isinstance(e, str) for e in self.jump_table.asm_data_entry.data ) return right_expr.value + int(cmp_exclusive) == jump_table_len @staticmethod def irregular_from_expr(control_expr: Expression) -> "SwitchControl": """ Return a SwitchControl representing a "irregular" switch statement. The switch does not have a single jump table; instead it is a series of if statements & other switches. """ return SwitchControl( control_expr=control_expr, jump_table=None, offset=0, is_irregular=True, ) @staticmethod def from_expr(expr: Expression) -> "SwitchControl": """ Try to convert `expr` into a SwitchControl from one of the following forms: - `*(&jump_table + (control_expr * 4))` - `*(&jump_table + ((control_expr + (-offset)) * 4))` If `offset` is not present, it defaults to 0. If `expr` does not match, return a thin wrapper around the input expression, with `jump_table` set to `None`. """ # The "error" expression we use if we aren't able to parse `expr` error_expr = SwitchControl(expr) # Match `*(&jump_table + (control_expr * 4))` struct_expr = early_unwrap(expr) if not isinstance(struct_expr, StructAccess) or struct_expr.offset != 0: return error_expr add_expr = early_unwrap(struct_expr.struct_var) if not isinstance(add_expr, BinaryOp) or add_expr.op != "+": return error_expr # Check for either `*(&jump_table + (control_expr * 4))` and `*((control_expr * 4) + &jump_table)` left_expr, right_expr = early_unwrap(add_expr.left), early_unwrap( add_expr.right ) if isinstance(left_expr, AddressOf) and isinstance( left_expr.expr, GlobalSymbol ): jtbl_addr_expr, mul_expr = left_expr, right_expr elif isinstance(right_expr, AddressOf) and isinstance( right_expr.expr, GlobalSymbol ): mul_expr, jtbl_addr_expr = left_expr, right_expr else: return error_expr jump_table = jtbl_addr_expr.expr assert isinstance(jump_table, GlobalSymbol) if ( not isinstance(mul_expr, BinaryOp) or mul_expr.op != "*" or early_unwrap(mul_expr.right) != Literal(4) ): return error_expr control_expr = mul_expr.left # Optionally match `control_expr + (-offset)` offset = 0 uw_control_expr = early_unwrap(control_expr) if isinstance(uw_control_expr, BinaryOp) and uw_control_expr.op == "+": offset_lit = early_unwrap(uw_control_expr.right) if isinstance(offset_lit, Literal): control_expr = uw_control_expr.left offset = -offset_lit.value # Check that it is really a jump table if jump_table.asm_data_entry is None or not jump_table.asm_data_entry.is_jtbl: return error_expr return SwitchControl(control_expr, jump_table, offset) @dataclass class EvalOnceStmt(Statement): expr: EvalOnceExpr def need_decl(self) -> bool: return self.expr.need_decl() def should_write(self) -> bool: if self.expr.emit_exactly_once: return self.expr.num_usages != 1 else: return self.need_decl() def format(self, fmt: Formatter) -> str: val_str = format_expr(elide_casts_for_store(self.expr.wrapped_expr), fmt) if self.expr.emit_exactly_once and self.expr.num_usages == 0: return f"{val_str};" return f"{self.expr.var.format(fmt)} = {val_str};" @dataclass class SetPhiStmt(Statement): phi: PhiExpr expr: Expression def should_write(self) -> bool: expr = self.expr if isinstance(expr, PhiExpr) and expr.propagates_to() != expr: # When we have phi1 = phi2, and phi2 is only used in this place, # the SetPhiStmt for phi2 will store directly to phi1 and we can # skip this store. assert expr.propagates_to() == self.phi.propagates_to() return False if late_unwrap(expr) == self.phi.propagates_to(): # Elide "phi = phi". return False return True def format(self, fmt: Formatter) -> str: return format_assignment(self.phi.propagates_to(), self.expr, fmt) @dataclass class ExprStmt(Statement): expr: Expression def should_write(self) -> bool: return True def format(self, fmt: Formatter) -> str: return f"{format_expr(self.expr, fmt)};" @dataclass class StoreStmt(Statement): source: Expression dest: Expression def should_write(self) -> bool: return True def format(self, fmt: Formatter) -> str: dest = self.dest source = self.source if ( isinstance(dest, StructAccess) and dest.late_has_known_type() ) or isinstance(dest, (ArrayAccess, LocalVar, RegisterVar, SubroutineArg)): # Known destination; fine to elide some casts. source = elide_casts_for_store(source) return format_assignment(dest, source, fmt) @dataclass class CommentStmt(Statement): contents: str def should_write(self) -> bool: return True def format(self, fmt: Formatter) -> str: return f"// {self.contents}" def error_stmt(msg: str) -> ExprStmt: return ExprStmt(ErrorExpr(msg)) @dataclass(frozen=True) class AddressMode: offset: int rhs: Register def __str__(self) -> str: if self.offset: return f"{self.offset}({self.rhs})" else: return f"({self.rhs})" @dataclass(frozen=True) class RawSymbolRef: offset: int sym: AsmGlobalSymbol def __str__(self) -> str: if self.offset: return f"{self.sym.symbol_name} + {self.offset}" else: return self.sym.symbol_name @dataclass class RegMeta: # True if this regdata is unchanged from the start of the block inherited: bool = False # True if this regdata is read by some later node is_read: bool = False # True if the value derives solely from function call return values function_return: bool = False # True if the value derives solely from regdata's with is_read = True, # function_return = True, or is a passed in argument uninteresting: bool = False # True if the regdata must be replaced by variable if it is ever read force: bool = False # True if the regdata was assigned by an Instruction marked as in_pattern; # it was part of a matched IR pattern but couldn't be elided at the time in_pattern: bool = False @dataclass class RegData: value: Expression meta: RegMeta @dataclass class RegInfo: stack_info: StackInfo = field(repr=False) contents: Dict[Register, RegData] = field(default_factory=dict) read_inherited: Set[Register] = field(default_factory=set) _active_instr: Optional[Instruction] = None def __getitem__(self, key: Register) -> Expression: if self._active_instr is not None and key not in self._active_instr.inputs: lineno = self._active_instr.meta.lineno return ErrorExpr(f"Read from unset register {key} on line {lineno}") if key == Register("zero"): return Literal(0) data = self.contents.get(key) if data is None: return ErrorExpr(f"Read from unset register {key}") ret = data.value data.meta.is_read = True if data.meta.inherited: self.read_inherited.add(key) if isinstance(ret, PassedInArg) and not ret.copied: # Create a new argument object to better distinguish arguments we # are called with from arguments passed to subroutines. Also, unify # the argument's type with what we can guess from the register used. val, arg = self.stack_info.get_argument(ret.value) self.stack_info.add_argument(arg) val.type.unify(ret.type) return val if data.meta.force: assert isinstance(ret, EvalOnceExpr) ret.force() return ret def __contains__(self, key: Register) -> bool: return key in self.contents def __setitem__(self, key: Register, value: Expression) -> None: self.set_with_meta(key, value, RegMeta()) def set_with_meta(self, key: Register, value: Expression, meta: RegMeta) -> None: if self._active_instr is not None and key not in self._active_instr.outputs: raise DecompFailure(f"Undeclared write to {key} in {self._active_instr}") self.unchecked_set_with_meta(key, value, meta) def unchecked_set_with_meta( self, key: Register, value: Expression, meta: RegMeta ) -> None: assert key != Register("zero") self.contents[key] = RegData(value, meta) def __delitem__(self, key: Register) -> None: assert key != Register("zero") del self.contents[key] def get_raw(self, key: Register) -> Optional[Expression]: data = self.contents.get(key) return data.value if data is not None else None def get_meta(self, key: Register) -> Optional[RegMeta]: data = self.contents.get(key) return data.meta if data is not None else None @contextmanager def current_instr(self, instr: Instruction) -> Iterator[None]: self._active_instr = instr try: with current_instr(instr): yield finally: self._active_instr = None def __str__(self) -> str: return ", ".join( f"{k}: {v.value}" for k, v in sorted(self.contents.items(), key=lambda x: x[0].register_name) if not self.stack_info.should_save(v.value, None) ) @dataclass class BlockInfo: """ Contains translated assembly code (to_write), the block's branch condition, and block's final register states. """ to_write: List[Statement] return_value: Optional[Expression] switch_control: Optional[SwitchControl] branch_condition: Optional[Condition] final_register_states: RegInfo has_function_call: bool def __str__(self) -> str: newline = "\n\t" return "\n".join( [ f"Statements: {newline.join(str(w) for w in self.statements_to_write())}", f"Branch condition: {self.branch_condition}", f"Final register states: {self.final_register_states}", ] ) def statements_to_write(self) -> List[Statement]: return [st for st in self.to_write if st.should_write()] def get_block_info(node: Node) -> BlockInfo: ret = node.block.block_info assert isinstance(ret, BlockInfo) return ret @dataclass class InstrArgs: raw_args: List[Argument] regs: RegInfo = field(repr=False) stack_info: StackInfo = field(repr=False) def raw_arg(self, index: int) -> Argument: assert index >= 0 if index >= len(self.raw_args): raise DecompFailure( f"Too few arguments for instruction, expected at least {index + 1}" ) return self.raw_args[index] def reg_ref(self, index: int) -> Register: ret = self.raw_arg(index) if not isinstance(ret, Register): raise DecompFailure( f"Expected instruction argument to be a register, but found {ret}" ) return ret def imm_value(self, index: int) -> int: arg = self.full_imm(index) assert isinstance(arg, Literal) return arg.value def reg(self, index: int) -> Expression: return self.regs[self.reg_ref(index)] def dreg(self, index: int) -> Expression: """Extract a double from a register. This may involve reading both the mentioned register and the next.""" reg = self.reg_ref(index) if not reg.is_float(): raise DecompFailure( f"Expected instruction argument {reg} to be a float register" ) ret = self.regs[reg] # PPC: FPR's hold doubles (64 bits), so we don't need to do anything special if self.stack_info.global_info.arch.arch == Target.ArchEnum.PPC: return ret # MIPS: Look at the paired FPR to get the full 64-bit value if not isinstance(ret, Literal) or ret.type.get_size_bits() == 64: return ret reg_num = int(reg.register_name[1:]) if reg_num % 2 != 0: raise DecompFailure( "Tried to use a double-precision instruction with odd-numbered float " f"register {reg}" ) other = self.regs[Register(f"f{reg_num+1}")] if not isinstance(other, Literal) or other.type.get_size_bits() == 64: raise DecompFailure( f"Unable to determine a value for double-precision register {reg} " "whose second half is non-static. This is a mips_to_c restriction " "which may be lifted in the future." ) value = ret.value | (other.value << 32) return Literal(value, type=Type.f64()) def cmp_reg(self, key: str) -> Condition: cond = self.regs[Register(key)] if not isinstance(cond, Condition): cond = BinaryOp.icmp(cond, "!=", Literal(0)) return cond def full_imm(self, index: int) -> Expression: arg = strip_macros(self.raw_arg(index)) ret = literal_expr(arg, self.stack_info) return ret def imm(self, index: int) -> Expression: ret = self.full_imm(index) if isinstance(ret, Literal): return Literal(((ret.value + 0x8000) & 0xFFFF) - 0x8000) return ret def unsigned_imm(self, index: int) -> Expression: ret = self.full_imm(index) if isinstance(ret, Literal): return Literal(ret.value & 0xFFFF) return ret def hi_imm(self, index: int) -> Argument: arg = self.raw_arg(index) if not isinstance(arg, Macro) or arg.macro_name not in ("hi", "ha", "h"): raise DecompFailure( f"Got lui/lis instruction with macro other than %hi/@ha/@h: {arg}" ) return arg.argument def shifted_imm(self, index: int) -> Expression: # TODO: Should this be part of hi_imm? Do we need to handle @ha? raw_imm = self.unsigned_imm(index) assert isinstance(raw_imm, Literal) return Literal(raw_imm.value << 16) def memory_ref(self, index: int) -> Union[AddressMode, RawSymbolRef]: ret = strip_macros(self.raw_arg(index)) # In MIPS, we want to allow "lw $v0, symbol + 4", which is outputted by # some disassemblers (like IDA) even though it isn't valid assembly. # For PPC, we want to allow "lwz $r1, symbol@sda21($r13)" where $r13 is # assumed to point to the start of a small data area (SDA). if isinstance(ret, AsmGlobalSymbol): return RawSymbolRef(offset=0, sym=ret) if ( isinstance(ret, BinOp) and ret.op in "+-" and isinstance(ret.lhs, AsmGlobalSymbol) and isinstance(ret.rhs, AsmLiteral) ): sign = 1 if ret.op == "+" else -1 return RawSymbolRef(offset=(ret.rhs.value * sign), sym=ret.lhs) if not isinstance(ret, AsmAddressMode): raise DecompFailure( "Expected instruction argument to be of the form offset($register), " f"but found {ret}" ) if not isinstance(ret.lhs, AsmLiteral): raise DecompFailure( f"Unable to parse offset for instruction argument {ret}. " "Expected a constant or a %lo macro." ) return AddressMode(offset=ret.lhs.signed_value(), rhs=ret.rhs) def count(self) -> int: return len(self.raw_args) def deref( arg: Union[AddressMode, RawSymbolRef, Expression], regs: RegInfo, stack_info: StackInfo, *, size: int, store: bool = False, ) -> Expression: if isinstance(arg, Expression): offset = 0 var = arg elif isinstance(arg, AddressMode): offset = arg.offset if stack_info.is_stack_reg(arg.rhs): return stack_info.get_stack_var(offset, store=store) var = regs[arg.rhs] else: offset = arg.offset var = stack_info.global_info.address_of_gsym(arg.sym.symbol_name) # Struct member is being dereferenced. # Cope slightly better with raw pointers. if isinstance(var, Literal) and var.value % (2 ** 16) == 0: var = Literal(var.value + offset, type=var.type) offset = 0 # Handle large struct offsets. uw_var = early_unwrap(var) if isinstance(uw_var, BinaryOp) and uw_var.op == "+": for base, addend in [(uw_var.left, uw_var.right), (uw_var.right, uw_var.left)]: if isinstance(addend, Literal) and addend.likely_partial_offset(): offset += addend.value var = base uw_var = early_unwrap(var) break var.type.unify(Type.ptr()) stack_info.record_struct_access(var, offset) field_name: Optional[str] = None type: Type = stack_info.unique_type_for("struct", (uw_var, offset), Type.any()) # Struct access with type information. array_expr = array_access_from_add( var, offset, stack_info, target_size=size, ptr=False ) if array_expr is not None: return array_expr field_path, field_type, _ = var.type.get_deref_field(offset, target_size=size) if field_path is not None: field_type.unify(type) type = field_type else: field_path = None return StructAccess( struct_var=var, offset=offset, target_size=size, field_path=field_path, stack_info=stack_info, type=type, ) def is_trivial_expression(expr: Expression) -> bool: # Determine whether an expression should be evaluated only once or not. if isinstance( expr, ( EvalOnceExpr, Literal, GlobalSymbol, LocalVar, PassedInArg, PhiExpr, RegisterVar, SubroutineArg, ), ): return True if isinstance(expr, AddressOf): return all(is_trivial_expression(e) for e in expr.dependencies()) if isinstance(expr, Cast): return expr.is_trivial() return False def is_type_obvious(expr: Expression) -> bool: """ Determine whether an expression's type is "obvious", e.g. because the expression refers to a variable which has a declaration. With perfect type information this this function would not be needed. This function may produce wrong results while code is being generated, since at that point we don't know the final status of EvalOnceExpr's. """ if isinstance( expr, ( Cast, Literal, AddressOf, LocalVar, PhiExpr, PassedInArg, RegisterVar, FuncCall, ), ): return True if isinstance(expr, EvalOnceExpr): if expr.need_decl(): return True return is_type_obvious(expr.wrapped_expr) return False def simplify_condition(expr: Expression) -> Expression: """ Simplify a boolean expression. This function may produce wrong results while code is being generated, since at that point we don't know the final status of EvalOnceExpr's. """ if isinstance(expr, EvalOnceExpr) and not expr.need_decl(): return simplify_condition(expr.wrapped_expr) if isinstance(expr, UnaryOp): inner = simplify_condition(expr.expr) if expr.op == "!" and isinstance(inner, Condition): return inner.negated() return UnaryOp(expr=inner, op=expr.op, type=expr.type) if isinstance(expr, BinaryOp): left = simplify_condition(expr.left) right = simplify_condition(expr.right) if isinstance(left, BinaryOp) and left.is_comparison() and right == Literal(0): if expr.op == "==": return simplify_condition(left.negated()) if expr.op == "!=": return left if ( expr.is_comparison() and isinstance(left, Literal) and not isinstance(right, Literal) ): return BinaryOp( left=right, op=expr.op.translate(str.maketrans("<>", "><")), right=left, type=expr.type, ) return BinaryOp(left=left, op=expr.op, right=right, type=expr.type) return expr def balanced_parentheses(string: str) -> bool: """ Check if parentheses in a string are balanced, ignoring any non-parenthesis characters. E.g. true for "(x())yz", false for ")(" or "(". """ bal = 0 for c in string: if c == "(": bal += 1 elif c == ")": if bal == 0: return False bal -= 1 return bal == 0 def format_expr(expr: Expression, fmt: Formatter) -> str: """Stringify an expression, stripping unnecessary parentheses around it.""" ret = expr.format(fmt) if ret.startswith("(") and balanced_parentheses(ret[1:-1]): return ret[1:-1] return ret def format_assignment(dest: Expression, source: Expression, fmt: Formatter) -> str: """Stringify `dest = source;`.""" dest = late_unwrap(dest) source = late_unwrap(source) if isinstance(source, BinaryOp) and source.op in COMPOUND_ASSIGNMENT_OPS: rhs = None if late_unwrap(source.left) == dest: rhs = source.right elif late_unwrap(source.right) == dest and source.op in ASSOCIATIVE_OPS: rhs = source.left if rhs is not None: return f"{dest.format(fmt)} {source.op}= {format_expr(rhs, fmt)};" return f"{dest.format(fmt)} = {format_expr(source, fmt)};" def parenthesize_for_struct_access(expr: Expression, fmt: Formatter) -> str: # Nested dereferences may need to be parenthesized. All other # expressions will already have adequate parentheses added to them. s = expr.format(fmt) if ( s.startswith("*") or s.startswith("&") or (isinstance(expr, Cast) and expr.needed_for_store()) ): return f"({s})" return s def elide_casts_for_store(expr: Expression) -> Expression: uw_expr = late_unwrap(expr) if isinstance(uw_expr, Cast) and not uw_expr.needed_for_store(): return elide_casts_for_store(uw_expr.expr) if isinstance(uw_expr, Literal) and uw_expr.type.is_int(): # Avoid suffixes for unsigned ints return replace(uw_expr, elide_cast=True) return uw_expr def uses_expr(expr: Expression, expr_filter: Callable[[Expression], bool]) -> bool: if expr_filter(expr): return True for e in expr.dependencies(): if uses_expr(e, expr_filter): return True return False def late_unwrap(expr: Expression) -> Expression: """ Unwrap EvalOnceExpr's, stopping at variable boundaries. This function may produce wrong results while code is being generated, since at that point we don't know the final status of EvalOnceExpr's. """ if isinstance(expr, EvalOnceExpr) and not expr.need_decl(): return late_unwrap(expr.wrapped_expr) if isinstance(expr, PhiExpr) and expr.replacement_expr is not None: return late_unwrap(expr.replacement_expr) return expr def early_unwrap(expr: Expression) -> Expression: """ Unwrap EvalOnceExpr's, even past variable boundaries. This is fine to use even while code is being generated, but disrespects decisions to use a temp for a value, so use with care. """ if ( isinstance(expr, EvalOnceExpr) and not expr.forced_emit and not expr.emit_exactly_once ): return early_unwrap(expr.wrapped_expr) return expr def early_unwrap_ints(expr: Expression) -> Expression: """ Unwrap EvalOnceExpr's, even past variable boundaries or through int Cast's This is a bit sketchier than early_unwrap(), but can be used for pattern matching. """ uw_expr = early_unwrap(expr) if isinstance(uw_expr, Cast) and uw_expr.reinterpret and uw_expr.type.is_int(): return early_unwrap_ints(uw_expr.expr) return uw_expr def unwrap_deep(expr: Expression) -> Expression: """ Unwrap EvalOnceExpr's, even past variable boundaries. This is generally a sketchy thing to do, try to avoid it. In particular: - the returned expression is not usable for emission, because it may contain accesses at an earlier point in time or an expression that should not be repeated. - just because unwrap_deep(a) == unwrap_deep(b) doesn't mean a and b are interchangable, because they may be computed in different places. """ if isinstance(expr, EvalOnceExpr): return unwrap_deep(expr.wrapped_expr) return expr def literal_expr(arg: Argument, stack_info: StackInfo) -> Expression: if isinstance(arg, AsmGlobalSymbol): return stack_info.global_info.address_of_gsym(arg.symbol_name) if isinstance(arg, AsmLiteral): return Literal(arg.value) if isinstance(arg, BinOp): lhs = literal_expr(arg.lhs, stack_info) rhs = literal_expr(arg.rhs, stack_info) return BinaryOp.int(left=lhs, op=arg.op, right=rhs) raise DecompFailure(f"Instruction argument {arg} must be a literal") def imm_add_32(expr: Expression) -> Expression: if isinstance(expr, Literal): return as_intish(Literal(expr.value + 32)) else: return BinaryOp.int(expr, "+", Literal(32)) def fn_op(fn_name: str, args: List[Expression], type: Type) -> FuncCall: fn_sig = FunctionSignature( return_type=type, params=[FunctionParam(type=arg.type) for arg in args], params_known=True, is_variadic=False, ) return FuncCall( function=GlobalSymbol(symbol_name=fn_name, type=Type.function(fn_sig)), args=args, type=type, ) def void_fn_op(fn_name: str, args: List[Expression]) -> ExprStmt: fn_call = fn_op(fn_name, args, Type.any_reg()) fn_call.use() return ExprStmt(fn_call) def load_upper(args: InstrArgs) -> Expression: arg = args.raw_arg(1) if not isinstance(arg, Macro): assert not isinstance( arg, Literal ), "normalize_instruction should convert lui/lis <literal> to li" raise DecompFailure( f"lui/lis argument must be a literal or %hi/@ha macro, found {arg}" ) hi_arg = args.hi_imm(1) if ( isinstance(hi_arg, BinOp) and hi_arg.op in "+-" and isinstance(hi_arg.lhs, AsmGlobalSymbol) and isinstance(hi_arg.rhs, AsmLiteral) ): sym = hi_arg.lhs offset = hi_arg.rhs.value * (-1 if hi_arg.op == "-" else 1) elif isinstance(hi_arg, AsmGlobalSymbol): sym = hi_arg offset = 0 else: raise DecompFailure(f"Invalid %hi/@ha argument {hi_arg}") stack_info = args.stack_info source = stack_info.global_info.address_of_gsym(sym.symbol_name) imm = Literal(offset) return handle_addi_real(args.reg_ref(0), None, source, imm, stack_info) def handle_convert(expr: Expression, dest_type: Type, source_type: Type) -> Cast: # int <-> float casts should be explicit silent = dest_type.data().kind != source_type.data().kind expr.type.unify(source_type) return Cast(expr=expr, type=dest_type, silent=silent, reinterpret=False) def handle_la(args: InstrArgs) -> Expression: target = args.memory_ref(1) stack_info = args.stack_info if isinstance(target, AddressMode): return handle_addi( InstrArgs( raw_args=[args.reg_ref(0), target.rhs, AsmLiteral(target.offset)], regs=args.regs, stack_info=args.stack_info, ) ) var = stack_info.global_info.address_of_gsym(target.sym.symbol_name) return add_imm(var, Literal(target.offset), stack_info) def handle_or(left: Expression, right: Expression) -> Expression: if left == right: # `or $rD, $rS, $rS` can be used to move $rS into $rD return left if isinstance(left, Literal) and isinstance(right, Literal): if (((left.value & 0xFFFF) == 0 and (right.value & 0xFFFF0000) == 0)) or ( (right.value & 0xFFFF) == 0 and (left.value & 0xFFFF0000) == 0 ): return Literal(value=(left.value | right.value)) # Regular bitwise OR. return BinaryOp.int(left=left, op="|", right=right) def handle_sltu(args: InstrArgs) -> Expression: right = args.reg(2) if args.reg_ref(1) == Register("zero"): # (0U < x) is equivalent to (x != 0) uw_right = early_unwrap(right) if isinstance(uw_right, BinaryOp) and uw_right.op == "^": # ((a ^ b) != 0) is equivalent to (a != b) return BinaryOp.icmp(uw_right.left, "!=", uw_right.right) return BinaryOp.icmp(right, "!=", Literal(0)) else: left = args.reg(1) return BinaryOp.ucmp(left, "<", right) def handle_sltiu(args: InstrArgs) -> Expression: left = args.reg(1) right = args.imm(2) if isinstance(right, Literal): value = right.value & 0xFFFFFFFF if value == 1: # (x < 1U) is equivalent to (x == 0) uw_left = early_unwrap(left) if isinstance(uw_left, BinaryOp) and uw_left.op == "^": # ((a ^ b) == 0) is equivalent to (a == b) return BinaryOp.icmp(uw_left.left, "==", uw_left.right) return BinaryOp.icmp(left, "==", Literal(0)) else: right = Literal(value) return BinaryOp.ucmp(left, "<", right) def handle_addi(args: InstrArgs) -> Expression: stack_info = args.stack_info source_reg = args.reg_ref(1) source = args.reg(1) imm = args.imm(2) # `(x + 0xEDCC)` is emitted as `((x + 0x10000) - 0x1234)`, # i.e. as an `addis` followed by an `addi` uw_source = early_unwrap(source) if ( isinstance(uw_source, BinaryOp) and uw_source.op == "+" and isinstance(uw_source.right, Literal) and uw_source.right.value % 0x10000 == 0 and isinstance(imm, Literal) ): return add_imm( uw_source.left, Literal(imm.value + uw_source.right.value), stack_info ) return handle_addi_real(args.reg_ref(0), source_reg, source, imm, stack_info) def handle_addis(args: InstrArgs) -> Expression: stack_info = args.stack_info source_reg = args.reg_ref(1) source = args.reg(1) imm = args.shifted_imm(2) return handle_addi_real(args.reg_ref(0), source_reg, source, imm, stack_info) def handle_addi_real( output_reg: Register, source_reg: Optional[Register], source: Expression, imm: Expression, stack_info: StackInfo, ) -> Expression: if source_reg is not None and stack_info.is_stack_reg(source_reg): # Adding to sp, i.e. passing an address. assert isinstance(imm, Literal) if stack_info.is_stack_reg(output_reg): # Changing sp. Just ignore that. return source # Keep track of all local variables that we take addresses of. var = stack_info.get_stack_var(imm.value, store=False) if isinstance(var, LocalVar): stack_info.add_local_var(var) return AddressOf(var, type=var.type.reference()) else: return add_imm(source, imm, stack_info) def add_imm(source: Expression, imm: Expression, stack_info: StackInfo) -> Expression: if imm == Literal(0): # addiu $reg1, $reg2, 0 is a move # (this happens when replacing %lo(...) by 0) return source elif source.type.is_pointer_or_array(): # Pointer addition (this may miss some pointers that get detected later; # unfortunately that's hard to do anything about with mips_to_c's single-pass # architecture). if isinstance(imm, Literal) and not imm.likely_partial_offset(): array_access = array_access_from_add( source, imm.value, stack_info, target_size=None, ptr=True ) if array_access is not None: return array_access field_path, field_type, _ = source.type.get_deref_field( imm.value, target_size=None ) if field_path is not None: return AddressOf( StructAccess( struct_var=source, offset=imm.value, target_size=None, field_path=field_path, stack_info=stack_info, type=field_type, ), type=field_type.reference(), ) if isinstance(imm, Literal): target = source.type.get_pointer_target() if target: target_size = target.get_size_bytes() if target_size and imm.value % target_size == 0: # Pointer addition. return BinaryOp( left=source, op="+", right=as_intish(imm), type=source.type ) return BinaryOp(left=source, op="+", right=as_intish(imm), type=Type.ptr()) elif isinstance(source, Literal) and isinstance(imm, Literal): return Literal(source.value + imm.value) else: # Regular binary addition. return BinaryOp.intptr(left=source, op="+", right=imm) def handle_load(args: InstrArgs, type: Type) -> Expression: # For now, make the cast silent so that output doesn't become cluttered. # Though really, it would be great to expose the load types somehow... size = type.get_size_bytes() assert size is not None expr = deref(args.memory_ref(1), args.regs, args.stack_info, size=size) # Detect rodata constants if isinstance(expr, StructAccess) and expr.offset == 0: target = early_unwrap(expr.struct_var) if ( isinstance(target, AddressOf) and isinstance(target.expr, GlobalSymbol) and type.is_likely_float() ): sym_name = target.expr.symbol_name ent = args.stack_info.global_info.asm_data_value(sym_name) if ( ent and ent.data and isinstance(ent.data[0], bytes) and len(ent.data[0]) >= size and ent.is_readonly and type.unify(target.expr.type) ): data = ent.data[0][:size] val: int if size == 4: (val,) = struct.unpack(">I", data) else: (val,) = struct.unpack(">Q", data) return Literal(value=val, type=type) return as_type(expr, type, silent=True) def deref_unaligned( arg: Union[AddressMode, RawSymbolRef], regs: RegInfo, stack_info: StackInfo, *, store: bool = False, ) -> Expression: # We don't know the correct size pass to deref. Passing None would signal that we # are taking an address, cause us to prefer entire substructs as referenced fields, # which would be confusing. Instead, we lie and pass 1. Hopefully nothing bad will # happen... return deref(arg, regs, stack_info, size=1, store=store) def handle_lwl(args: InstrArgs) -> Expression: # Unaligned load for the left part of a register (lwl can technically merge with # a pre-existing lwr, but doesn't in practice, so we treat this as a standard # destination-first operation) ref = args.memory_ref(1) expr = deref_unaligned(ref, args.regs, args.stack_info) key: Tuple[int, object] if isinstance(ref, AddressMode): key = (ref.offset, args.regs[ref.rhs]) else: key = (ref.offset, ref.sym) return Lwl(expr, key) def handle_lwr(args: InstrArgs) -> Expression: # Unaligned load for the right part of a register. This lwr may merge with an # existing lwl, if it loads from the same target but with an offset that's +3. uw_old_value = early_unwrap(args.reg(0)) ref = args.memory_ref(1) lwl_key: Tuple[int, object] if isinstance(ref, AddressMode): lwl_key = (ref.offset - 3, args.regs[ref.rhs]) else: lwl_key = (ref.offset - 3, ref.sym) if isinstance(uw_old_value, Lwl) and uw_old_value.key[0] == lwl_key[0]: return UnalignedLoad(uw_old_value.load_expr) if ref.offset % 4 == 2: left_mem_ref = replace(ref, offset=ref.offset - 2) load_expr = deref_unaligned(left_mem_ref, args.regs, args.stack_info) return Load3Bytes(load_expr) return ErrorExpr("Unable to handle lwr; missing a corresponding lwl") def make_store(args: InstrArgs, type: Type) -> Optional[StoreStmt]: size = type.get_size_bytes() assert size is not None stack_info = args.stack_info source_reg = args.reg_ref(0) source_raw = args.regs.get_raw(source_reg) if type.is_likely_float() and size == 8: source_val = args.dreg(0) else: source_val = args.reg(0) target = args.memory_ref(1) is_stack = isinstance(target, AddressMode) and stack_info.is_stack_reg(target.rhs) if ( is_stack and source_raw is not None and stack_info.should_save(source_raw, target.offset) ): # Elide register preserval. return None dest = deref(target, args.regs, stack_info, size=size, store=True) dest.type.unify(type) return StoreStmt(source=as_type(source_val, type, silent=is_stack), dest=dest) def make_storex(args: InstrArgs, type: Type) -> Optional[StoreStmt]: # "indexed stores" like `stwx rS, rA, rB` write `rS` into `(rA + rB)` size = type.get_size_bytes() assert size is not None source = args.reg(0) ptr = BinaryOp.intptr(left=args.reg(1), op="+", right=args.reg(2)) # TODO: Can we assume storex's are never used to save registers to the stack? dest = deref(ptr, args.regs, args.stack_info, size=size, store=True) dest.type.unify(type) return StoreStmt(source=as_type(source, type, silent=False), dest=dest) def handle_swl(args: InstrArgs) -> Optional[StoreStmt]: # swl in practice only occurs together with swr, so we can treat it as a regular # store, with the expression wrapped in UnalignedLoad if needed. source = args.reg(0) target = args.memory_ref(1) if not isinstance(early_unwrap(source), UnalignedLoad): source = UnalignedLoad(source) dest = deref_unaligned(target, args.regs, args.stack_info, store=True) return StoreStmt(source=source, dest=dest) def handle_swr(args: InstrArgs) -> Optional[StoreStmt]: expr = early_unwrap(args.reg(0)) target = args.memory_ref(1) if not isinstance(expr, Load3Bytes): # Elide swr's that don't come from 3-byte-loading lwr's; they probably # come with a corresponding swl which has already been emitted. return None real_target = replace(target, offset=target.offset - 2) dest = deref_unaligned(real_target, args.regs, args.stack_info, store=True) return StoreStmt(source=expr, dest=dest) def handle_sra(args: InstrArgs) -> Expression: lhs = args.reg(1) shift = args.imm(2) if isinstance(shift, Literal) and shift.value in [16, 24]: expr = early_unwrap(lhs) pow2 = 1 << shift.value if isinstance(expr, BinaryOp) and isinstance(expr.right, Literal): tp = Type.s16() if shift.value == 16 else Type.s8() rhs = expr.right.value if expr.op == "<<" and rhs == shift.value: return as_type(expr.left, tp, silent=False) elif expr.op == "<<" and rhs > shift.value: new_shift = fold_mul_chains( BinaryOp.int(expr.left, "<<", Literal(rhs - shift.value)) ) return as_type(new_shift, tp, silent=False) elif expr.op == "*" and rhs % pow2 == 0 and rhs != pow2: mul = BinaryOp.int(expr.left, "*", Literal(value=rhs // pow2)) return as_type(mul, tp, silent=False) return fold_divmod( BinaryOp(as_sintish(lhs), ">>", as_intish(shift), type=Type.s32()) ) def handle_conditional_move(args: InstrArgs, nonzero: bool) -> Expression: op = "!=" if nonzero else "==" type = Type.any_reg() return TernaryOp( BinaryOp.scmp(args.reg(2), op, Literal(0)), as_type(args.reg(1), type, silent=True), as_type(args.reg(0), type, silent=True), type, ) def format_f32_imm(num: int) -> str: packed = struct.pack(">I", num & (2 ** 32 - 1)) value = struct.unpack(">f", packed)[0] if not value or value == 4294967296.0: # Zero, negative zero, nan, or INT_MAX. return str(value) # Write values smaller than 1e-7 / greater than 1e7 using scientific notation, # and values in between using fixed point. if abs(math.log10(abs(value))) > 6.9: fmt_char = "e" elif abs(value) < 1: fmt_char = "f" else: fmt_char = "g" def fmt(prec: int) -> str: """Format 'value' with 'prec' significant digits/decimals, in either scientific or regular notation depending on 'fmt_char'.""" ret = ("{:." + str(prec) + fmt_char + "}").format(value) if fmt_char == "e": return ret.replace("e+", "e").replace("e0", "e").replace("e-0", "e-") if "e" in ret: # The "g" format character can sometimes introduce scientific notation if # formatting with too few decimals. If this happens, return an incorrect # value to prevent the result from being used. # # Since the value we are formatting is within (1e-7, 1e7) in absolute # value, it will at least be possible to format with 7 decimals, which is # less than float precision. Thus, this annoying Python limitation won't # lead to us outputting numbers with more precision than we really have. return "0" return ret # 20 decimals is more than enough for a float. Start there, then try to shrink it. prec = 20 while prec > 0: prec -= 1 value2 = float(fmt(prec)) if struct.pack(">f", value2) != packed: prec += 1 break if prec == 20: # Uh oh, even the original value didn't format correctly. Fall back to str(), # which ought to work. return str(value) ret = fmt(prec) if "." not in ret: ret += ".0" return ret def format_f64_imm(num: int) -> str: (value,) = struct.unpack(">d", struct.pack(">Q", num & (2 ** 64 - 1))) return str(value) def fold_divmod(original_expr: BinaryOp) -> BinaryOp: """ Return a new BinaryOp instance if this one can be simplified to a single / or % op. This involves simplifying expressions using MULT_HI, MULTU_HI, +, -, <<, >>, and /. In GCC 2.7.2, the code that generates these instructions is in expmed.c. See also https://ridiculousfish.com/blog/posts/labor-of-division-episode-i.html for a modern writeup of a similar algorithm. This optimization is also used by MWCC and modern compilers (but not IDO). """ mult_high_ops = ("MULT_HI", "MULTU_HI") possible_match_ops = mult_high_ops + ("-", "+", ">>") # Only operate on integer expressions of certain operations if original_expr.is_floating() or original_expr.op not in possible_match_ops: return original_expr # Use `early_unwrap_ints` instead of `early_unwrap` to ignore Casts to integer types # Although this discards some extra type information, this function largely ignores # sign/size information to stay simpler. The result will be made with BinaryOp.int() # regardless of input types. expr = original_expr left_expr = early_unwrap_ints(expr.left) right_expr = early_unwrap_ints(expr.right) divisor_shift = 0 # Detect signed power-of-two division: (x >> N) + MIPS2C_CARRY --> x / (1 << N) if ( isinstance(left_expr, BinaryOp) and left_expr.op == ">>" and isinstance(left_expr.right, Literal) and expr.op == "+" and isinstance(right_expr, CarryBit) ): new_denom = 1 << left_expr.right.value return BinaryOp.sint( left=left_expr.left, op="/", right=Literal(new_denom), silent=True, ) # Fold `/` with `>>`: ((x / N) >> M) --> x / (N << M) # NB: If x is signed, this is only correct if there is a sign-correcting subtraction term if ( isinstance(left_expr, BinaryOp) and left_expr.op == "/" and isinstance(left_expr.right, Literal) and expr.op == ">>" and isinstance(right_expr, Literal) ): new_denom = left_expr.right.value << right_expr.value if new_denom < (1 << 32): return BinaryOp.int( left=left_expr.left, op="/", right=Literal(new_denom), ) # Detect `%`: (x - ((x / y) * y)) --> x % y if expr.op == "-" and isinstance(right_expr, BinaryOp) and right_expr.op == "*": div_expr = early_unwrap_ints(right_expr.left) mod_base = early_unwrap_ints(right_expr.right) if ( isinstance(div_expr, BinaryOp) and early_unwrap_ints(div_expr.left) == left_expr ): # Accept either `(x / y) * y` or `(x >> N) * M` (where `1 << N == M`) divisor = early_unwrap_ints(div_expr.right) if (div_expr.op == "/" and divisor == mod_base) or ( div_expr.op == ">>" and isinstance(divisor, Literal) and isinstance(mod_base, Literal) and (1 << divisor.value) == mod_base.value ): return BinaryOp.int(left=left_expr, op="%", right=right_expr.right) # Detect dividing by a negative: ((x >> 31) - (x / N)) --> x / -N if ( expr.op == "-" and isinstance(left_expr, BinaryOp) and left_expr.op == ">>" and early_unwrap_ints(left_expr.right) == Literal(31) and isinstance(right_expr, BinaryOp) and right_expr.op == "/" and isinstance(right_expr.right, Literal) ): # Swap left_expr & right_expr, but replace the N in right_expr with -N left_expr, right_expr = ( replace(right_expr, right=Literal(-right_expr.right.value)), left_expr, ) # Remove outer error term: ((x / N) + ((x / N) >> 31)) --> x / N # As N gets close to (1 << 30), this is no longer a negligible error term if ( expr.op == "+" and isinstance(left_expr, BinaryOp) and left_expr.op == "/" and isinstance(left_expr.right, Literal) and left_expr.right.value <= (1 << 29) and isinstance(right_expr, BinaryOp) and early_unwrap_ints(right_expr.left) == left_expr and right_expr.op == ">>" and early_unwrap_ints(right_expr.right) == Literal(31) ): return left_expr # Remove outer error term: ((x / N) - (x >> 31)) --> x / N if ( expr.op == "-" and isinstance(left_expr, BinaryOp) and left_expr.op == "/" and isinstance(left_expr.right, Literal) and isinstance(right_expr, BinaryOp) and right_expr.op == ">>" and early_unwrap_ints(right_expr.right) == Literal(31) ): div_expr = left_expr shift_var_expr = early_unwrap_ints(right_expr.left) div_var_expr = early_unwrap_ints(div_expr.left) # Check if the LHS of the shift is the same var that we're dividing by if div_var_expr == shift_var_expr: if isinstance(div_expr.right, Literal) and div_expr.right.value >= ( 1 << 30 ): return BinaryOp.int( left=div_expr.left, op=div_expr.op, right=div_expr.right, ) return div_expr # If the var is under 32 bits, the error term may look like `(x << K) >> 31` instead if ( isinstance(shift_var_expr, BinaryOp) and early_unwrap_ints(div_expr.left) == early_unwrap_ints(shift_var_expr.left) and shift_var_expr.op == "<<" and isinstance(shift_var_expr.right, Literal) ): return div_expr # Shift on the result of the mul: MULT_HI(x, N) >> M, shift the divisor by M if ( isinstance(left_expr, BinaryOp) and expr.op == ">>" and isinstance(right_expr, Literal) ): divisor_shift += right_expr.value expr = left_expr left_expr = early_unwrap_ints(expr.left) right_expr = early_unwrap_ints(expr.right) # Normalize MULT_HI(N, x) to MULT_HI(x, N) if isinstance(left_expr, Literal) and not isinstance(right_expr, Literal): left_expr, right_expr = right_expr, left_expr # Remove inner addition: (MULT_HI(x, N) + x) >> M --> MULT_HI(x, N) >> M # MULT_HI performs signed multiplication, so the `+ x` acts as setting the 32nd bit # while having a result with the same sign as x. # We can ignore it because `round_div` can work with arbitrarily large constants if ( isinstance(left_expr, BinaryOp) and left_expr.op == "MULT_HI" and expr.op == "+" and early_unwrap_ints(left_expr.left) == right_expr ): expr = left_expr left_expr = early_unwrap_ints(expr.left) right_expr = early_unwrap_ints(expr.right) # Shift on the LHS of the mul: MULT_HI(x >> M, N) --> MULT_HI(x, N) >> M if ( expr.op in mult_high_ops and isinstance(left_expr, BinaryOp) and left_expr.op == ">>" and isinstance(left_expr.right, Literal) ): divisor_shift += left_expr.right.value left_expr = early_unwrap_ints(left_expr.left) # Instead of checking for the error term precisely, just check that # the quotient is "close enough" to the integer value def round_div(x: int, y: int) -> Optional[int]: if y <= 1: return None result = round(x / y) if x / (y + 1) <= result <= x / (y - 1): return result return None if expr.op in mult_high_ops and isinstance(right_expr, Literal): denom = round_div(1 << (32 + divisor_shift), right_expr.value) if denom is not None: return BinaryOp.int( left=left_expr, op="/", right=Literal(denom), ) return original_expr def replace_clz_shift(expr: BinaryOp) -> BinaryOp: """ Simplify an expression matching `CLZ(x) >> 5` into `x == 0`, and further simplify `(a - b) == 0` into `a == b`. """ # Check that the outer expression is `>>` if expr.is_floating() or expr.op != ">>": return expr # Match `CLZ(x) >> 5`, or return the original expr left_expr = early_unwrap_ints(expr.left) right_expr = early_unwrap_ints(expr.right) if not ( isinstance(left_expr, UnaryOp) and left_expr.op == "CLZ" and isinstance(right_expr, Literal) and right_expr.value == 5 ): return expr # If the inner `x` is `(a - b)`, return `a == b` sub_expr = early_unwrap(left_expr.expr) if ( isinstance(sub_expr, BinaryOp) and not sub_expr.is_floating() and sub_expr.op == "-" ): return BinaryOp.icmp(sub_expr.left, "==", sub_expr.right) return BinaryOp.icmp(left_expr.expr, "==", Literal(0, type=left_expr.expr.type)) def replace_bitand(expr: BinaryOp) -> Expression: """Detect expressions using `&` for truncating integer casts""" if not expr.is_floating() and expr.op == "&": if expr.right == Literal(0xFF): return as_type(expr.left, Type.int_of_size(8), silent=False) if expr.right == Literal(0xFFFF): return as_type(expr.left, Type.int_of_size(16), silent=False) return expr def fold_mul_chains(expr: Expression) -> Expression: """Simplify an expression involving +, -, * and << to a single multiplication, e.g. 4*x - x -> 3*x, or x<<2 -> x*4. This includes some logic for preventing folds of consecutive sll, and keeping multiplications by large powers of two as bitshifts at the top layer.""" def fold( expr: Expression, toplevel: bool, allow_sll: bool ) -> Tuple[Expression, int]: if isinstance(expr, BinaryOp): lbase, lnum = fold(expr.left, False, (expr.op != "<<")) rbase, rnum = fold(expr.right, False, (expr.op != "<<")) if expr.op == "<<" and isinstance(expr.right, Literal) and allow_sll: # Left-shifts by small numbers are easier to understand if # written as multiplications (they compile to the same thing). if toplevel and lnum == 1 and not (1 <= expr.right.value <= 4): return (expr, 1) return (lbase, lnum << expr.right.value) if ( expr.op == "*" and isinstance(expr.right, Literal) and (allow_sll or expr.right.value % 2 != 0) ): return (lbase, lnum * expr.right.value) if early_unwrap(lbase) == early_unwrap(rbase): if expr.op == "+": return (lbase, lnum + rnum) if expr.op == "-": return (lbase, lnum - rnum) if isinstance(expr, UnaryOp) and expr.op == "-" and not toplevel: base, num = fold(expr.expr, False, True) return (base, -num) if ( isinstance(expr, EvalOnceExpr) and not expr.emit_exactly_once and not expr.forced_emit ): base, num = fold(early_unwrap(expr), False, allow_sll) if num != 1 and is_trivial_expression(base): return (base, num) return (expr, 1) base, num = fold(expr, True, True) if num == 1: return expr return BinaryOp.int(left=base, op="*", right=Literal(num)) def array_access_from_add( expr: Expression, offset: int, stack_info: StackInfo, *, target_size: Optional[int], ptr: bool, ) -> Optional[Expression]: expr = early_unwrap(expr) if not isinstance(expr, BinaryOp) or expr.op != "+": return None base = expr.left addend = expr.right if addend.type.is_pointer_or_array() and not base.type.is_pointer_or_array(): base, addend = addend, base index: Expression scale: int uw_addend = early_unwrap(addend) if ( isinstance(uw_addend, BinaryOp) and uw_addend.op == "*" and isinstance(uw_addend.right, Literal) ): index = uw_addend.left scale = uw_addend.right.value elif ( isinstance(uw_addend, BinaryOp) and uw_addend.op == "<<" and isinstance(uw_addend.right, Literal) ): index = uw_addend.left scale = 1 << uw_addend.right.value else: index = addend scale = 1 if scale < 0: scale = -scale index = UnaryOp.sint("-", index) target_type = base.type.get_pointer_target() if target_type is None: return None uw_base = early_unwrap(base) typepool = stack_info.global_info.typepool # In `&x + index * scale`, if the type of `x` is not known, try to mark it as an array. # Skip the `scale = 1` case because this often indicates a complex `index` expression, # and is not actually a 1-byte array lookup. if ( scale > 1 and offset == 0 and isinstance(uw_base, AddressOf) and target_type.get_size_bytes() is None ): inner_type: Optional[Type] = None if ( isinstance(uw_base.expr, GlobalSymbol) and uw_base.expr.potential_array_dim(scale)[1] != 0 ): # For GlobalSymbols, use the size of the asm data to check the feasibility of being # an array with `scale`. This helps be more conservative around fake symbols. pass elif scale == 2: # This *could* be a struct, but is much more likely to be an int inner_type = Type.int_of_size(16) elif scale == 4: inner_type = Type.reg32(likely_float=False) elif typepool.unk_inference and isinstance(uw_base.expr, GlobalSymbol): # Make up a struct with a tag name based on the symbol & struct size. # Although `scale = 8` could indicate an array of longs/doubles, it seems more # common to be an array of structs. struct_name = f"_struct_{uw_base.expr.symbol_name}_0x{scale:X}" struct = typepool.get_struct_by_tag_name( struct_name, stack_info.global_info.typemap ) if struct is None: struct = StructDeclaration.unknown( typepool, size=scale, tag_name=struct_name ) elif struct.size != scale: # This should only happen if there was already a struct with this name in the context raise DecompFailure(f"sizeof(struct {struct_name}) != {scale:#x}") inner_type = Type.struct(struct) if inner_type is not None: # This might fail, if `uw_base.expr.type` can't be changed to an array uw_base.expr.type.unify(Type.array(inner_type, dim=None)) # This acts as a backup, and will usually succeed target_type.unify(inner_type) if target_type.get_size_bytes() == scale: # base[index] pass else: # base->subarray[index] sub_path, sub_type, remaining_offset = base.type.get_deref_field( offset, target_size=scale, exact=False ) # Check if the last item in the path is `0`, which indicates the start of an array # If it is, remove it: it will be replaced by `[index]` if sub_path is None or len(sub_path) < 2 or sub_path[-1] != 0: return None sub_path.pop() base = StructAccess( struct_var=base, offset=offset - remaining_offset, target_size=None, field_path=sub_path, stack_info=stack_info, type=sub_type, ) offset = remaining_offset target_type = sub_type ret: Expression = ArrayAccess(base, index, type=target_type) # Add .field if necessary by wrapping ret in StructAccess(AddressOf(...)) ret_ref = AddressOf(ret, type=ret.type.reference()) field_path, field_type, _ = ret_ref.type.get_deref_field( offset, target_size=target_size ) if offset != 0 or (target_size is not None and target_size != scale): ret = StructAccess( struct_var=ret_ref, offset=offset, target_size=target_size, field_path=field_path, stack_info=stack_info, type=field_type, ) if ptr: ret = AddressOf(ret, type=ret.type.reference()) return ret def handle_add(args: InstrArgs) -> Expression: lhs = args.reg(1) rhs = args.reg(2) stack_info = args.stack_info type = Type.intptr() # Because lhs & rhs are in registers, it shouldn't be possible for them to be arrays. # If they are, treat them the same as pointers anyways. if lhs.type.is_pointer_or_array(): type = Type.ptr() elif rhs.type.is_pointer_or_array(): type = Type.ptr() # addiu instructions can sometimes be emitted as addu instead, when the # offset is too large. if isinstance(rhs, Literal): return handle_addi_real(args.reg_ref(0), args.reg_ref(1), lhs, rhs, stack_info) if isinstance(lhs, Literal): return handle_addi_real(args.reg_ref(0), args.reg_ref(2), rhs, lhs, stack_info) expr = BinaryOp(left=as_intptr(lhs), op="+", right=as_intptr(rhs), type=type) folded_expr = fold_mul_chains(expr) if isinstance(folded_expr, BinaryOp): folded_expr = fold_divmod(folded_expr) if folded_expr is not expr: return folded_expr array_expr = array_access_from_add(expr, 0, stack_info, target_size=None, ptr=True) if array_expr is not None: return array_expr return expr def handle_add_float(args: InstrArgs) -> Expression: if args.reg_ref(1) == args.reg_ref(2): two = Literal(1 << 30, type=Type.f32()) return BinaryOp.f32(two, "*", args.reg(1)) return BinaryOp.f32(args.reg(1), "+", args.reg(2)) def handle_add_double(args: InstrArgs) -> Expression: if args.reg_ref(1) == args.reg_ref(2): two = Literal(1 << 62, type=Type.f64()) return BinaryOp.f64(two, "*", args.dreg(1)) return BinaryOp.f64(args.dreg(1), "+", args.dreg(2)) def handle_bgez(args: InstrArgs) -> Condition: expr = args.reg(0) uw_expr = early_unwrap(expr) if ( isinstance(uw_expr, BinaryOp) and uw_expr.op == "<<" and isinstance(uw_expr.right, Literal) ): shift = uw_expr.right.value bitand = BinaryOp.int(uw_expr.left, "&", Literal(1 << (31 - shift))) return UnaryOp("!", bitand, type=Type.bool()) return BinaryOp.scmp(expr, ">=", Literal(0)) def rlwi_mask(mask_begin: int, mask_end: int) -> int: # Compute the mask constant used by the rlwi* family of PPC instructions, # referred to as the `MASK(MB, ME)` function in the processor manual. # Bit 0 is the MSB, Bit 31 is the LSB bits_upto: Callable[[int], int] = lambda m: (1 << (32 - m)) - 1 all_ones = 0xFFFFFFFF if mask_begin <= mask_end: # Set bits inside the range, fully inclusive mask = bits_upto(mask_begin) - bits_upto(mask_end + 1) else: # Set bits from [31, mask_end] and [mask_begin, 0] mask = (bits_upto(mask_end + 1) - bits_upto(mask_begin)) ^ all_ones return mask def handle_rlwinm( source: Expression, shift: int, mask_begin: int, mask_end: int, simplify: bool = True, ) -> Expression: # TODO: Detect shift + truncate, like `(x << 2) & 0xFFF3` or `(x >> 2) & 0x3FFF` # The output of the rlwinm instruction is `ROTL(source, shift) & mask`. We write this as # ((source << shift) & mask) | ((source >> (32 - shift)) & mask) # and compute both OR operands (upper_bits and lower_bits respectively). all_ones = 0xFFFFFFFF mask = rlwi_mask(mask_begin, mask_end) left_shift = shift right_shift = 32 - shift left_mask = (all_ones << left_shift) & mask right_mask = (all_ones >> right_shift) & mask # We only simplify if the `simplify` argument is True, and there will be no `|` in the # resulting expression. If there is an `|`, the expression is best left as bitwise math simplify = simplify and not (left_mask and right_mask) if isinstance(source, Literal): upper_value = (source.value << left_shift) & mask lower_value = (source.value >> right_shift) & mask return Literal(upper_value | lower_value) upper_bits: Optional[Expression] if left_mask == 0: upper_bits = None else: upper_bits = source if left_shift != 0: upper_bits = BinaryOp.int( left=upper_bits, op="<<", right=Literal(left_shift) ) if simplify: upper_bits = fold_mul_chains(upper_bits) if left_mask != (all_ones << left_shift) & all_ones: upper_bits = BinaryOp.int(left=upper_bits, op="&", right=Literal(left_mask)) if simplify: upper_bits = replace_bitand(upper_bits) lower_bits: Optional[Expression] if right_mask == 0: lower_bits = None else: lower_bits = BinaryOp.uint(left=source, op=">>", right=Literal(right_shift)) if simplify: lower_bits = replace_clz_shift(fold_divmod(lower_bits)) if right_mask != (all_ones >> right_shift) & all_ones: lower_bits = BinaryOp.int( left=lower_bits, op="&", right=Literal(right_mask) ) if simplify: lower_bits = replace_bitand(lower_bits) if upper_bits is None and lower_bits is None: return Literal(0) elif upper_bits is None: assert lower_bits is not None return lower_bits elif lower_bits is None: return upper_bits else: return BinaryOp.int(left=upper_bits, op="|", right=lower_bits) def handle_rlwimi( base: Expression, source: Expression, shift: int, mask_begin: int, mask_end: int ) -> Expression: # This instruction reads from `base`, replaces some bits with values from `source`, then # writes the result back into the first register. This can be used to copy any contiguous # bitfield from `source` into `base`, and is commonly used when manipulating flags, such # as in `x |= 0x10` or `x &= ~0x10`. # It's generally more readable to write the mask with `~` (instead of computing the inverse here) mask_literal = Literal(rlwi_mask(mask_begin, mask_end)) mask = UnaryOp("~", mask_literal, type=Type.u32()) masked_base = BinaryOp.int(left=base, op="&", right=mask) if source == Literal(0): # If the source is 0, there are no bits inserted. (This may look like `x &= ~0x10`) return masked_base # Set `simplify=False` to keep the `inserted` expression as bitwise math instead of `*` or `/` inserted = handle_rlwinm(source, shift, mask_begin, mask_end, simplify=False) if inserted == mask_literal: # If this instruction will set all the bits in the mask, we can OR the values # together without masking the base. (`x |= 0xF0` instead of `x = (x & ~0xF0) | 0xF0`) return BinaryOp.int(left=base, op="|", right=inserted) return BinaryOp.int(left=masked_base, op="|", right=inserted) def handle_loadx(args: InstrArgs, type: Type) -> Expression: # "indexed loads" like `lwzx rD, rA, rB` read `(rA + rB)` into `rD` size = type.get_size_bytes() assert size is not None ptr = BinaryOp.intptr(left=args.reg(1), op="+", right=args.reg(2)) expr = deref(ptr, args.regs, args.stack_info, size=size) return as_type(expr, type, silent=True) def strip_macros(arg: Argument) -> Argument: """Replace %lo(...) by 0, and assert that there are no %hi(...). We assume that %hi's only ever occur in lui, where we expand them to an entire value, and not just the upper part. This preserves semantics in most cases (though not when %hi's are reused for different %lo's...)""" if isinstance(arg, Macro): if arg.macro_name in ["sda2", "sda21"]: return arg.argument if arg.macro_name == "hi": raise DecompFailure("%hi macro outside of lui") if arg.macro_name not in ["lo", "l"]: raise DecompFailure(f"Unrecognized linker macro %{arg.macro_name}") # This is sort of weird; for `symbol@l` we return 0 here and assume # that this @l is always perfectly paired with one other @ha. # However, with `literal@l`, we return the literal value, and assume it is # paired with another `literal@ha`. This lets us reuse `literal@ha` values, # but assumes that we never mix literals & symbols if isinstance(arg.argument, AsmLiteral): return AsmLiteral(arg.argument.value) return AsmLiteral(0) elif isinstance(arg, AsmAddressMode) and isinstance(arg.lhs, Macro): if arg.lhs.macro_name in ["sda2", "sda21"]: return arg.lhs.argument if arg.lhs.macro_name not in ["lo", "l"]: raise DecompFailure( f"Bad linker macro in instruction argument {arg}, expected %lo" ) return AsmAddressMode(lhs=AsmLiteral(0), rhs=arg.rhs) else: return arg @dataclass class AbiArgSlot: offset: int reg: Optional[Register] type: Type name: Optional[str] = None comment: Optional[str] = None @dataclass class Abi: arg_slots: List[AbiArgSlot] possible_slots: List[AbiArgSlot] def reg_always_set(node: Node, reg: Register, *, dom_set: bool) -> bool: if node.immediate_dominator is None: return False seen = {node.immediate_dominator} stack = node.parents[:] while stack: n = stack.pop() if n == node.immediate_dominator and not dom_set: return False if n in seen: continue seen.add(n) clobbered: Optional[bool] = None for instr in n.block.instructions: with current_instr(instr): if reg in instr.outputs: clobbered = False elif reg in instr.clobbers: clobbered = True if clobbered == True: return False if clobbered is None: stack.extend(n.parents) return True def pick_phi_assignment_nodes( reg: Register, nodes: List[Node], expr: Expression ) -> List[Node]: """ As part of `assign_phis()`, we need to pick a set of nodes where we can emit a `SetPhiStmt` that assigns the phi for `reg` to `expr`. The final register state for `reg` for each node in `nodes` is `expr`, so the best case would be finding a single dominating node for the assignment. """ # Find the set of nodes which dominate *all* of `nodes`, sorted by number # of dominators. (This puts "earlier" nodes at the beginning of the list.) dominators = sorted( set.intersection(*(node.dominators for node in nodes)), key=lambda n: len(n.dominators), ) # Check the dominators for a node with the correct final state for `reg` for node in dominators: regs = get_block_info(node).final_register_states raw = regs.get_raw(reg) meta = regs.get_meta(reg) if raw is None or meta is None or meta.force: continue if raw == expr: return [node] # We couldn't find anything, so fall back to the naive solution # TODO: In some cases there may be a better solution (e.g. one that requires 2 nodes) return nodes def assign_phis(used_phis: List[PhiExpr], stack_info: StackInfo) -> None: i = 0 # Iterate over used phis until there are no more remaining. New ones may # appear during iteration, hence the while loop. while i < len(used_phis): phi = used_phis[i] assert phi.num_usages > 0 assert len(phi.node.parents) >= 2 # Group parent nodes by the value of their phi register equivalent_nodes: DefaultDict[Expression, List[Node]] = defaultdict(list) for node in phi.node.parents: expr = get_block_info(node).final_register_states[phi.reg] expr.type.unify(phi.type) equivalent_nodes[expr].append(node) exprs = list(equivalent_nodes.keys()) first_uw = early_unwrap(exprs[0]) if all(early_unwrap(e) == first_uw for e in exprs[1:]): # All the phis have the same value (e.g. because we recomputed an # expression after a store, or restored a register after a function # call). Just use that value instead of introducing a phi node. # TODO: the unwrapping here is necessary, but also kinda sketchy: # we may set as replacement_expr an expression that really shouldn't # be repeated, e.g. a StructAccess. It would make sense to use less # eager unwrapping, and/or to emit an EvalOnceExpr at this point # (though it's too late for it to be able to participate in the # prevent_later_uses machinery). phi.replacement_expr = as_type(first_uw, phi.type, silent=True) for _ in range(phi.num_usages): first_uw.use() else: for expr, nodes in equivalent_nodes.items(): for node in pick_phi_assignment_nodes(phi.reg, nodes, expr): block_info = get_block_info(node) expr = block_info.final_register_states[phi.reg] if isinstance(expr, PhiExpr): # Explicitly mark how the expression is used if it's a phi, # so we can propagate phi sets (to get rid of temporaries). expr.use(from_phi=phi) else: expr.use() typed_expr = as_type(expr, phi.type, silent=True) block_info.to_write.append(SetPhiStmt(phi, typed_expr)) i += 1 name_counter: Dict[Register, int] = {} for phi in used_phis: if not phi.replacement_expr and phi.propagates_to() == phi: counter = name_counter.get(phi.reg, 0) + 1 name_counter[phi.reg] = counter output_reg_name = stack_info.function.reg_formatter.format(phi.reg) prefix = f"phi_{output_reg_name}" phi.name = f"{prefix}_{counter}" if counter > 1 else prefix stack_info.phi_vars.append(phi) def propagate_register_meta(nodes: List[Node], reg: Register) -> None: """Propagate RegMeta bits forwards/backwards.""" non_terminal: List[Node] = [n for n in nodes if not isinstance(n, TerminalNode)] # Set `is_read` based on `read_inherited`. for n in non_terminal: if reg in get_block_info(n).final_register_states.read_inherited: for p in n.parents: par_meta = get_block_info(p).final_register_states.get_meta(reg) if par_meta: par_meta.is_read = True # Propagate `is_read` backwards. todo = non_terminal[:] while todo: n = todo.pop() meta = get_block_info(n).final_register_states.get_meta(reg) for p in n.parents: par_meta = get_block_info(p).final_register_states.get_meta(reg) if (par_meta and not par_meta.is_read) and ( meta and meta.inherited and meta.is_read ): par_meta.is_read = True todo.append(p) # Set `uninteresting` and propagate it, `function_return`, and `in_pattern` forwards. # Start by assuming inherited values are all set; they will get unset iteratively, # but for cyclic dependency purposes we want to assume them set. for n in non_terminal: meta = get_block_info(n).final_register_states.get_meta(reg) if meta: if meta.inherited: meta.uninteresting = True meta.function_return = True meta.in_pattern = True else: meta.uninteresting |= ( meta.is_read or meta.function_return or meta.in_pattern ) todo = non_terminal[:] while todo: n = todo.pop() if isinstance(n, TerminalNode): continue meta = get_block_info(n).final_register_states.get_meta(reg) if not meta or not meta.inherited: continue all_uninteresting = True all_function_return = True all_in_pattern = True for p in n.parents: par_meta = get_block_info(p).final_register_states.get_meta(reg) if par_meta: all_uninteresting &= par_meta.uninteresting all_function_return &= par_meta.function_return all_in_pattern &= par_meta.in_pattern if meta.uninteresting and not all_uninteresting and not meta.is_read: meta.uninteresting = False todo.extend(n.children()) if meta.function_return and not all_function_return: meta.function_return = False todo.extend(n.children()) if meta.in_pattern and not all_in_pattern: meta.in_pattern = False todo.extend(n.children()) def determine_return_register( return_blocks: List[BlockInfo], fn_decl_provided: bool, arch: Arch ) -> Optional[Register]: """Determine which of the arch's base_return_regs (i.e. v0, f0) is the most likely to contain the return value, or if the function is likely void.""" def priority(block_info: BlockInfo, reg: Register) -> int: meta = block_info.final_register_states.get_meta(reg) if not meta: return 4 if meta.uninteresting: return 2 if meta.in_pattern: return 1 if meta.function_return: return 0 return 3 if not return_blocks: return None best_reg: Optional[Register] = None best_prio = -1 for reg in arch.base_return_regs: prios = [priority(b, reg) for b in return_blocks] max_prio = max(prios) if max_prio == 4: # Register is not always set, skip it continue if max_prio <= 2 and not fn_decl_provided: # Register is always read after being written, or comes from a # function call; seems unlikely to be an intentional return. # Skip it, unless we have a known non-void return type. continue if max_prio > best_prio: best_prio = max_prio best_reg = reg return best_reg def translate_node_body(node: Node, regs: RegInfo, stack_info: StackInfo) -> BlockInfo: """ Given a node and current register contents, return a BlockInfo containing the translated AST for that node. """ to_write: List[Union[Statement]] = [] local_var_writes: Dict[LocalVar, Tuple[Register, Expression]] = {} subroutine_args: Dict[int, Expression] = {} branch_condition: Optional[Condition] = None switch_expr: Optional[Expression] = None has_custom_return: bool = False has_function_call: bool = False in_pattern: bool = False arch = stack_info.global_info.arch def eval_once( expr: Expression, *, emit_exactly_once: bool, trivial: bool, prefix: str = "", reuse_var: Optional[Var] = None, ) -> EvalOnceExpr: if emit_exactly_once: # (otherwise this will be marked used once num_usages reaches 1) expr.use() elif "_fictive_" in prefix and isinstance(expr, EvalOnceExpr): # Avoid creating additional EvalOnceExprs for fictive Registers # so they're less likely to appear in the output return expr assert reuse_var or prefix if prefix == "condition_bit": prefix = "cond" var = reuse_var or Var(stack_info, "temp_" + prefix) expr = EvalOnceExpr( wrapped_expr=expr, var=var, type=expr.type, emit_exactly_once=emit_exactly_once, trivial=trivial, ) var.num_usages += 1 stmt = EvalOnceStmt(expr) to_write.append(stmt) stack_info.temp_vars.append(stmt) return expr def prevent_later_uses(expr_filter: Callable[[Expression], bool]) -> None: """Prevent later uses of registers whose contents match a callback filter.""" for r in regs.contents.keys(): data = regs.contents.get(r) assert data is not None expr = data.value if not data.meta.force and expr_filter(expr): # Mark the register as "if used, emit the expression's once # var". We usually always have a once var at this point, # but if we don't, create one. if not isinstance(expr, EvalOnceExpr): expr = eval_once( expr, emit_exactly_once=False, trivial=False, prefix=stack_info.function.reg_formatter.format(r), ) # This write isn't changing the value of the register; it didn't need # to be declared as part of the current instruction's inputs/outputs. regs.unchecked_set_with_meta(r, expr, replace(data.meta, force=True)) def prevent_later_value_uses(sub_expr: Expression) -> None: """Prevent later uses of registers that recursively contain a given subexpression.""" # Unused PassedInArg are fine; they can pass the uses_expr test simply based # on having the same variable name. If we didn't filter them out here it could # cause them to be incorrectly passed as function arguments -- the function # call logic sees an opaque wrapper and doesn't realize that they are unused # arguments that should not be passed on. prevent_later_uses( lambda e: uses_expr(e, lambda e2: e2 == sub_expr) and not (isinstance(e, PassedInArg) and not e.copied) ) def prevent_later_function_calls() -> None: """Prevent later uses of registers that recursively contain a function call.""" prevent_later_uses(lambda e: uses_expr(e, lambda e2: isinstance(e2, FuncCall))) def prevent_later_reads() -> None: """Prevent later uses of registers that recursively contain a read.""" contains_read = lambda e: isinstance(e, (StructAccess, ArrayAccess)) prevent_later_uses(lambda e: uses_expr(e, contains_read)) def set_reg_maybe_return(reg: Register, expr: Expression) -> None: regs.set_with_meta(reg, expr, RegMeta(in_pattern=in_pattern)) def set_reg(reg: Register, expr: Optional[Expression]) -> Optional[Expression]: if expr is None: if reg in regs: del regs[reg] return None if isinstance(expr, LocalVar): if ( isinstance(node, ReturnNode) and stack_info.maybe_get_register_var(reg) and stack_info.in_callee_save_reg_region(expr.value) and reg in stack_info.callee_save_regs ): # Elide saved register restores with --reg-vars (it doesn't # matter in other cases). return None if expr in local_var_writes: # Elide register restores (only for the same register for now, # to be conversative). orig_reg, orig_expr = local_var_writes[expr] if orig_reg == reg: expr = orig_expr uw_expr = expr if not isinstance(expr, Literal): expr = eval_once( expr, emit_exactly_once=False, trivial=is_trivial_expression(expr), prefix=stack_info.function.reg_formatter.format(reg), ) if reg == Register("zero"): # Emit the expression as is. It's probably a volatile load. expr.use() to_write.append(ExprStmt(expr)) else: dest = stack_info.maybe_get_register_var(reg) if dest is not None: stack_info.use_register_var(dest) # Avoid emitting x = x, but still refresh EvalOnceExpr's etc. if not (isinstance(uw_expr, RegisterVar) and uw_expr.reg == reg): source = as_type(expr, dest.type, True) source.use() to_write.append(StoreStmt(source=source, dest=dest)) expr = dest set_reg_maybe_return(reg, expr) return expr def clear_caller_save_regs() -> None: for reg in arch.temp_regs: if reg in regs: del regs[reg] def maybe_clear_local_var_writes(func_args: List[Expression]) -> None: # Clear the `local_var_writes` dict if any of the `func_args` contain # a reference to a stack var. (The called function may modify the stack, # replacing the value we have in `local_var_writes`.) for arg in func_args: if uses_expr( arg, lambda expr: isinstance(expr, AddressOf) and isinstance(expr.expr, LocalVar), ): local_var_writes.clear() return def process_instr(instr: Instruction) -> None: nonlocal branch_condition, switch_expr, has_function_call, in_pattern in_pattern = instr.in_pattern mnemonic = instr.mnemonic arch_mnemonic = instr.arch_mnemonic(arch) args = InstrArgs(instr.args, regs, stack_info) expr: Expression # Figure out what code to generate! if mnemonic in arch.instrs_ignore: pass elif mnemonic in arch.instrs_store or mnemonic in arch.instrs_store_update: # Store a value in a permanent place. if mnemonic in arch.instrs_store: to_store = arch.instrs_store[mnemonic](args) else: # PPC specific store-and-update instructions # `stwu r3, 8(r4)` is equivalent to `$r3 = *($r4 + 8); $r4 += 8;` to_store = arch.instrs_store_update[mnemonic](args) # Update the register in the second argument update = args.memory_ref(1) if not isinstance(update, AddressMode): raise DecompFailure( f"Unhandled store-and-update arg in {instr}: {update!r}" ) set_reg( update.rhs, add_imm(args.regs[update.rhs], Literal(update.offset), stack_info), ) if to_store is None: # Elided register preserval. pass elif isinstance(to_store.dest, SubroutineArg): # About to call a subroutine with this argument. Skip arguments for the # first four stack slots; they are also passed in registers. if to_store.dest.value >= 0x10: subroutine_args[to_store.dest.value] = to_store.source else: if isinstance(to_store.dest, LocalVar): stack_info.add_local_var(to_store.dest) raw_value = to_store.source if isinstance(raw_value, Cast) and raw_value.reinterpret: # When preserving values on the stack across function calls, # ignore the type of the stack variable. The same stack slot # might be used to preserve values of different types. raw_value = raw_value.expr local_var_writes[to_store.dest] = (args.reg_ref(0), raw_value) # Emit a write. This includes four steps: # - mark the expression as used (since writes are always emitted) # - mark the dest used (if it's a struct access it needs to be # evaluated, though ideally we would not mark the top-level expression # used; it may cause early emissions that shouldn't happen) # - mark other usages of the dest as "emit before this point if used". # - emit the actual write. # # Note that the prevent_later_value_uses step happens after use(), since # the stored expression is allowed to reference its destination var, # but before the write is written, since prevent_later_value_uses might # emit writes of its own that should go before this write. In practice # that probably never occurs -- all relevant register contents should be # EvalOnceExpr's that can be emitted at their point of creation, but # I'm not 100% certain that that's always the case and will remain so. to_store.source.use() to_store.dest.use() prevent_later_value_uses(to_store.dest) prevent_later_function_calls() to_write.append(to_store) elif mnemonic in arch.instrs_source_first: # Just 'mtc1'. It's reversed, so we have to specially handle it. set_reg(args.reg_ref(1), arch.instrs_source_first[mnemonic](args)) elif mnemonic in arch.instrs_branches: assert branch_condition is None branch_condition = arch.instrs_branches[mnemonic](args) elif mnemonic in arch.instrs_float_branches: assert branch_condition is None cond_bit = regs[Register("condition_bit")] if not isinstance(cond_bit, BinaryOp): cond_bit = ExprCondition(cond_bit, type=cond_bit.type) if arch_mnemonic == "mips:bc1t": branch_condition = cond_bit elif arch_mnemonic == "mips:bc1f": branch_condition = cond_bit.negated() elif mnemonic in arch.instrs_jumps: if arch_mnemonic == "ppc:bctr": # Switch jump assert isinstance(node, SwitchNode) switch_expr = args.regs[Register("ctr")] elif arch_mnemonic == "mips:jr": # MIPS: if args.reg_ref(0) == arch.return_address_reg: # Return from the function. assert isinstance(node, ReturnNode) else: # Switch jump. assert isinstance(node, SwitchNode) switch_expr = args.reg(0) elif arch_mnemonic == "ppc:blr": assert isinstance(node, ReturnNode) else: assert False, f"Unhandled jump mnemonic {arch_mnemonic}" elif mnemonic in arch.instrs_fn_call: if arch_mnemonic in ["mips:jal", "ppc:bl"]: fn_target = args.imm(0) if not ( ( isinstance(fn_target, AddressOf) and isinstance(fn_target.expr, GlobalSymbol) ) or isinstance(fn_target, Literal) ): raise DecompFailure( f"Target of function call must be a symbol, not {fn_target}" ) elif arch_mnemonic == "ppc:blrl": fn_target = args.regs[Register("lr")] elif arch_mnemonic == "ppc:bctrl": fn_target = args.regs[Register("ctr")] elif arch_mnemonic == "mips:jalr": fn_target = args.reg(1) else: assert False, f"Unhandled fn call mnemonic {arch_mnemonic}" fn_target = as_function_ptr(fn_target) fn_sig = fn_target.type.get_function_pointer_signature() assert fn_sig is not None, "known function pointers must have a signature" likely_regs: Dict[Register, bool] = {} for reg, data in regs.contents.items(): # We use a much stricter filter for PPC than MIPS, because the same # registers can be used arguments & return values. # The ABI can also mix & match the rN & fN registers, which makes the # "require" heuristic less powerful. # # - `meta.inherited` will only be False for registers set in *this* basic block # - `meta.function_return` will only be accurate for registers set within this # basic block because we have not called `propagate_register_meta` yet. # Within this block, it will be True for registers that were return values. if arch.arch == Target.ArchEnum.PPC and ( data.meta.inherited or data.meta.function_return ): likely_regs[reg] = False elif data.meta.in_pattern: # Like `meta.function_return` mentioned above, `meta.in_pattern` will only be # accurate for registers set within this basic block. likely_regs[reg] = False elif isinstance(data.value, PassedInArg) and not data.value.copied: likely_regs[reg] = False else: likely_regs[reg] = True abi = arch.function_abi(fn_sig, likely_regs, for_call=True) func_args: List[Expression] = [] for slot in abi.arg_slots: if slot.reg: expr = regs[slot.reg] elif slot.offset in subroutine_args: expr = subroutine_args.pop(slot.offset) else: expr = ErrorExpr( f"Unable to find stack arg {slot.offset:#x} in block" ) func_args.append( CommentExpr.wrap( as_type(expr, slot.type, True), prefix=slot.comment ) ) for slot in abi.possible_slots: assert slot.reg is not None func_args.append(regs[slot.reg]) # Add the arguments after a3. # TODO: limit this based on abi.arg_slots. If the function type is known # and not variadic, this list should be empty. for _, arg in sorted(subroutine_args.items()): if fn_sig.params_known and not fn_sig.is_variadic: func_args.append(CommentExpr.wrap(arg, prefix="extra?")) else: func_args.append(arg) if not fn_sig.params_known: while len(func_args) > len(fn_sig.params): fn_sig.params.append(FunctionParam()) # When the function signature isn't provided, the we only assume that each # parameter is "simple" (<=4 bytes, no return struct, etc.). This may not # match the actual function signature, but it's the best we can do. # Without that assumption, the logic from `function_abi` would be needed here. for i, (arg_expr, param) in enumerate(zip(func_args, fn_sig.params)): func_args[i] = as_type(arg_expr, param.type.decay(), True) # Reset subroutine_args, for the next potential function call. subroutine_args.clear() call: Expression = FuncCall( fn_target, func_args, fn_sig.return_type.weaken_void_ptr() ) call = eval_once(call, emit_exactly_once=True, trivial=False, prefix="ret") # Clear out caller-save registers, for clarity and to ensure that # argument regs don't get passed into the next function. clear_caller_save_regs() # Clear out local var write tracking if any argument contains a stack # reference. That dict is used to track register saves/restores, which # are unreliable if we call a function with a stack reference. maybe_clear_local_var_writes(func_args) # Prevent reads and function calls from moving across this call. # This isn't really right, because this call might be moved later, # and then this prevention should also be... but it's the best we # can do with the current code architecture. prevent_later_function_calls() prevent_later_reads() return_reg_vals = arch.function_return(call) for out in instr.outputs: if not isinstance(out, Register): continue val = return_reg_vals[out] if not isinstance(val, SecondF64Half): val = eval_once( val, emit_exactly_once=False, trivial=False, prefix=stack_info.function.reg_formatter.format(out), ) regs.set_with_meta(out, val, RegMeta(function_return=True)) has_function_call = True elif mnemonic in arch.instrs_float_comp: expr = arch.instrs_float_comp[mnemonic](args) regs[Register("condition_bit")] = expr elif mnemonic in arch.instrs_hi_lo: hi, lo = arch.instrs_hi_lo[mnemonic](args) set_reg(Register("hi"), hi) set_reg(Register("lo"), lo) elif mnemonic in arch.instrs_implicit_destination: reg, expr_fn = arch.instrs_implicit_destination[mnemonic] set_reg(reg, expr_fn(args)) elif mnemonic in arch.instrs_ppc_compare: if instr.args[0] != Register("cr0"): raise DecompFailure( f"Instruction {instr} not supported (first arg is not $cr0)" ) set_reg(Register("cr0_eq"), arch.instrs_ppc_compare[mnemonic](args, "==")) set_reg(Register("cr0_gt"), arch.instrs_ppc_compare[mnemonic](args, ">")) set_reg(Register("cr0_lt"), arch.instrs_ppc_compare[mnemonic](args, "<")) set_reg(Register("cr0_so"), Literal(0)) elif mnemonic in arch.instrs_no_dest: stmt = arch.instrs_no_dest[mnemonic](args) to_write.append(stmt) elif mnemonic.rstrip(".") in arch.instrs_destination_first: target = args.reg_ref(0) val = arch.instrs_destination_first[mnemonic.rstrip(".")](args) # TODO: IDO tends to keep variables within single registers. Thus, # if source = target, maybe we could overwrite that variable instead # of creating a new one? target_val = set_reg(target, val) mn_parts = arch_mnemonic.split(".") if arch_mnemonic.startswith("ppc:") and arch_mnemonic.endswith("."): # PPC instructions suffixed with . set condition bits (CR0) based on the result value if target_val is None: target_val = val set_reg( Register("cr0_eq"), BinaryOp.icmp(target_val, "==", Literal(0, type=target_val.type)), ) # Use manual casts for cr0_gt/cr0_lt so that the type of target_val is not modified # until the resulting bit is .use()'d. target_s32 = Cast( target_val, reinterpret=True, silent=True, type=Type.s32() ) set_reg( Register("cr0_gt"), BinaryOp(target_s32, ">", Literal(0), type=Type.s32()), ) set_reg( Register("cr0_lt"), BinaryOp(target_s32, "<", Literal(0), type=Type.s32()), ) set_reg( Register("cr0_so"), fn_op("MIPS2C_OVERFLOW", [target_val], type=Type.s32()), ) elif ( len(mn_parts) >= 2 and mn_parts[0].startswith("mips:") and mn_parts[1] == "d" ) or arch_mnemonic == "mips:ldc1": set_reg(target.other_f64_reg(), SecondF64Half()) elif mnemonic in arch.instrs_load_update: target = args.reg_ref(0) val = arch.instrs_load_update[mnemonic](args) set_reg(target, val) if arch_mnemonic in ["ppc:lwzux", "ppc:lhzux", "ppc:lbzux"]: # In `rD, rA, rB`, update `rA = rA + rB` update_reg = args.reg_ref(1) offset = args.reg(2) else: # In `rD, rA(N)`, update `rA = rA + N` update = args.memory_ref(1) if not isinstance(update, AddressMode): raise DecompFailure( f"Unhandled store-and-update arg in {instr}: {update!r}" ) update_reg = update.rhs offset = Literal(update.offset) if update_reg == target: raise DecompFailure( f"Invalid instruction, rA and rD must be different in {instr}" ) set_reg(update_reg, add_imm(args.regs[update_reg], offset, stack_info)) else: expr = ErrorExpr(f"unknown instruction: {instr}") if arch_mnemonic.startswith("ppc:") and arch_mnemonic.endswith("."): # Unimplemented PPC instructions that modify CR0 set_reg(Register("cr0_eq"), expr) set_reg(Register("cr0_gt"), expr) set_reg(Register("cr0_lt"), expr) set_reg(Register("cr0_so"), expr) if args.count() >= 1 and isinstance(args.raw_arg(0), Register): reg = args.reg_ref(0) expr = eval_once( expr, emit_exactly_once=True, trivial=False, prefix=stack_info.function.reg_formatter.format(reg), ) if reg != Register("zero"): set_reg_maybe_return(reg, expr) else: to_write.append(ExprStmt(expr)) for instr in node.block.instructions: with regs.current_instr(instr): process_instr(instr) if branch_condition is not None: branch_condition.use() switch_control: Optional[SwitchControl] = None if switch_expr is not None: switch_control = SwitchControl.from_expr(switch_expr) switch_control.control_expr.use() return BlockInfo( to_write=to_write, return_value=None, switch_control=switch_control, branch_condition=branch_condition, final_register_states=regs, has_function_call=has_function_call, ) def translate_graph_from_block( node: Node, regs: RegInfo, stack_info: StackInfo, used_phis: List[PhiExpr], return_blocks: List[BlockInfo], options: Options, ) -> None: """ Given a FlowGraph node and a dictionary of register contents, give that node its appropriate BlockInfo (which contains the AST of its code). """ if options.debug: print(f"\nNode in question: {node}") # Translate the given node and discover final register states. try: block_info = translate_node_body(node, regs, stack_info) if options.debug: print(block_info) except Exception as e: # TODO: handle issues better if options.stop_on_error: raise instr: Optional[Instruction] = None if isinstance(e, InstrProcessingFailure) and isinstance(e.__cause__, Exception): instr = e.instr e = e.__cause__ if isinstance(e, DecompFailure): emsg = str(e) print(emsg) else: tb = e.__traceback__ traceback.print_exception(None, e, tb) emsg = str(e) or traceback.format_tb(tb)[-1] emsg = emsg.strip().split("\n")[-1].strip() error_stmts: List[Statement] = [CommentStmt(f"Error: {emsg}")] if instr is not None: print( f"Error occurred while processing instruction: {instr}", file=sys.stderr ) error_stmts.append(CommentStmt(f"At instruction: {instr}")) print(file=sys.stderr) block_info = BlockInfo( to_write=error_stmts, return_value=None, switch_control=None, branch_condition=ErrorExpr(), final_register_states=regs, has_function_call=False, ) node.block.add_block_info(block_info) if isinstance(node, ReturnNode): return_blocks.append(block_info) # Translate everything dominated by this node, now that we know our own # final register state. This will eventually reach every node. for child in node.immediately_dominates: if isinstance(child, TerminalNode): continue new_regs = RegInfo(stack_info=stack_info) for reg, data in regs.contents.items(): new_regs.set_with_meta( reg, data.value, RegMeta(inherited=True, force=data.meta.force) ) phi_regs = ( r for r in locs_clobbered_until_dominator(child) if isinstance(r, Register) ) for reg in phi_regs: if reg_always_set(child, reg, dom_set=(reg in regs)): expr: Optional[Expression] = stack_info.maybe_get_register_var(reg) if expr is None: expr = PhiExpr( reg=reg, node=child, used_phis=used_phis, type=Type.any_reg() ) new_regs.set_with_meta(reg, expr, RegMeta(inherited=True)) elif reg in new_regs: del new_regs[reg] translate_graph_from_block( child, new_regs, stack_info, used_phis, return_blocks, options ) def resolve_types_late(stack_info: StackInfo) -> None: """ After translating a function, perform a final type-resolution pass. """ # Final check over stack var types. Because of delayed type unification, some # locations should now be marked as "weak". for location in stack_info.weak_stack_var_types.keys(): stack_info.get_stack_var(location, store=False) # Use dereferences to determine pointer types struct_type_map = stack_info.get_struct_type_map() for var, offset_type_map in struct_type_map.items(): if len(offset_type_map) == 1 and 0 in offset_type_map: # var was probably a plain pointer, not a struct # Try to unify it with the appropriate pointer type, # to fill in the type if it does not already have one type = offset_type_map[0] var.type.unify(Type.ptr(type)) @dataclass class FunctionInfo: stack_info: StackInfo flow_graph: FlowGraph return_type: Type symbol: GlobalSymbol @dataclass class GlobalInfo: asm_data: AsmData arch: Arch target: Target local_functions: Set[str] typemap: TypeMap typepool: TypePool global_symbol_map: Dict[str, GlobalSymbol] = field(default_factory=dict) def asm_data_value(self, sym_name: str) -> Optional[AsmDataEntry]: return self.asm_data.values.get(sym_name) def address_of_gsym(self, sym_name: str) -> AddressOf: if sym_name in self.global_symbol_map: sym = self.global_symbol_map[sym_name] else: demangled_symbol: Optional[CxxSymbol] = None demangled_str: Optional[str] = None if self.target.language == Target.LanguageEnum.CXX: try: demangled_symbol = demangle_codewarrior_parse(sym_name) except ValueError: pass else: demangled_str = str(demangled_symbol) sym = self.global_symbol_map[sym_name] = GlobalSymbol( symbol_name=sym_name, type=Type.any(), asm_data_entry=self.asm_data_value(sym_name), demangled_str=demangled_str, ) # If the symbol is a C++ vtable, try to build a custom type for it by parsing it if ( self.target.language == Target.LanguageEnum.CXX and sym_name.startswith("__vt__") and sym.asm_data_entry is not None ): sym.type.unify(self.vtable_type(sym_name, sym.asm_data_entry)) fn = self.typemap.functions.get(sym_name) ctype: Optional[CType] if fn is not None: ctype = fn.type else: ctype = self.typemap.var_types.get(sym_name) if ctype is not None: sym.symbol_in_context = True sym.initializer_in_typemap = ( sym_name in self.typemap.vars_with_initializers ) sym.type.unify(Type.ctype(ctype, self.typemap, self.typepool)) if sym_name not in self.typepool.unknown_decls: sym.type_provided = True elif sym_name in self.local_functions: sym.type.unify(Type.function()) # Do this after unifying the type in the typemap, so that it has lower precedence if demangled_symbol is not None: sym.type.unify( Type.demangled_symbol(self.typemap, self.typepool, demangled_symbol) ) return AddressOf(sym, type=sym.type.reference()) def vtable_type(self, sym_name: str, asm_data_entry: AsmDataEntry) -> Type: """ Parse MWCC vtable data to create a custom struct to represent it. This format is not well documented, but is briefly explored in this series of posts: https://web.archive.org/web/20220413174849/http://hacksoflife.blogspot.com/2007/02/c-objects-part-2-single-inheritance.html """ size = asm_data_entry.size_range_bytes()[1] struct = StructDeclaration.unknown( self.typepool, size=size, align=4, tag_name=sym_name ) offset = 0 for entry in asm_data_entry.data: if isinstance(entry, bytes): # MWCC vtables start with a pointer to a typeid struct (or NULL) and an offset if len(entry) % 4 != 0: raise DecompFailure( f"Unable to parse misaligned vtable data in {sym_name}" ) for i in range(len(entry) // 4): field_name = f"{struct.new_field_prefix}{offset:X}" struct.try_add_field( Type.reg32(likely_float=False), offset, field_name, size=4 ) offset += 4 else: entry_name = entry try: demangled_field_sym = demangle_codewarrior_parse(entry) if demangled_field_sym.name.qualified_name is not None: entry_name = str(demangled_field_sym.name.qualified_name[-1]) except ValueError: pass field = struct.try_add_field( self.address_of_gsym(entry).type, offset, name=entry_name, size=4, ) assert field is not None field.known = True offset += 4 return Type.struct(struct) def is_function_known_void(self, sym_name: str) -> bool: """Return True if the function exists in the context, and has no return value""" fn = self.typemap.functions.get(sym_name) if fn is None: return False return fn.ret_type is None def initializer_for_symbol( self, sym: GlobalSymbol, fmt: Formatter ) -> Optional[str]: assert sym.asm_data_entry is not None data = sym.asm_data_entry.data[:] def read_uint(n: int) -> Optional[int]: """Read the next `n` bytes from `data` as an (long) integer""" assert 0 < n <= 8 if not data or not isinstance(data[0], bytes): return None if len(data[0]) < n: return None bs = data[0][:n] data[0] = data[0][n:] if not data[0]: del data[0] value = 0 for b in bs: value = (value << 8) | b return value def read_pointer() -> Optional[Expression]: """Read the next label from `data`""" if not data or not isinstance(data[0], str): return None label = data[0] data.pop(0) return self.address_of_gsym(label) def for_type(type: Type) -> Optional[str]: """Return the initializer for a single element of type `type`""" if type.is_struct() or type.is_array(): struct_fields = type.get_initializer_fields() if not struct_fields: return None members = [] for field in struct_fields: if isinstance(field, int): # Check that all padding bytes are 0 for i in range(field): padding = read_uint(1) if padding != 0: return None else: m = for_type(field) if m is None: return None members.append(m) return fmt.format_array(members) if type.is_reg(): size = type.get_size_bytes() if not size: return None if size == 4: ptr = read_pointer() if ptr is not None: return as_type(ptr, type, silent=True).format(fmt) value = read_uint(size) if value is not None: enum_name = type.get_enum_name(value) if enum_name is not None: return enum_name expr = as_type(Literal(value), type, True) return elide_casts_for_store(expr).format(fmt) # Type kinds K_FN and K_VOID do not have initializers return None return for_type(sym.type) def find_forward_declares_needed(self, functions: List[FunctionInfo]) -> Set[str]: funcs_seen = set() forward_declares_needed = self.asm_data.mentioned_labels for func in functions: funcs_seen.add(func.stack_info.function.name) for instr in func.stack_info.function.body: if not isinstance(instr, Instruction): continue for arg in instr.args: if isinstance(arg, AsmGlobalSymbol): func_name = arg.symbol_name elif isinstance(arg, Macro) and isinstance( arg.argument, AsmGlobalSymbol ): func_name = arg.argument.symbol_name else: continue if func_name in self.local_functions: if func_name not in funcs_seen: forward_declares_needed.add(func_name) return forward_declares_needed def global_decls( self, fmt: Formatter, decls: Options.GlobalDeclsEnum, functions: List[FunctionInfo], ) -> str: # Format labels from symbol_type_map into global declarations. # As the initializers are formatted, this may cause more symbols # to be added to the global_symbol_map. forward_declares_needed = self.find_forward_declares_needed(functions) lines = [] processed_names: Set[str] = set() while True: names: AbstractSet[str] = self.global_symbol_map.keys() if decls == Options.GlobalDeclsEnum.ALL: names |= self.asm_data.values.keys() names -= processed_names if not names: break for name in sorted(names): processed_names.add(name) sym = self.address_of_gsym(name).expr assert isinstance(sym, GlobalSymbol) data_entry = sym.asm_data_entry # Is the label defined in this unit (in the active AsmData file(s)) is_in_file = data_entry is not None or name in self.local_functions # Is the label externally visible (mentioned in the context file) is_global = sym.symbol_in_context # Is the label a symbol in .rodata? is_const = data_entry is not None and data_entry.is_readonly if data_entry and data_entry.is_jtbl: # Skip jump tables continue if is_in_file and is_global and sym.type.is_function(): # Skip externally-declared functions that are defined here continue if self.local_functions == {name}: # Skip the function being decompiled if just a single one continue if not is_in_file and sym.type_provided: # Skip externally-declared symbols that are defined in other files continue # TODO: Use original MIPSFile ordering for variables sort_order = ( not sym.type.is_function(), is_global, is_in_file, is_const, name, ) qualifier = "" value: Optional[str] = None comments = [] # Determine type qualifier: static, extern, or neither if is_in_file and is_global: qualifier = "" elif is_in_file: qualifier = "static" else: qualifier = "extern" if sym.type.is_function(): comments.append(qualifier) qualifier = "" # Try to guess if the symbol is an array (and if it is, its dimension) if # we have a data entry for it, and the symbol is either not in the typemap # or was a variable-length array there ("VLA", e.g. `int []`) # (Otherwise, if the dim is provided by the typemap, we trust it.) element_type, array_dim = sym.type.get_array() is_vla = element_type is not None and ( array_dim is None or array_dim <= 0 ) if data_entry and (not sym.type_provided or is_vla): # The size of the data entry is uncertain, because of padding # between sections. Generally `(max_data_size - data_size) < 16`. min_data_size, max_data_size = data_entry.size_range_bytes() # The size of the element type (not the size of the array type) if element_type is None: element_type = sym.type # If we don't know the type, we can't guess the array_dim type_size = element_type.get_size_bytes() if type_size: potential_dim, extra_bytes = sym.potential_array_dim(type_size) if potential_dim == 0 and extra_bytes > 0: # The type is too big for our data. (not an array) comments.append( f"type too large by {fmt.format_int(type_size - extra_bytes)}" ) elif potential_dim > 1 or is_vla: # NB: In general, replacing the types of Expressions can be sketchy. # However, the GlobalSymbol here came from address_of_gsym(), which # always returns a reference to the element_type. array_dim = potential_dim sym.type = Type.array(element_type, array_dim) if potential_dim != 0 and extra_bytes > 0: comments.append( f"extra bytes: {fmt.format_int(extra_bytes)}" ) # Try to convert the data from .data/.rodata into an initializer if data_entry and not data_entry.is_bss: value = self.initializer_for_symbol(sym, fmt) if value is None: # This warning helps distinguish .bss symbols from .data/.rodata, # IDO only puts symbols in .bss if they don't have any initializer comments.append("unable to generate initializer") if is_const: comments.append("const") # Float & string constants are almost always inlined and can be omitted if sym.is_string_constant(): continue if array_dim is None and sym.type.is_likely_float(): continue # In "none" mode, do not emit any decls if decls == Options.GlobalDeclsEnum.NONE: continue # In modes except "all", skip the decl if the context file already had an initializer if decls != Options.GlobalDeclsEnum.ALL and sym.initializer_in_typemap: continue # In modes except "all", skip vtable decls when compiling C++ if ( decls != Options.GlobalDeclsEnum.ALL and self.target.language == Target.LanguageEnum.CXX and name.startswith("__vt__") ): continue if ( sym.type.is_function() and decls != Options.GlobalDeclsEnum.ALL and name in self.local_functions and name not in forward_declares_needed ): continue qualifier = f"{qualifier} " if qualifier else "" value = f" = {value}" if value else "" lines.append( ( sort_order, fmt.with_comments( f"{qualifier}{sym.type.to_decl(name, fmt)}{value};", comments, ) + "\n", ) ) lines.sort() return "".join(line for _, line in lines) def narrow_func_call_outputs( function: Function, global_info: GlobalInfo, ) -> None: """ Modify the `outputs` list of function call Instructions using the context file. For now, this only handles known-void functions, but in the future it could be extended to select a specific register subset based on type. """ for instr in function.body: if ( isinstance(instr, Instruction) and isinstance(instr.function_target, AsmGlobalSymbol) and global_info.is_function_known_void(instr.function_target.symbol_name) ): instr.outputs.clear() def translate_to_ast( function: Function, flow_graph: FlowGraph, options: Options, global_info: GlobalInfo, ) -> FunctionInfo: """ Given a function, produce a FlowGraph that both contains control-flow information and has AST transformations for each block of code and branch condition. """ # Initialize info about the function. stack_info = get_stack_info(function, global_info, flow_graph) start_regs: RegInfo = RegInfo(stack_info=stack_info) arch = global_info.arch start_regs[arch.stack_pointer_reg] = GlobalSymbol("sp", type=Type.ptr()) for reg in arch.saved_regs: start_regs[reg] = stack_info.saved_reg_symbol(reg.register_name) fn_sym = global_info.address_of_gsym(function.name).expr assert isinstance(fn_sym, GlobalSymbol) fn_type = fn_sym.type fn_type.unify(Type.function()) fn_sig = Type.ptr(fn_type).get_function_pointer_signature() assert fn_sig is not None, "fn_type is known to be a function" return_type = fn_sig.return_type stack_info.is_variadic = fn_sig.is_variadic def make_arg(offset: int, type: Type) -> PassedInArg: assert offset % 4 == 0 return PassedInArg(offset, copied=False, stack_info=stack_info, type=type) abi = arch.function_abi( fn_sig, likely_regs={reg: True for reg in arch.argument_regs}, for_call=False, ) for slot in abi.arg_slots: stack_info.add_known_param(slot.offset, slot.name, slot.type) if slot.reg is not None: start_regs.set_with_meta( slot.reg, make_arg(slot.offset, slot.type), RegMeta(uninteresting=True) ) for slot in abi.possible_slots: if slot.reg is not None: start_regs.set_with_meta( slot.reg, make_arg(slot.offset, slot.type), RegMeta(uninteresting=True) ) if options.reg_vars == ["saved"]: reg_vars = arch.saved_regs elif options.reg_vars == ["most"]: reg_vars = arch.saved_regs + arch.simple_temp_regs elif options.reg_vars == ["all"]: reg_vars = arch.saved_regs + arch.simple_temp_regs + arch.argument_regs else: reg_vars = [ stack_info.function.reg_formatter.parse(x, arch) for x in options.reg_vars ] for reg in reg_vars: reg_name = stack_info.function.reg_formatter.format(reg) stack_info.add_register_var(reg, reg_name) if options.debug: print(stack_info) print("\nNow, we attempt to translate:") used_phis: List[PhiExpr] = [] return_blocks: List[BlockInfo] = [] translate_graph_from_block( flow_graph.entry_node(), start_regs, stack_info, used_phis, return_blocks, options, ) for reg in arch.base_return_regs: propagate_register_meta(flow_graph.nodes, reg) return_reg: Optional[Register] = None if not options.void and not return_type.is_void(): return_reg = determine_return_register( return_blocks, fn_sym.type_provided, arch ) if return_reg is not None: for b in return_blocks: if return_reg in b.final_register_states: ret_val = b.final_register_states[return_reg] ret_val = as_type(ret_val, return_type, True) ret_val.use() b.return_value = ret_val else: return_type.unify(Type.void()) if not fn_sig.params_known: while len(fn_sig.params) < len(stack_info.arguments): fn_sig.params.append(FunctionParam()) for param, arg in zip(fn_sig.params, stack_info.arguments): param.type.unify(arg.type) if not param.name: param.name = arg.format(Formatter()) assign_phis(used_phis, stack_info) resolve_types_late(stack_info) if options.pdb_translate: import pdb v: Dict[str, object] = {} fmt = Formatter() for local in stack_info.local_vars: var_name = local.format(fmt) v[var_name] = local for temp in stack_info.temp_vars: if temp.need_decl(): var_name = temp.expr.var.format(fmt) v[var_name] = temp.expr for phi in stack_info.phi_vars: assert phi.name is not None v[phi.name] = phi pdb.set_trace() return FunctionInfo(stack_info, flow_graph, return_type, fn_sym)
38.14032
131
0.598064
import abc from collections import defaultdict from contextlib import contextmanager from dataclasses import dataclass, field, replace import math import struct import sys import traceback import typing from typing import ( AbstractSet, Callable, Collection, DefaultDict, Dict, Iterator, List, Mapping, Optional, Set, Tuple, Union, ) from .c_types import CType, TypeMap from .demangle_codewarrior import parse as demangle_codewarrior_parse, CxxSymbol from .error import DecompFailure, static_assert_unreachable from .flow_graph import ( ArchFlowGraph, FlowGraph, Function, Node, ReturnNode, SwitchNode, TerminalNode, locs_clobbered_until_dominator, ) from .ir_pattern import IrPattern, simplify_ir_patterns from .options import CodingStyle, Formatter, Options, Target from .parse_file import AsmData, AsmDataEntry from .parse_instruction import ( ArchAsm, Argument, AsmAddressMode, AsmGlobalSymbol, AsmLiteral, BinOp, Instruction, InstrProcessingFailure, Macro, Register, StackLocation, current_instr, ) from .types import ( AccessPath, FunctionParam, FunctionSignature, StructDeclaration, Type, TypePool, ) InstrSet = Collection[str] InstrMap = Mapping[str, Callable[["InstrArgs"], "Expression"]] StmtInstrMap = Mapping[str, Callable[["InstrArgs"], "Statement"]] CmpInstrMap = Mapping[str, Callable[["InstrArgs"], "Condition"]] StoreInstrMap = Mapping[str, Callable[["InstrArgs"], Optional["StoreStmt"]]] MaybeInstrMap = Mapping[str, Callable[["InstrArgs"], Optional["Expression"]]] PairInstrMap = Mapping[str, Callable[["InstrArgs"], Tuple["Expression", "Expression"]]] ImplicitInstrMap = Mapping[str, Tuple[Register, Callable[["InstrArgs"], "Expression"]]] PpcCmpInstrMap = Mapping[str, Callable[["InstrArgs", str], "Expression"]] class Arch(ArchFlowGraph): instrs_ignore: InstrSet = set() instrs_store: StoreInstrMap = {} instrs_store_update: StoreInstrMap = {} instrs_load_update: InstrMap = {} instrs_branches: CmpInstrMap = {} instrs_float_branches: InstrSet = set() instrs_float_comp: CmpInstrMap = {} instrs_ppc_compare: PpcCmpInstrMap = {} instrs_jumps: InstrSet = set() instrs_fn_call: InstrSet = set() instrs_no_dest: StmtInstrMap = {} instrs_hi_lo: PairInstrMap = {} instrs_source_first: InstrMap = {} instrs_destination_first: InstrMap = {} instrs_implicit_destination: ImplicitInstrMap = {} @abc.abstractmethod def function_abi( self, fn_sig: FunctionSignature, likely_regs: Dict[Register, bool], *, for_call: bool, ) -> "Abi": ... @abc.abstractmethod def function_return(self, expr: "Expression") -> Dict[Register, "Expression"]: ... ir_patterns: List[IrPattern] = [] def simplify_ir(self, flow_graph: FlowGraph) -> None: simplify_ir_patterns(self, flow_graph, self.ir_patterns) ASSOCIATIVE_OPS: Set[str] = {"+", "&&", "||", "&", "|", "^", "*"} COMPOUND_ASSIGNMENT_OPS: Set[str] = {"+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>"} PSEUDO_FUNCTION_OPS: Set[str] = {"MULT_HI", "MULTU_HI", "DMULT_HI", "DMULTU_HI", "CLZ"} def as_type(expr: "Expression", type: Type, silent: bool) -> "Expression": type = type.weaken_void_ptr() ptr_target_type = type.get_pointer_target() if expr.type.unify(type): if silent or isinstance(expr, Literal): return expr elif ptr_target_type is not None: ptr_target_type_size = ptr_target_type.get_size_bytes() field_path, field_type, _ = expr.type.get_deref_field( 0, target_size=ptr_target_type_size ) if field_path is not None and field_type.unify(ptr_target_type): expr = AddressOf( StructAccess( struct_var=expr, offset=0, target_size=ptr_target_type_size, field_path=field_path, stack_info=None, type=field_type, ), type=type, ) if silent: return expr return Cast(expr=expr, reinterpret=True, silent=False, type=type) def as_f32(expr: "Expression") -> "Expression": return as_type(expr, Type.f32(), True) def as_f64(expr: "Expression") -> "Expression": return as_type(expr, Type.f64(), True) def as_sintish(expr: "Expression", *, silent: bool = False) -> "Expression": return as_type(expr, Type.sintish(), silent) def as_uintish(expr: "Expression") -> "Expression": return as_type(expr, Type.uintish(), False) def as_u32(expr: "Expression") -> "Expression": return as_type(expr, Type.u32(), False) def as_s64(expr: "Expression", *, silent: bool = False) -> "Expression": return as_type(expr, Type.s64(), silent) def as_u64(expr: "Expression", *, silent: bool = False) -> "Expression": return as_type(expr, Type.u64(), silent) def as_intish(expr: "Expression") -> "Expression": return as_type(expr, Type.intish(), True) def as_int64(expr: "Expression") -> "Expression": return as_type(expr, Type.int64(), True) def as_intptr(expr: "Expression") -> "Expression": return as_type(expr, Type.intptr(), True) def as_ptr(expr: "Expression") -> "Expression": return as_type(expr, Type.ptr(), True) def as_function_ptr(expr: "Expression") -> "Expression": return as_type(expr, Type.ptr(Type.function()), True) @dataclass class StackInfo: function: Function global_info: "GlobalInfo" flow_graph: FlowGraph allocated_stack_size: int = 0 is_leaf: bool = True is_variadic: bool = False uses_framepointer: bool = False subroutine_arg_top: int = 0 callee_save_regs: Set[Register] = field(default_factory=set) callee_save_reg_region: Tuple[int, int] = (0, 0) unique_type_map: Dict[Tuple[str, object], "Type"] = field(default_factory=dict) local_vars: List["LocalVar"] = field(default_factory=list) temp_vars: List["EvalOnceStmt"] = field(default_factory=list) phi_vars: List["PhiExpr"] = field(default_factory=list) reg_vars: Dict[Register, "RegisterVar"] = field(default_factory=dict) used_reg_vars: Set[Register] = field(default_factory=set) arguments: List["PassedInArg"] = field(default_factory=list) temp_name_counter: Dict[str, int] = field(default_factory=dict) nonzero_accesses: Set["Expression"] = field(default_factory=set) param_names: Dict[int, str] = field(default_factory=dict) stack_pointer_type: Optional[Type] = None replace_first_arg: Optional[Tuple[str, Type]] = None weak_stack_var_types: Dict[int, Type] = field(default_factory=dict) weak_stack_var_locations: Set[int] = field(default_factory=set) def temp_var(self, prefix: str) -> str: counter = self.temp_name_counter.get(prefix, 0) + 1 self.temp_name_counter[prefix] = counter return prefix + (f"_{counter}" if counter > 1 else "") def in_subroutine_arg_region(self, location: int) -> bool: if self.global_info.arch.arch == Target.ArchEnum.PPC: return False if self.is_leaf: return False assert self.subroutine_arg_top is not None return location < self.subroutine_arg_top def in_callee_save_reg_region(self, location: int) -> bool: lower_bound, upper_bound = self.callee_save_reg_region if lower_bound <= location < upper_bound: return True if ( self.global_info.arch.arch == Target.ArchEnum.PPC and location == self.allocated_stack_size + 4 ): return True return False def location_above_stack(self, location: int) -> bool: return location >= self.allocated_stack_size def add_known_param(self, offset: int, name: Optional[str], type: Type) -> None: if offset == 0 and type.is_pointer() and self.replace_first_arg is None: namespace = self.function.name.partition("_")[0] base_struct_type = type.get_pointer_target() self_struct = self.global_info.typepool.get_struct_by_tag_name( namespace, self.global_info.typemap ) if ( self_struct is not None and base_struct_type is not None and base_struct_type.is_struct() ): self_struct_type = Type.struct(self_struct) field_path, field_type, _ = self_struct_type.get_field( offset=0, target_size=base_struct_type.get_size_bytes() ) if ( field_path is not None and field_type.unify(base_struct_type) and not self_struct_type.unify(base_struct_type) ): self.replace_first_arg = (name or "_self", type) name = "this" if name == "thisx" else "self" type = Type.ptr(Type.struct(self_struct)) if name: self.param_names[offset] = name _, arg = self.get_argument(offset) self.add_argument(arg) arg.type.unify(type) def get_param_name(self, offset: int) -> Optional[str]: return self.param_names.get(offset) def add_local_var(self, var: "LocalVar") -> None: if any(v.value == var.value for v in self.local_vars): return self.local_vars.append(var) self.local_vars.sort(key=lambda v: v.value) def add_argument(self, arg: "PassedInArg") -> None: if any(a.value == arg.value for a in self.arguments): return self.arguments.append(arg) self.arguments.sort(key=lambda a: a.value) def get_argument(self, location: int) -> Tuple["Expression", "PassedInArg"]: real_location = location & -4 arg = PassedInArg( real_location, copied=True, stack_info=self, type=self.unique_type_for("arg", real_location, Type.any_reg()), ) if real_location == location - 3: return as_type(arg, Type.int_of_size(8), True), arg if real_location == location - 2: return as_type(arg, Type.int_of_size(16), True), arg return arg, arg def record_struct_access(self, ptr: "Expression", location: int) -> None: if location: self.nonzero_accesses.add(unwrap_deep(ptr)) def has_nonzero_access(self, ptr: "Expression") -> bool: return unwrap_deep(ptr) in self.nonzero_accesses def unique_type_for(self, category: str, key: object, default: Type) -> "Type": key = (category, key) if key not in self.unique_type_map: self.unique_type_map[key] = default return self.unique_type_map[key] def saved_reg_symbol(self, reg_name: str) -> "GlobalSymbol": sym_name = "saved_reg_" + reg_name type = self.unique_type_for("saved_reg", sym_name, Type.any_reg()) return GlobalSymbol(symbol_name=sym_name, type=type) def should_save(self, expr: "Expression", offset: Optional[int]) -> bool: expr = early_unwrap(expr) if isinstance(expr, GlobalSymbol) and ( expr.symbol_name.startswith("saved_reg_") or expr.symbol_name == "sp" ): return True if ( isinstance(expr, PassedInArg) and not expr.copied and (offset is None or offset == self.allocated_stack_size + expr.value) ): return True return False def get_stack_var(self, location: int, *, store: bool) -> "Expression": if self.in_callee_save_reg_region(location): return LocalVar(location, type=Type.any_reg(), path=None) elif self.location_above_stack(location): ret, arg = self.get_argument(location - self.allocated_stack_size) if not store: self.add_argument(arg) return ret elif self.in_subroutine_arg_region(location): return SubroutineArg(location, type=Type.any_reg()) else: # Local variable assert self.stack_pointer_type is not None field_path, field_type, _ = self.stack_pointer_type.get_deref_field( location, target_size=None ) # Some variables on the stack are compiler-managed, and aren't declared previous_stored_type = self.weak_stack_var_types.get(location) if previous_stored_type is not None: if not previous_stored_type.unify(field_type): # This marker is only used to annotate the output self.weak_stack_var_locations.add(location) if store: # If there's already been a store to `location`, then return a fresh type field_type = Type.any_field() else: field_type = previous_stored_type if store: self.weak_stack_var_types[location] = field_type return LocalVar(location, type=field_type, path=field_path) def maybe_get_register_var(self, reg: Register) -> Optional["RegisterVar"]: return self.reg_vars.get(reg) def add_register_var(self, reg: Register, name: str) -> None: type = Type.floatish() if reg.is_float() else Type.intptr() self.reg_vars[reg] = RegisterVar(reg=reg, type=type, name=name) def use_register_var(self, var: "RegisterVar") -> None: self.used_reg_vars.add(var.reg) def is_stack_reg(self, reg: Register) -> bool: if reg == self.global_info.arch.stack_pointer_reg: return True if reg == self.global_info.arch.frame_pointer_reg: return self.uses_framepointer return False def get_struct_type_map(self) -> Dict["Expression", Dict[int, Type]]: struct_type_map: Dict[Expression, Dict[int, Type]] = {} for (category, key), type in self.unique_type_map.items(): if category != "struct": continue var, offset = typing.cast(Tuple[Expression, int], key) if var not in struct_type_map: struct_type_map[var] = {} struct_type_map[var][offset] = type return struct_type_map def __str__(self) -> str: return "\n".join( [ f"Stack info for function {self.function.name}:", f"Allocated stack size: {self.allocated_stack_size}", f"Leaf? {self.is_leaf}", f"Bounds of callee-saved vars region: {self.callee_save_reg_region}", f"Callee save registers: {self.callee_save_regs}", ] ) def get_stack_info( function: Function, global_info: "GlobalInfo", flow_graph: FlowGraph, ) -> StackInfo: arch = global_info.arch info = StackInfo(function, global_info, flow_graph) # # IDO puts local variables *above* the saved registers on the stack, but # GCC puts local variables *below* the saved registers. # To support both, we explicitly determine both the upper & lower bounds of the # saved registers. Then, we estimate the boundary of the subroutine arguments # by finding the lowest stack offset that is loaded from or computed. (This # assumes that the compiler will never reuse a section of stack for *both* # a local variable *and* a subroutine argument.) Anything within the stack frame, # but outside of these two regions, is considered a local variable. callee_saved_offsets: List[int] = [] # Track simple literal values stored into registers: MIPS compilers need a temp # reg to move the stack pointer more than 0x7FFF bytes. temp_reg_values: Dict[Register, int] = {} for inst in flow_graph.entry_node().block.instructions: arch_mnemonic = inst.arch_mnemonic(arch) if inst.mnemonic in arch.instrs_fn_call: break elif arch_mnemonic == "mips:addiu" and inst.args[0] == arch.stack_pointer_reg: # Moving the stack pointer on MIPS assert isinstance(inst.args[2], AsmLiteral) info.allocated_stack_size = abs(inst.args[2].signed_value()) elif ( arch_mnemonic == "mips:subu" and inst.args[0] == arch.stack_pointer_reg and inst.args[1] == arch.stack_pointer_reg and inst.args[2] in temp_reg_values ): # Moving the stack pointer more than 0x7FFF on MIPS # TODO: This instruction needs to be ignored later in translation, in the # same way that `addiu $sp, $sp, N` is ignored in handle_addi_real assert isinstance(inst.args[2], Register) info.allocated_stack_size = temp_reg_values[inst.args[2]] elif arch_mnemonic == "ppc:stwu" and inst.args[0] == arch.stack_pointer_reg: # Moving the stack pointer on PPC assert isinstance(inst.args[1], AsmAddressMode) assert isinstance(inst.args[1].lhs, AsmLiteral) info.allocated_stack_size = abs(inst.args[1].lhs.signed_value()) elif ( arch_mnemonic == "mips:move" and inst.args[0] == arch.frame_pointer_reg and inst.args[1] == arch.stack_pointer_reg ): # "move fp, sp" very likely means the code is compiled with frame # pointers enabled; thus fp should be treated the same as sp. info.uses_framepointer = True elif ( arch_mnemonic in [ "mips:sw", "mips:swc1", "mips:sdc1", "ppc:stw", "ppc:stmw", "ppc:stfd", "ppc:psq_st", ] and isinstance(inst.args[0], Register) and inst.args[0] in arch.saved_regs and isinstance(inst.args[1], AsmAddressMode) and inst.args[1].rhs == arch.stack_pointer_reg and ( inst.args[0] not in info.callee_save_regs or arch_mnemonic == "ppc:psq_st" ) ): # Initial saving of callee-save register onto the stack. if inst.args[0] in (arch.return_address_reg, Register("r0")): # Saving the return address on the stack. info.is_leaf = False # The registers & their stack accesses must be matched up in ArchAsm.parse for reg, mem in zip(inst.inputs, inst.outputs): if isinstance(reg, Register) and isinstance(mem, StackLocation): assert mem.symbolic_offset is None stack_offset = mem.offset if arch_mnemonic != "ppc:psq_st": # psq_st instructions store the same register as stfd, just # as packed singles instead. Prioritize the stfd. info.callee_save_regs.add(reg) callee_saved_offsets.append(stack_offset) elif arch_mnemonic == "ppc:mflr" and inst.args[0] == Register("r0"): info.is_leaf = False elif arch_mnemonic == "mips:li" and inst.args[0] in arch.temp_regs: assert isinstance(inst.args[0], Register) assert isinstance(inst.args[1], AsmLiteral) temp_reg_values[inst.args[0]] = inst.args[1].value elif ( arch_mnemonic == "mips:ori" and inst.args[0] == inst.args[1] and inst.args[0] in temp_reg_values ): assert isinstance(inst.args[0], Register) assert isinstance(inst.args[2], AsmLiteral) temp_reg_values[inst.args[0]] |= inst.args[2].value if not info.is_leaf: # Iterate over the whole function, not just the first basic block, # to estimate the boundary for the subroutine argument region info.subroutine_arg_top = info.allocated_stack_size for node in flow_graph.nodes: for inst in node.block.instructions: arch_mnemonic = inst.arch_mnemonic(arch) if ( arch_mnemonic in ["mips:lw", "mips:lwc1", "mips:ldc1", "ppc:lwz"] and isinstance(inst.args[1], AsmAddressMode) and inst.args[1].rhs == arch.stack_pointer_reg and inst.args[1].lhs_as_literal() >= 16 ): info.subroutine_arg_top = min( info.subroutine_arg_top, inst.args[1].lhs_as_literal() ) elif ( arch_mnemonic == "mips:addiu" and inst.args[0] != arch.stack_pointer_reg and inst.args[1] == arch.stack_pointer_reg and isinstance(inst.args[2], AsmLiteral) and inst.args[2].value < info.allocated_stack_size ): info.subroutine_arg_top = min( info.subroutine_arg_top, inst.args[2].value ) # Compute the bounds of the callee-saved register region, including padding if callee_saved_offsets: callee_saved_offsets.sort() bottom = callee_saved_offsets[0] # Both IDO & GCC save registers in two subregions: # (a) One for double-sized registers # (b) One for word-sized registers, padded to a multiple of 8 bytes # IDO has (a) lower than (b); GCC has (b) lower than (a) # Check that there are no gaps in this region, other than a single # 4-byte word between subregions. top = bottom internal_padding_added = False for offset in callee_saved_offsets: if offset != top: if not internal_padding_added and offset == top + 4: internal_padding_added = True else: raise DecompFailure( f"Gap in callee-saved word stack region. " f"Saved: {callee_saved_offsets}, " f"gap at: {offset} != {top}." ) top = offset + 4 info.callee_save_reg_region = (bottom, top) # Subroutine arguments must be at the very bottom of the stack, so they # must come after the callee-saved region info.subroutine_arg_top = min(info.subroutine_arg_top, bottom) # Use a struct to represent the stack layout. If the struct is provided in the context, # its fields will be used for variable types & names. stack_struct_name = f"_mips2c_stack_{function.name}" stack_struct = global_info.typepool.get_struct_by_tag_name( stack_struct_name, global_info.typemap ) if stack_struct is not None: if stack_struct.size != info.allocated_stack_size: raise DecompFailure( f"Function {function.name} has a provided stack type {stack_struct_name} " f"with size {stack_struct.size}, but the detected stack size was " f"{info.allocated_stack_size}." ) else: stack_struct = StructDeclaration.unknown( global_info.typepool, size=info.allocated_stack_size, tag_name=stack_struct_name, ) # Mark the struct as a stack struct so we never try to use a reference to the struct itself stack_struct.is_stack = True stack_struct.new_field_prefix = "sp" # This acts as the type of the $sp register info.stack_pointer_type = Type.ptr(Type.struct(stack_struct)) return info def format_hex(val: int) -> str: return format(val, "x").upper() def escape_byte(b: int) -> bytes: table = { b"\0": b"\\0", b"\b": b"\\b", b"\f": b"\\f", b"\n": b"\\n", b"\r": b"\\r", b"\t": b"\\t", b"\v": b"\\v", b"\\": b"\\\\", b'"': b'\\"', } bs = bytes([b]) if bs in table: return table[bs] if b < 0x20 or b in (0xFF, 0x7F): return f"\\x{b:02x}".encode("ascii") return bs @dataclass(eq=False) class Var: stack_info: StackInfo = field(repr=False) prefix: str num_usages: int = 0 name: Optional[str] = None def format(self, fmt: Formatter) -> str: if self.name is None: self.name = self.stack_info.temp_var(self.prefix) return self.name def __str__(self) -> str: return "<temp>" class Expression(abc.ABC): type: Type @abc.abstractmethod def dependencies(self) -> List["Expression"]: ... def use(self) -> None: for expr in self.dependencies(): expr.use() @abc.abstractmethod def format(self, fmt: Formatter) -> str: ... def __str__(self) -> str: fmt = Formatter(debug=True) return '"' + self.format(fmt) + '"' class Condition(Expression): @abc.abstractmethod def negated(self) -> "Condition": ... class Statement(abc.ABC): @abc.abstractmethod def should_write(self) -> bool: ... @abc.abstractmethod def format(self, fmt: Formatter) -> str: ... def __str__(self) -> str: fmt = Formatter(debug=True) return '"' + self.format(fmt) + '"' @dataclass(frozen=True, eq=False) class ErrorExpr(Condition): desc: Optional[str] = None type: Type = field(default_factory=Type.any_reg) def dependencies(self) -> List[Expression]: return [] def negated(self) -> "Condition": return self def format(self, fmt: Formatter) -> str: if self.desc is not None: return f"MIPS2C_ERROR({self.desc})" return "MIPS2C_ERROR()" @dataclass(frozen=True) class CommentExpr(Expression): expr: Expression type: Type = field(compare=False) prefix: Optional[str] = None suffix: Optional[str] = None def dependencies(self) -> List[Expression]: return [self.expr] def format(self, fmt: Formatter) -> str: expr_str = self.expr.format(fmt) if fmt.coding_style.comment_style == CodingStyle.CommentStyle.NONE: return expr_str prefix_str = f"/* {self.prefix} */ " if self.prefix is not None else "" suffix_str = f" /* {self.suffix} */" if self.suffix is not None else "" return f"{prefix_str}{expr_str}{suffix_str}" @staticmethod def wrap( expr: Expression, prefix: Optional[str] = None, suffix: Optional[str] = None ) -> Expression: if prefix is None and suffix is None: return expr return CommentExpr(expr=expr, type=expr.type, prefix=prefix, suffix=suffix) @dataclass(frozen=True, eq=False) class SecondF64Half(Expression): type: Type = field(default_factory=Type.any_reg) def dependencies(self) -> List[Expression]: return [] def format(self, fmt: Formatter) -> str: return "(second half of f64)" @dataclass(frozen=True, eq=False) class CarryBit(Expression): type: Type = field(default_factory=Type.intish) def dependencies(self) -> List[Expression]: return [] def format(self, fmt: Formatter) -> str: return "MIPS2C_CARRY" @staticmethod def add_to(expr: Expression) -> "BinaryOp": return fold_divmod(BinaryOp.intptr(expr, "+", CarryBit())) @staticmethod def sub_from(expr: Expression) -> "BinaryOp": return BinaryOp.intptr(expr, "-", UnaryOp("!", CarryBit(), type=Type.intish())) @dataclass(frozen=True, eq=False) class BinaryOp(Condition): left: Expression op: str right: Expression type: Type @staticmethod def int(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_intish(left), op=op, right=as_intish(right), type=Type.intish() ) @staticmethod def int64(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_int64(left), op=op, right=as_int64(right), type=Type.int64() ) @staticmethod def intptr(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_intptr(left), op=op, right=as_intptr(right), type=Type.intptr() ) @staticmethod def icmp(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_intptr(left), op=op, right=as_intptr(right), type=Type.bool() ) @staticmethod def scmp(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_sintish(left, silent=True), op=op, right=as_sintish(right, silent=True), type=Type.bool(), ) @staticmethod def sintptr_cmp(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_type(left, Type.sintptr(), False), op=op, right=as_type(right, Type.sintptr(), False), type=Type.bool(), ) @staticmethod def ucmp(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_uintish(left), op=op, right=as_uintish(right), type=Type.bool() ) @staticmethod def uintptr_cmp(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_type(left, Type.uintptr(), False), op=op, right=as_type(right, Type.uintptr(), False), type=Type.bool(), ) @staticmethod def fcmp(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_f32(left), op=op, right=as_f32(right), type=Type.bool(), ) @staticmethod def dcmp(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_f64(left), op=op, right=as_f64(right), type=Type.bool(), ) @staticmethod def sint( left: Expression, op: str, right: Expression, *, silent: bool = False ) -> "BinaryOp": return BinaryOp( left=as_sintish(left, silent=silent), op=op, right=as_sintish(right, silent=silent), type=Type.s32(), ) @staticmethod def uint(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_uintish(left), op=op, right=as_uintish(right), type=Type.u32() ) @staticmethod def s64(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp(left=as_s64(left), op=op, right=as_s64(right), type=Type.s64()) @staticmethod def u64(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp(left=as_u64(left), op=op, right=as_u64(right), type=Type.u64()) @staticmethod def f32(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_f32(left), op=op, right=as_f32(right), type=Type.f32(), ) @staticmethod def f64(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_f64(left), op=op, right=as_f64(right), type=Type.f64(), ) def is_comparison(self) -> bool: return self.op in ["==", "!=", ">", "<", ">=", "<="] def is_floating(self) -> bool: return self.left.type.is_float() and self.right.type.is_float() def negated(self) -> "Condition": if ( self.op in ["&&", "||"] and isinstance(self.left, Condition) and isinstance(self.right, Condition) ): # DeMorgan's Laws return BinaryOp( left=self.left.negated(), op={"&&": "||", "||": "&&"}[self.op], right=self.right.negated(), type=Type.bool(), ) if not self.is_comparison() or ( self.is_floating() and self.op in ["<", ">", "<=", ">="] ): return UnaryOp("!", self, type=Type.bool()) return BinaryOp( left=self.left, op={"==": "!=", "!=": "==", ">": "<=", "<": ">=", ">=": "<", "<=": ">"}[ self.op ], right=self.right, type=Type.bool(), ) def dependencies(self) -> List[Expression]: return [self.left, self.right] def format(self, fmt: Formatter) -> str: left_expr = late_unwrap(self.left) right_expr = late_unwrap(self.right) if ( self.is_comparison() and isinstance(left_expr, Literal) and not isinstance(right_expr, Literal) ): return BinaryOp( left=right_expr, op=self.op.translate(str.maketrans("<>", "><")), right=left_expr, type=self.type, ).format(fmt) if ( not self.is_floating() and isinstance(right_expr, Literal) and right_expr.value < 0 ): if self.op == "+": neg = Literal(value=-right_expr.value, type=right_expr.type) sub = BinaryOp(op="-", left=left_expr, right=neg, type=self.type) return sub.format(fmt) if self.op in ("&", "|"): neg = Literal(value=~right_expr.value, type=right_expr.type) right = UnaryOp("~", neg, type=Type.any_reg()) expr = BinaryOp(op=self.op, left=left_expr, right=right, type=self.type) return expr.format(fmt) lhs = left_expr.format(fmt) if ( isinstance(left_expr, BinaryOp) and left_expr.op == self.op and self.op in ASSOCIATIVE_OPS ): lhs = lhs[1:-1] if self.op in ("/", "%") and isinstance(right_expr, Literal): rhs = right_expr.format(fmt, force_dec=True) else: rhs = right_expr.format(fmt) if self.op in PSEUDO_FUNCTION_OPS: return f"{self.op}({lhs}, {rhs})" return f"({lhs} {self.op} {rhs})" @dataclass(frozen=True, eq=False) class TernaryOp(Expression): cond: Condition left: Expression right: Expression type: Type def dependencies(self) -> List[Expression]: return [self.cond, self.left, self.right] def format(self, fmt: Formatter) -> str: cond_str = simplify_condition(self.cond).format(fmt) left_str = self.left.format(fmt) right_str = self.right.format(fmt) return f"({cond_str} ? {left_str} : {right_str})" @dataclass(frozen=True, eq=False) class UnaryOp(Condition): op: str expr: Expression type: Type def dependencies(self) -> List[Expression]: return [self.expr] @staticmethod def sint(op: str, expr: Expression) -> "UnaryOp": expr = as_sintish(expr, silent=True) return UnaryOp( op=op, expr=expr, type=expr.type, ) def negated(self) -> "Condition": if self.op == "!" and isinstance(self.expr, (UnaryOp, BinaryOp)): return self.expr return UnaryOp("!", self, type=Type.bool()) def format(self, fmt: Formatter) -> str: # These aren't real operators (or functions); format them as a fn call if self.op in PSEUDO_FUNCTION_OPS: return f"{self.op}({self.expr.format(fmt)})" return f"{self.op}{self.expr.format(fmt)}" @dataclass(frozen=True, eq=False) class ExprCondition(Condition): expr: Expression type: Type is_negated: bool = False def dependencies(self) -> List[Expression]: return [self.expr] def negated(self) -> "Condition": return ExprCondition(self.expr, self.type, not self.is_negated) def format(self, fmt: Formatter) -> str: neg = "!" if self.is_negated else "" return f"{neg}{self.expr.format(fmt)}" @dataclass(frozen=True, eq=False) class CommaConditionExpr(Condition): statements: List["Statement"] condition: "Condition" type: Type = Type.bool() def dependencies(self) -> List[Expression]: assert False, "CommaConditionExpr should not be used within translate.py" return [] def negated(self) -> "Condition": return CommaConditionExpr(self.statements, self.condition.negated()) def format(self, fmt: Formatter) -> str: comma_joined = ", ".join( stmt.format(fmt).rstrip(";") for stmt in self.statements ) return f"({comma_joined}, {self.condition.format(fmt)})" @dataclass(frozen=True, eq=False) class Cast(Expression): expr: Expression type: Type reinterpret: bool = False silent: bool = True def dependencies(self) -> List[Expression]: return [self.expr] def use(self) -> None: self.expr.type.unify(self.type) super().use() def needed_for_store(self) -> bool: if not self.reinterpret: return True if not self.expr.type.unify(self.type): return True return False def is_trivial(self) -> bool: return ( self.reinterpret and self.expr.type.is_float() == self.type.is_float() and is_trivial_expression(self.expr) ) def format(self, fmt: Formatter) -> str: if self.reinterpret and self.expr.type.is_float() != self.type.is_float(): if fmt.valid_syntax: return ( f"MIPS2C_BITWISE({self.type.format(fmt)}, {self.expr.format(fmt)})" ) return f"(bitwise {self.type.format(fmt)}) {self.expr.format(fmt)}" if self.reinterpret and ( self.silent or (is_type_obvious(self.expr) and self.expr.type.unify(self.type)) ): return self.expr.format(fmt) if fmt.skip_casts: return self.expr.format(fmt) # Function casts require special logic because function calls have # higher precedence than casts fn_sig = self.type.get_function_pointer_signature() if fn_sig: prototype_sig = self.expr.type.get_function_pointer_signature() if not prototype_sig or not prototype_sig.unify_with_args(fn_sig): # A function pointer cast is required if the inner expr is not # a function pointer, or has incompatible argument types return f"(({self.type.format(fmt)}) {self.expr.format(fmt)})" if not prototype_sig.return_type.unify(fn_sig.return_type): # Only cast the return value of the call return f"({fn_sig.return_type.format(fmt)}) {self.expr.format(fmt)}" # No cast needed return self.expr.format(fmt) return f"({self.type.format(fmt)}) {self.expr.format(fmt)}" @dataclass(frozen=True, eq=False) class FuncCall(Expression): function: Expression args: List[Expression] type: Type def dependencies(self) -> List[Expression]: return self.args + [self.function] def format(self, fmt: Formatter) -> str: # TODO: The function type may have a different number of params than it had # when the FuncCall was created. Should we warn that there may be the wrong # number of arguments at this callsite? args = ", ".join(format_expr(arg, fmt) for arg in self.args) return f"{self.function.format(fmt)}({args})" @dataclass(frozen=True, eq=True) class LocalVar(Expression): value: int type: Type = field(compare=False) path: Optional[AccessPath] = field(compare=False) def dependencies(self) -> List[Expression]: return [] def format(self, fmt: Formatter) -> str: fallback_name = f"unksp{format_hex(self.value)}" if self.path is None: return fallback_name name = StructAccess.access_path_to_field_name(self.path, fmt) if name.startswith("->"): return name[2:] return fallback_name def toplevel_decl(self, fmt: Formatter) -> Optional[str]: # If len(self.path) > 2, then this local is an inner field of another # local, so it doesn't need to be declared. if ( self.path is None or len(self.path) != 2 or not isinstance(self.path[1], str) ): return None return self.type.to_decl(self.path[1], fmt) @dataclass(frozen=True, eq=False) class RegisterVar(Expression): reg: Register name: str type: Type def dependencies(self) -> List[Expression]: return [] def format(self, fmt: Formatter) -> str: return self.name @dataclass(frozen=True, eq=True) class PassedInArg(Expression): value: int copied: bool = field(compare=False) stack_info: StackInfo = field(compare=False, repr=False) type: Type = field(compare=False) def dependencies(self) -> List[Expression]: return [] def format(self, fmt: Formatter) -> str: assert self.value % 4 == 0 name = self.stack_info.get_param_name(self.value) return name or f"arg{format_hex(self.value // 4)}" @dataclass(frozen=True, eq=True) class SubroutineArg(Expression): value: int type: Type = field(compare=False) def dependencies(self) -> List[Expression]: return [] def format(self, fmt: Formatter) -> str: return f"subroutine_arg{format_hex(self.value // 4)}" @dataclass(eq=True, unsafe_hash=True) class StructAccess(Expression): # that may invalidate it. struct_var: Expression offset: int target_size: Optional[int] field_path: Optional[AccessPath] = field(compare=False) stack_info: Optional[StackInfo] = field(compare=False, repr=False) type: Type = field(compare=False) checked_late_field_path: bool = field(default=False, compare=False) def __post_init__(self) -> None: # stack_info is used to resolve field_path late assert ( self.stack_info is not None or self.field_path is not None ), "Must provide at least one of (stack_info, field_path)" self.assert_valid_field_path(self.field_path) @staticmethod def assert_valid_field_path(path: Optional[AccessPath]) -> None: assert path is None or ( path and isinstance(path[0], int) ), "The first element of the field path, if present, must be an int" @classmethod def access_path_to_field_name(cls, path: AccessPath, fmt: Formatter) -> str: cls.assert_valid_field_path(path) output = "" # Replace an initial "[0]." with "->" if len(path) >= 2 and path[0] == 0 and isinstance(path[1], str): output += f"->{path[1]}" path = path[2:] for p in path: if isinstance(p, str): output += f".{p}" elif isinstance(p, int): output += f"[{fmt.format_int(p)}]" else: static_assert_unreachable(p) return output def dependencies(self) -> List[Expression]: return [self.struct_var] def make_reference(self) -> Optional["StructAccess"]: field_path = self.late_field_path() if field_path and len(field_path) >= 2 and field_path[-1] == 0: return replace(self, field_path=field_path[:-1]) return None def late_field_path(self) -> Optional[AccessPath]: # If we didn't have a type at the time when the struct access was if self.field_path is None and not self.checked_late_field_path: var = late_unwrap(self.struct_var) var.format(Formatter()) field_path, field_type, _ = var.type.get_deref_field( self.offset, target_size=self.target_size ) if field_path is not None: self.assert_valid_field_path(field_path) self.field_path = field_path self.type.unify(field_type) self.checked_late_field_path = True return self.field_path def late_has_known_type(self) -> bool: if self.late_field_path() is not None: return True assert ( self.stack_info is not None ), "StructAccess must have stack_info if field_path isn't set" if self.offset == 0: var = late_unwrap(self.struct_var) if ( not self.stack_info.has_nonzero_access(var) and isinstance(var, AddressOf) and isinstance(var.expr, GlobalSymbol) and var.expr.type_provided ): return True return False def format(self, fmt: Formatter) -> str: var = late_unwrap(self.struct_var) has_nonzero_access = False if self.stack_info is not None: has_nonzero_access = self.stack_info.has_nonzero_access(var) field_path = self.late_field_path() if field_path is not None and field_path != [0]: has_nonzero_access = True elif fmt.valid_syntax and (self.offset != 0 or has_nonzero_access): offset_str = fmt.format_int(self.offset) return f"MIPS2C_FIELD({var.format(fmt)}, {Type.ptr(self.type).format(fmt)}, {offset_str})" else: prefix = "unk" + ("_" if fmt.coding_style.unknown_underscore else "") field_path = [0, prefix + format_hex(self.offset)] field_name = self.access_path_to_field_name(field_path, fmt) # Rewrite `(&x)->y` to `x.y` by stripping `AddressOf` & setting deref=False deref = True if ( isinstance(var, AddressOf) and not var.expr.type.is_array() and field_name.startswith("->") ): var = var.expr field_name = field_name.replace("->", ".", 1) deref = False # Rewrite `x->unk0` to `*x` and `x.unk0` to `x`, unless has_nonzero_access if self.offset == 0 and not has_nonzero_access: return f"{'*' if deref else ''}{var.format(fmt)}" return f"{parenthesize_for_struct_access(var, fmt)}{field_name}" @dataclass(frozen=True, eq=True) class ArrayAccess(Expression): # Represents ptr[index]. eq=True for symmetry with StructAccess. ptr: Expression index: Expression type: Type = field(compare=False) def dependencies(self) -> List[Expression]: return [self.ptr, self.index] def format(self, fmt: Formatter) -> str: base = parenthesize_for_struct_access(self.ptr, fmt) index = format_expr(self.index, fmt) return f"{base}[{index}]" @dataclass(eq=False) class GlobalSymbol(Expression): symbol_name: str type: Type asm_data_entry: Optional[AsmDataEntry] = None symbol_in_context: bool = False type_provided: bool = False initializer_in_typemap: bool = False demangled_str: Optional[str] = None def dependencies(self) -> List[Expression]: return [] def is_string_constant(self) -> bool: ent = self.asm_data_entry if not ent or not ent.is_string: return False return len(ent.data) == 1 and isinstance(ent.data[0], bytes) def format_string_constant(self, fmt: Formatter) -> str: assert self.is_string_constant(), "checked by caller" assert self.asm_data_entry and isinstance(self.asm_data_entry.data[0], bytes) has_trailing_null = False data = self.asm_data_entry.data[0] while data and data[-1] == 0: data = data[:-1] has_trailing_null = True data = b"".join(map(escape_byte, data)) strdata = data.decode("utf-8", "backslashreplace") ret = f'"{strdata}"' if not has_trailing_null: ret += " /* not null-terminated */" return ret def format(self, fmt: Formatter) -> str: return self.symbol_name def potential_array_dim(self, element_size: int) -> Tuple[int, int]: # If we don't have the .data/.rodata entry for this symbol, we can't guess # its array dimension. Jump tables are ignored and not treated as arrays. if self.asm_data_entry is None or self.asm_data_entry.is_jtbl: return 0, element_size min_data_size, max_data_size = self.asm_data_entry.size_range_bytes() if element_size > max_data_size: # The type is too big for the data (not an array) return 0, max_data_size # Check if it's possible that this symbol is not an array, and is just 1 element if min_data_size <= element_size <= max_data_size and not self.type.is_array(): return 1, 0 array_dim, extra_bytes = divmod(min_data_size, element_size) if extra_bytes != 0: # bytes from the padding, then indicate that in the return value. padding_bytes = element_size - extra_bytes if min_data_size + padding_bytes > max_data_size: return array_dim, extra_bytes # Include potential padding in the array. Although this is unlikely to match the original C, # it's much easier to manually remove all or some of these elements than to add them back in. return max_data_size // element_size, 0 @dataclass(frozen=True, eq=True) class Literal(Expression): value: int type: Type = field(compare=False, default_factory=Type.any) elide_cast: bool = field(compare=False, default=False) def dependencies(self) -> List[Expression]: return [] def format(self, fmt: Formatter, force_dec: bool = False) -> str: enum_name = self.type.get_enum_name(self.value) if enum_name is not None: return enum_name if self.type.is_likely_float(): if self.type.get_size_bits() == 64: return format_f64_imm(self.value) else: return format_f32_imm(self.value) + "f" if self.type.is_pointer() and self.value == 0: return "NULL" prefix = "" suffix = "" if not fmt.skip_casts and not self.elide_cast: if self.type.is_pointer(): prefix = f"({self.type.format(fmt)})" if self.type.is_unsigned(): suffix = "U" if force_dec: value = str(self.value) else: size_bits = self.type.get_size_bits() v = self.value if ( self.type.is_signed() and size_bits and v & (1 << (size_bits - 1)) and v > (3 << (size_bits - 2)) and v < 2 ** size_bits ): v -= 1 << size_bits value = fmt.format_int(v, size_bits=size_bits) return prefix + value + suffix def likely_partial_offset(self) -> bool: return self.value % 2 ** 15 in (0, 2 ** 15 - 1) and self.value < 0x1000000 @dataclass(frozen=True, eq=True) class AddressOf(Expression): expr: Expression type: Type = field(compare=False, default_factory=Type.ptr) def dependencies(self) -> List[Expression]: return [self.expr] def format(self, fmt: Formatter) -> str: if isinstance(self.expr, GlobalSymbol): if self.expr.is_string_constant(): return self.expr.format_string_constant(fmt) if self.expr.type.is_array(): return f"{self.expr.format(fmt)}" if self.expr.type.is_function(): return f"{self.expr.format(fmt)}" if isinstance(self.expr, StructAccess): ref = self.expr.make_reference() if ref: return f"{ref.format(fmt)}" return f"&{self.expr.format(fmt)}" @dataclass(frozen=True) class Lwl(Expression): load_expr: Expression key: Tuple[int, object] type: Type = field(compare=False, default_factory=Type.any_reg) def dependencies(self) -> List[Expression]: return [self.load_expr] def format(self, fmt: Formatter) -> str: return f"MIPS2C_LWL({self.load_expr.format(fmt)})" @dataclass(frozen=True) class Load3Bytes(Expression): load_expr: Expression type: Type = field(compare=False, default_factory=Type.any_reg) def dependencies(self) -> List[Expression]: return [self.load_expr] def format(self, fmt: Formatter) -> str: if fmt.valid_syntax: return f"MIPS2C_FIRST3BYTES({self.load_expr.format(fmt)})" return f"(first 3 bytes) {self.load_expr.format(fmt)}" @dataclass(frozen=True) class UnalignedLoad(Expression): load_expr: Expression type: Type = field(compare=False, default_factory=Type.any_reg) def dependencies(self) -> List[Expression]: return [self.load_expr] def format(self, fmt: Formatter) -> str: if fmt.valid_syntax: return f"MIPS2C_UNALIGNED32({self.load_expr.format(fmt)})" return f"(unaligned s32) {self.load_expr.format(fmt)}" @dataclass(frozen=False, eq=False) class EvalOnceExpr(Expression): wrapped_expr: Expression var: Var type: Type emit_exactly_once: bool trivial: bool forced_emit: bool = False num_usages: int = 0 def dependencies(self) -> List[Expression]: if self.need_decl(): return [] return [self.wrapped_expr] def use(self) -> None: self.num_usages += 1 if self.trivial or (self.num_usages == 1 and not self.emit_exactly_once): self.wrapped_expr.use() def force(self) -> None: # getting this wrong are pretty mild -- it just causes extraneous var # emission in rare cases. self.trivial = False self.forced_emit = True self.use() self.use() def need_decl(self) -> bool: return self.num_usages > 1 and not self.trivial def format(self, fmt: Formatter) -> str: if not self.need_decl(): return self.wrapped_expr.format(fmt) else: return self.var.format(fmt) @dataclass(frozen=False, eq=False) class PhiExpr(Expression): reg: Register node: Node type: Type used_phis: List["PhiExpr"] name: Optional[str] = None num_usages: int = 0 replacement_expr: Optional[Expression] = None used_by: Optional["PhiExpr"] = None def dependencies(self) -> List[Expression]: return [] def get_var_name(self) -> str: return self.name or f"unnamed-phi({self.reg.register_name})" def use(self, from_phi: Optional["PhiExpr"] = None) -> None: if self.num_usages == 0: self.used_phis.append(self) self.used_by = from_phi self.num_usages += 1 if self.used_by != from_phi: self.used_by = None if self.replacement_expr is not None: self.replacement_expr.use() def propagates_to(self) -> "PhiExpr": if self.used_by is None or self.replacement_expr is not None: return self return self.used_by.propagates_to() def format(self, fmt: Formatter) -> str: if self.replacement_expr: return self.replacement_expr.format(fmt) return self.get_var_name() @dataclass class SwitchControl: control_expr: Expression jump_table: Optional[GlobalSymbol] = None offset: int = 0 is_irregular: bool = False def matches_guard_condition(self, cond: Condition) -> bool: cmp_expr = simplify_condition(cond) if not isinstance(cmp_expr, BinaryOp) or cmp_expr.op not in (">=", ">"): return False cmp_exclusive = cmp_expr.op == ">" # The LHS may have been wrapped in a u32 cast left_expr = late_unwrap(cmp_expr.left) if isinstance(left_expr, Cast): left_expr = late_unwrap(left_expr.expr) if self.offset != 0: if ( not isinstance(left_expr, BinaryOp) or late_unwrap(left_expr.left) != late_unwrap(self.control_expr) or left_expr.op != "+" or late_unwrap(left_expr.right) != Literal(-self.offset) ): return False elif left_expr != late_unwrap(self.control_expr): return False right_expr = late_unwrap(cmp_expr.right) if ( self.jump_table is None or self.jump_table.asm_data_entry is None or not self.jump_table.asm_data_entry.is_jtbl or not isinstance(right_expr, Literal) ): return False # Count the number of labels (exclude padding bytes) jump_table_len = sum( isinstance(e, str) for e in self.jump_table.asm_data_entry.data ) return right_expr.value + int(cmp_exclusive) == jump_table_len @staticmethod def irregular_from_expr(control_expr: Expression) -> "SwitchControl": return SwitchControl( control_expr=control_expr, jump_table=None, offset=0, is_irregular=True, ) @staticmethod def from_expr(expr: Expression) -> "SwitchControl": # The "error" expression we use if we aren't able to parse `expr` error_expr = SwitchControl(expr) struct_expr = early_unwrap(expr) if not isinstance(struct_expr, StructAccess) or struct_expr.offset != 0: return error_expr add_expr = early_unwrap(struct_expr.struct_var) if not isinstance(add_expr, BinaryOp) or add_expr.op != "+": return error_expr left_expr, right_expr = early_unwrap(add_expr.left), early_unwrap( add_expr.right ) if isinstance(left_expr, AddressOf) and isinstance( left_expr.expr, GlobalSymbol ): jtbl_addr_expr, mul_expr = left_expr, right_expr elif isinstance(right_expr, AddressOf) and isinstance( right_expr.expr, GlobalSymbol ): mul_expr, jtbl_addr_expr = left_expr, right_expr else: return error_expr jump_table = jtbl_addr_expr.expr assert isinstance(jump_table, GlobalSymbol) if ( not isinstance(mul_expr, BinaryOp) or mul_expr.op != "*" or early_unwrap(mul_expr.right) != Literal(4) ): return error_expr control_expr = mul_expr.left offset = 0 uw_control_expr = early_unwrap(control_expr) if isinstance(uw_control_expr, BinaryOp) and uw_control_expr.op == "+": offset_lit = early_unwrap(uw_control_expr.right) if isinstance(offset_lit, Literal): control_expr = uw_control_expr.left offset = -offset_lit.value if jump_table.asm_data_entry is None or not jump_table.asm_data_entry.is_jtbl: return error_expr return SwitchControl(control_expr, jump_table, offset) @dataclass class EvalOnceStmt(Statement): expr: EvalOnceExpr def need_decl(self) -> bool: return self.expr.need_decl() def should_write(self) -> bool: if self.expr.emit_exactly_once: return self.expr.num_usages != 1 else: return self.need_decl() def format(self, fmt: Formatter) -> str: val_str = format_expr(elide_casts_for_store(self.expr.wrapped_expr), fmt) if self.expr.emit_exactly_once and self.expr.num_usages == 0: return f"{val_str};" return f"{self.expr.var.format(fmt)} = {val_str};" @dataclass class SetPhiStmt(Statement): phi: PhiExpr expr: Expression def should_write(self) -> bool: expr = self.expr if isinstance(expr, PhiExpr) and expr.propagates_to() != expr: assert expr.propagates_to() == self.phi.propagates_to() return False if late_unwrap(expr) == self.phi.propagates_to(): return False return True def format(self, fmt: Formatter) -> str: return format_assignment(self.phi.propagates_to(), self.expr, fmt) @dataclass class ExprStmt(Statement): expr: Expression def should_write(self) -> bool: return True def format(self, fmt: Formatter) -> str: return f"{format_expr(self.expr, fmt)};" @dataclass class StoreStmt(Statement): source: Expression dest: Expression def should_write(self) -> bool: return True def format(self, fmt: Formatter) -> str: dest = self.dest source = self.source if ( isinstance(dest, StructAccess) and dest.late_has_known_type() ) or isinstance(dest, (ArrayAccess, LocalVar, RegisterVar, SubroutineArg)): source = elide_casts_for_store(source) return format_assignment(dest, source, fmt) @dataclass class CommentStmt(Statement): contents: str def should_write(self) -> bool: return True def format(self, fmt: Formatter) -> str: return f"// {self.contents}" def error_stmt(msg: str) -> ExprStmt: return ExprStmt(ErrorExpr(msg)) @dataclass(frozen=True) class AddressMode: offset: int rhs: Register def __str__(self) -> str: if self.offset: return f"{self.offset}({self.rhs})" else: return f"({self.rhs})" @dataclass(frozen=True) class RawSymbolRef: offset: int sym: AsmGlobalSymbol def __str__(self) -> str: if self.offset: return f"{self.sym.symbol_name} + {self.offset}" else: return self.sym.symbol_name @dataclass class RegMeta: inherited: bool = False is_read: bool = False function_return: bool = False # function_return = True, or is a passed in argument uninteresting: bool = False # True if the regdata must be replaced by variable if it is ever read force: bool = False # True if the regdata was assigned by an Instruction marked as in_pattern; # it was part of a matched IR pattern but couldn't be elided at the time in_pattern: bool = False @dataclass class RegData: value: Expression meta: RegMeta @dataclass class RegInfo: stack_info: StackInfo = field(repr=False) contents: Dict[Register, RegData] = field(default_factory=dict) read_inherited: Set[Register] = field(default_factory=set) _active_instr: Optional[Instruction] = None def __getitem__(self, key: Register) -> Expression: if self._active_instr is not None and key not in self._active_instr.inputs: lineno = self._active_instr.meta.lineno return ErrorExpr(f"Read from unset register {key} on line {lineno}") if key == Register("zero"): return Literal(0) data = self.contents.get(key) if data is None: return ErrorExpr(f"Read from unset register {key}") ret = data.value data.meta.is_read = True if data.meta.inherited: self.read_inherited.add(key) if isinstance(ret, PassedInArg) and not ret.copied: val, arg = self.stack_info.get_argument(ret.value) self.stack_info.add_argument(arg) val.type.unify(ret.type) return val if data.meta.force: assert isinstance(ret, EvalOnceExpr) ret.force() return ret def __contains__(self, key: Register) -> bool: return key in self.contents def __setitem__(self, key: Register, value: Expression) -> None: self.set_with_meta(key, value, RegMeta()) def set_with_meta(self, key: Register, value: Expression, meta: RegMeta) -> None: if self._active_instr is not None and key not in self._active_instr.outputs: raise DecompFailure(f"Undeclared write to {key} in {self._active_instr}") self.unchecked_set_with_meta(key, value, meta) def unchecked_set_with_meta( self, key: Register, value: Expression, meta: RegMeta ) -> None: assert key != Register("zero") self.contents[key] = RegData(value, meta) def __delitem__(self, key: Register) -> None: assert key != Register("zero") del self.contents[key] def get_raw(self, key: Register) -> Optional[Expression]: data = self.contents.get(key) return data.value if data is not None else None def get_meta(self, key: Register) -> Optional[RegMeta]: data = self.contents.get(key) return data.meta if data is not None else None @contextmanager def current_instr(self, instr: Instruction) -> Iterator[None]: self._active_instr = instr try: with current_instr(instr): yield finally: self._active_instr = None def __str__(self) -> str: return ", ".join( f"{k}: {v.value}" for k, v in sorted(self.contents.items(), key=lambda x: x[0].register_name) if not self.stack_info.should_save(v.value, None) ) @dataclass class BlockInfo: to_write: List[Statement] return_value: Optional[Expression] switch_control: Optional[SwitchControl] branch_condition: Optional[Condition] final_register_states: RegInfo has_function_call: bool def __str__(self) -> str: newline = "\n\t" return "\n".join( [ f"Statements: {newline.join(str(w) for w in self.statements_to_write())}", f"Branch condition: {self.branch_condition}", f"Final register states: {self.final_register_states}", ] ) def statements_to_write(self) -> List[Statement]: return [st for st in self.to_write if st.should_write()] def get_block_info(node: Node) -> BlockInfo: ret = node.block.block_info assert isinstance(ret, BlockInfo) return ret @dataclass class InstrArgs: raw_args: List[Argument] regs: RegInfo = field(repr=False) stack_info: StackInfo = field(repr=False) def raw_arg(self, index: int) -> Argument: assert index >= 0 if index >= len(self.raw_args): raise DecompFailure( f"Too few arguments for instruction, expected at least {index + 1}" ) return self.raw_args[index] def reg_ref(self, index: int) -> Register: ret = self.raw_arg(index) if not isinstance(ret, Register): raise DecompFailure( f"Expected instruction argument to be a register, but found {ret}" ) return ret def imm_value(self, index: int) -> int: arg = self.full_imm(index) assert isinstance(arg, Literal) return arg.value def reg(self, index: int) -> Expression: return self.regs[self.reg_ref(index)] def dreg(self, index: int) -> Expression: reg = self.reg_ref(index) if not reg.is_float(): raise DecompFailure( f"Expected instruction argument {reg} to be a float register" ) ret = self.regs[reg] # PPC: FPR's hold doubles (64 bits), so we don't need to do anything special if self.stack_info.global_info.arch.arch == Target.ArchEnum.PPC: return ret # MIPS: Look at the paired FPR to get the full 64-bit value if not isinstance(ret, Literal) or ret.type.get_size_bits() == 64: return ret reg_num = int(reg.register_name[1:]) if reg_num % 2 != 0: raise DecompFailure( "Tried to use a double-precision instruction with odd-numbered float " f"register {reg}" ) other = self.regs[Register(f"f{reg_num+1}")] if not isinstance(other, Literal) or other.type.get_size_bits() == 64: raise DecompFailure( f"Unable to determine a value for double-precision register {reg} " "whose second half is non-static. This is a mips_to_c restriction " "which may be lifted in the future." ) value = ret.value | (other.value << 32) return Literal(value, type=Type.f64()) def cmp_reg(self, key: str) -> Condition: cond = self.regs[Register(key)] if not isinstance(cond, Condition): cond = BinaryOp.icmp(cond, "!=", Literal(0)) return cond def full_imm(self, index: int) -> Expression: arg = strip_macros(self.raw_arg(index)) ret = literal_expr(arg, self.stack_info) return ret def imm(self, index: int) -> Expression: ret = self.full_imm(index) if isinstance(ret, Literal): return Literal(((ret.value + 0x8000) & 0xFFFF) - 0x8000) return ret def unsigned_imm(self, index: int) -> Expression: ret = self.full_imm(index) if isinstance(ret, Literal): return Literal(ret.value & 0xFFFF) return ret def hi_imm(self, index: int) -> Argument: arg = self.raw_arg(index) if not isinstance(arg, Macro) or arg.macro_name not in ("hi", "ha", "h"): raise DecompFailure( f"Got lui/lis instruction with macro other than %hi/@ha/@h: {arg}" ) return arg.argument def shifted_imm(self, index: int) -> Expression: # TODO: Should this be part of hi_imm? Do we need to handle @ha? raw_imm = self.unsigned_imm(index) assert isinstance(raw_imm, Literal) return Literal(raw_imm.value << 16) def memory_ref(self, index: int) -> Union[AddressMode, RawSymbolRef]: ret = strip_macros(self.raw_arg(index)) # In MIPS, we want to allow "lw $v0, symbol + 4", which is outputted by # some disassemblers (like IDA) even though it isn't valid assembly. if isinstance(ret, AsmGlobalSymbol): return RawSymbolRef(offset=0, sym=ret) if ( isinstance(ret, BinOp) and ret.op in "+-" and isinstance(ret.lhs, AsmGlobalSymbol) and isinstance(ret.rhs, AsmLiteral) ): sign = 1 if ret.op == "+" else -1 return RawSymbolRef(offset=(ret.rhs.value * sign), sym=ret.lhs) if not isinstance(ret, AsmAddressMode): raise DecompFailure( "Expected instruction argument to be of the form offset($register), " f"but found {ret}" ) if not isinstance(ret.lhs, AsmLiteral): raise DecompFailure( f"Unable to parse offset for instruction argument {ret}. " "Expected a constant or a %lo macro." ) return AddressMode(offset=ret.lhs.signed_value(), rhs=ret.rhs) def count(self) -> int: return len(self.raw_args) def deref( arg: Union[AddressMode, RawSymbolRef, Expression], regs: RegInfo, stack_info: StackInfo, *, size: int, store: bool = False, ) -> Expression: if isinstance(arg, Expression): offset = 0 var = arg elif isinstance(arg, AddressMode): offset = arg.offset if stack_info.is_stack_reg(arg.rhs): return stack_info.get_stack_var(offset, store=store) var = regs[arg.rhs] else: offset = arg.offset var = stack_info.global_info.address_of_gsym(arg.sym.symbol_name) if isinstance(var, Literal) and var.value % (2 ** 16) == 0: var = Literal(var.value + offset, type=var.type) offset = 0 uw_var = early_unwrap(var) if isinstance(uw_var, BinaryOp) and uw_var.op == "+": for base, addend in [(uw_var.left, uw_var.right), (uw_var.right, uw_var.left)]: if isinstance(addend, Literal) and addend.likely_partial_offset(): offset += addend.value var = base uw_var = early_unwrap(var) break var.type.unify(Type.ptr()) stack_info.record_struct_access(var, offset) field_name: Optional[str] = None type: Type = stack_info.unique_type_for("struct", (uw_var, offset), Type.any()) array_expr = array_access_from_add( var, offset, stack_info, target_size=size, ptr=False ) if array_expr is not None: return array_expr field_path, field_type, _ = var.type.get_deref_field(offset, target_size=size) if field_path is not None: field_type.unify(type) type = field_type else: field_path = None return StructAccess( struct_var=var, offset=offset, target_size=size, field_path=field_path, stack_info=stack_info, type=type, ) def is_trivial_expression(expr: Expression) -> bool: if isinstance( expr, ( EvalOnceExpr, Literal, GlobalSymbol, LocalVar, PassedInArg, PhiExpr, RegisterVar, SubroutineArg, ), ): return True if isinstance(expr, AddressOf): return all(is_trivial_expression(e) for e in expr.dependencies()) if isinstance(expr, Cast): return expr.is_trivial() return False def is_type_obvious(expr: Expression) -> bool: if isinstance( expr, ( Cast, Literal, AddressOf, LocalVar, PhiExpr, PassedInArg, RegisterVar, FuncCall, ), ): return True if isinstance(expr, EvalOnceExpr): if expr.need_decl(): return True return is_type_obvious(expr.wrapped_expr) return False def simplify_condition(expr: Expression) -> Expression: if isinstance(expr, EvalOnceExpr) and not expr.need_decl(): return simplify_condition(expr.wrapped_expr) if isinstance(expr, UnaryOp): inner = simplify_condition(expr.expr) if expr.op == "!" and isinstance(inner, Condition): return inner.negated() return UnaryOp(expr=inner, op=expr.op, type=expr.type) if isinstance(expr, BinaryOp): left = simplify_condition(expr.left) right = simplify_condition(expr.right) if isinstance(left, BinaryOp) and left.is_comparison() and right == Literal(0): if expr.op == "==": return simplify_condition(left.negated()) if expr.op == "!=": return left if ( expr.is_comparison() and isinstance(left, Literal) and not isinstance(right, Literal) ): return BinaryOp( left=right, op=expr.op.translate(str.maketrans("<>", "><")), right=left, type=expr.type, ) return BinaryOp(left=left, op=expr.op, right=right, type=expr.type) return expr def balanced_parentheses(string: str) -> bool: bal = 0 for c in string: if c == "(": bal += 1 elif c == ")": if bal == 0: return False bal -= 1 return bal == 0 def format_expr(expr: Expression, fmt: Formatter) -> str: ret = expr.format(fmt) if ret.startswith("(") and balanced_parentheses(ret[1:-1]): return ret[1:-1] return ret def format_assignment(dest: Expression, source: Expression, fmt: Formatter) -> str: dest = late_unwrap(dest) source = late_unwrap(source) if isinstance(source, BinaryOp) and source.op in COMPOUND_ASSIGNMENT_OPS: rhs = None if late_unwrap(source.left) == dest: rhs = source.right elif late_unwrap(source.right) == dest and source.op in ASSOCIATIVE_OPS: rhs = source.left if rhs is not None: return f"{dest.format(fmt)} {source.op}= {format_expr(rhs, fmt)};" return f"{dest.format(fmt)} = {format_expr(source, fmt)};" def parenthesize_for_struct_access(expr: Expression, fmt: Formatter) -> str: s = expr.format(fmt) if ( s.startswith("*") or s.startswith("&") or (isinstance(expr, Cast) and expr.needed_for_store()) ): return f"({s})" return s def elide_casts_for_store(expr: Expression) -> Expression: uw_expr = late_unwrap(expr) if isinstance(uw_expr, Cast) and not uw_expr.needed_for_store(): return elide_casts_for_store(uw_expr.expr) if isinstance(uw_expr, Literal) and uw_expr.type.is_int(): return replace(uw_expr, elide_cast=True) return uw_expr def uses_expr(expr: Expression, expr_filter: Callable[[Expression], bool]) -> bool: if expr_filter(expr): return True for e in expr.dependencies(): if uses_expr(e, expr_filter): return True return False def late_unwrap(expr: Expression) -> Expression: if isinstance(expr, EvalOnceExpr) and not expr.need_decl(): return late_unwrap(expr.wrapped_expr) if isinstance(expr, PhiExpr) and expr.replacement_expr is not None: return late_unwrap(expr.replacement_expr) return expr def early_unwrap(expr: Expression) -> Expression: if ( isinstance(expr, EvalOnceExpr) and not expr.forced_emit and not expr.emit_exactly_once ): return early_unwrap(expr.wrapped_expr) return expr def early_unwrap_ints(expr: Expression) -> Expression: uw_expr = early_unwrap(expr) if isinstance(uw_expr, Cast) and uw_expr.reinterpret and uw_expr.type.is_int(): return early_unwrap_ints(uw_expr.expr) return uw_expr def unwrap_deep(expr: Expression) -> Expression: if isinstance(expr, EvalOnceExpr): return unwrap_deep(expr.wrapped_expr) return expr def literal_expr(arg: Argument, stack_info: StackInfo) -> Expression: if isinstance(arg, AsmGlobalSymbol): return stack_info.global_info.address_of_gsym(arg.symbol_name) if isinstance(arg, AsmLiteral): return Literal(arg.value) if isinstance(arg, BinOp): lhs = literal_expr(arg.lhs, stack_info) rhs = literal_expr(arg.rhs, stack_info) return BinaryOp.int(left=lhs, op=arg.op, right=rhs) raise DecompFailure(f"Instruction argument {arg} must be a literal") def imm_add_32(expr: Expression) -> Expression: if isinstance(expr, Literal): return as_intish(Literal(expr.value + 32)) else: return BinaryOp.int(expr, "+", Literal(32)) def fn_op(fn_name: str, args: List[Expression], type: Type) -> FuncCall: fn_sig = FunctionSignature( return_type=type, params=[FunctionParam(type=arg.type) for arg in args], params_known=True, is_variadic=False, ) return FuncCall( function=GlobalSymbol(symbol_name=fn_name, type=Type.function(fn_sig)), args=args, type=type, ) def void_fn_op(fn_name: str, args: List[Expression]) -> ExprStmt: fn_call = fn_op(fn_name, args, Type.any_reg()) fn_call.use() return ExprStmt(fn_call) def load_upper(args: InstrArgs) -> Expression: arg = args.raw_arg(1) if not isinstance(arg, Macro): assert not isinstance( arg, Literal ), "normalize_instruction should convert lui/lis <literal> to li" raise DecompFailure( f"lui/lis argument must be a literal or %hi/@ha macro, found {arg}" ) hi_arg = args.hi_imm(1) if ( isinstance(hi_arg, BinOp) and hi_arg.op in "+-" and isinstance(hi_arg.lhs, AsmGlobalSymbol) and isinstance(hi_arg.rhs, AsmLiteral) ): sym = hi_arg.lhs offset = hi_arg.rhs.value * (-1 if hi_arg.op == "-" else 1) elif isinstance(hi_arg, AsmGlobalSymbol): sym = hi_arg offset = 0 else: raise DecompFailure(f"Invalid %hi/@ha argument {hi_arg}") stack_info = args.stack_info source = stack_info.global_info.address_of_gsym(sym.symbol_name) imm = Literal(offset) return handle_addi_real(args.reg_ref(0), None, source, imm, stack_info) def handle_convert(expr: Expression, dest_type: Type, source_type: Type) -> Cast: silent = dest_type.data().kind != source_type.data().kind expr.type.unify(source_type) return Cast(expr=expr, type=dest_type, silent=silent, reinterpret=False) def handle_la(args: InstrArgs) -> Expression: target = args.memory_ref(1) stack_info = args.stack_info if isinstance(target, AddressMode): return handle_addi( InstrArgs( raw_args=[args.reg_ref(0), target.rhs, AsmLiteral(target.offset)], regs=args.regs, stack_info=args.stack_info, ) ) var = stack_info.global_info.address_of_gsym(target.sym.symbol_name) return add_imm(var, Literal(target.offset), stack_info) def handle_or(left: Expression, right: Expression) -> Expression: if left == right: return left if isinstance(left, Literal) and isinstance(right, Literal): if (((left.value & 0xFFFF) == 0 and (right.value & 0xFFFF0000) == 0)) or ( (right.value & 0xFFFF) == 0 and (left.value & 0xFFFF0000) == 0 ): return Literal(value=(left.value | right.value)) return BinaryOp.int(left=left, op="|", right=right) def handle_sltu(args: InstrArgs) -> Expression: right = args.reg(2) if args.reg_ref(1) == Register("zero"): uw_right = early_unwrap(right) if isinstance(uw_right, BinaryOp) and uw_right.op == "^": return BinaryOp.icmp(uw_right.left, "!=", uw_right.right) return BinaryOp.icmp(right, "!=", Literal(0)) else: left = args.reg(1) return BinaryOp.ucmp(left, "<", right) def handle_sltiu(args: InstrArgs) -> Expression: left = args.reg(1) right = args.imm(2) if isinstance(right, Literal): value = right.value & 0xFFFFFFFF if value == 1: uw_left = early_unwrap(left) if isinstance(uw_left, BinaryOp) and uw_left.op == "^": return BinaryOp.icmp(uw_left.left, "==", uw_left.right) return BinaryOp.icmp(left, "==", Literal(0)) else: right = Literal(value) return BinaryOp.ucmp(left, "<", right) def handle_addi(args: InstrArgs) -> Expression: stack_info = args.stack_info source_reg = args.reg_ref(1) source = args.reg(1) imm = args.imm(2) uw_source = early_unwrap(source) if ( isinstance(uw_source, BinaryOp) and uw_source.op == "+" and isinstance(uw_source.right, Literal) and uw_source.right.value % 0x10000 == 0 and isinstance(imm, Literal) ): return add_imm( uw_source.left, Literal(imm.value + uw_source.right.value), stack_info ) return handle_addi_real(args.reg_ref(0), source_reg, source, imm, stack_info) def handle_addis(args: InstrArgs) -> Expression: stack_info = args.stack_info source_reg = args.reg_ref(1) source = args.reg(1) imm = args.shifted_imm(2) return handle_addi_real(args.reg_ref(0), source_reg, source, imm, stack_info) def handle_addi_real( output_reg: Register, source_reg: Optional[Register], source: Expression, imm: Expression, stack_info: StackInfo, ) -> Expression: if source_reg is not None and stack_info.is_stack_reg(source_reg): assert isinstance(imm, Literal) if stack_info.is_stack_reg(output_reg): return source var = stack_info.get_stack_var(imm.value, store=False) if isinstance(var, LocalVar): stack_info.add_local_var(var) return AddressOf(var, type=var.type.reference()) else: return add_imm(source, imm, stack_info) def add_imm(source: Expression, imm: Expression, stack_info: StackInfo) -> Expression: if imm == Literal(0): return source elif source.type.is_pointer_or_array(): if isinstance(imm, Literal) and not imm.likely_partial_offset(): array_access = array_access_from_add( source, imm.value, stack_info, target_size=None, ptr=True ) if array_access is not None: return array_access field_path, field_type, _ = source.type.get_deref_field( imm.value, target_size=None ) if field_path is not None: return AddressOf( StructAccess( struct_var=source, offset=imm.value, target_size=None, field_path=field_path, stack_info=stack_info, type=field_type, ), type=field_type.reference(), ) if isinstance(imm, Literal): target = source.type.get_pointer_target() if target: target_size = target.get_size_bytes() if target_size and imm.value % target_size == 0: return BinaryOp( left=source, op="+", right=as_intish(imm), type=source.type ) return BinaryOp(left=source, op="+", right=as_intish(imm), type=Type.ptr()) elif isinstance(source, Literal) and isinstance(imm, Literal): return Literal(source.value + imm.value) else: return BinaryOp.intptr(left=source, op="+", right=imm) def handle_load(args: InstrArgs, type: Type) -> Expression: # Though really, it would be great to expose the load types somehow... size = type.get_size_bytes() assert size is not None expr = deref(args.memory_ref(1), args.regs, args.stack_info, size=size) # Detect rodata constants if isinstance(expr, StructAccess) and expr.offset == 0: target = early_unwrap(expr.struct_var) if ( isinstance(target, AddressOf) and isinstance(target.expr, GlobalSymbol) and type.is_likely_float() ): sym_name = target.expr.symbol_name ent = args.stack_info.global_info.asm_data_value(sym_name) if ( ent and ent.data and isinstance(ent.data[0], bytes) and len(ent.data[0]) >= size and ent.is_readonly and type.unify(target.expr.type) ): data = ent.data[0][:size] val: int if size == 4: (val,) = struct.unpack(">I", data) else: (val,) = struct.unpack(">Q", data) return Literal(value=val, type=type) return as_type(expr, type, silent=True) def deref_unaligned( arg: Union[AddressMode, RawSymbolRef], regs: RegInfo, stack_info: StackInfo, *, store: bool = False, ) -> Expression: # We don't know the correct size pass to deref. Passing None would signal that we return deref(arg, regs, stack_info, size=1, store=store) def handle_lwl(args: InstrArgs) -> Expression: # destination-first operation) ref = args.memory_ref(1) expr = deref_unaligned(ref, args.regs, args.stack_info) key: Tuple[int, object] if isinstance(ref, AddressMode): key = (ref.offset, args.regs[ref.rhs]) else: key = (ref.offset, ref.sym) return Lwl(expr, key) def handle_lwr(args: InstrArgs) -> Expression: # Unaligned load for the right part of a register. This lwr may merge with an # existing lwl, if it loads from the same target but with an offset that's +3. uw_old_value = early_unwrap(args.reg(0)) ref = args.memory_ref(1) lwl_key: Tuple[int, object] if isinstance(ref, AddressMode): lwl_key = (ref.offset - 3, args.regs[ref.rhs]) else: lwl_key = (ref.offset - 3, ref.sym) if isinstance(uw_old_value, Lwl) and uw_old_value.key[0] == lwl_key[0]: return UnalignedLoad(uw_old_value.load_expr) if ref.offset % 4 == 2: left_mem_ref = replace(ref, offset=ref.offset - 2) load_expr = deref_unaligned(left_mem_ref, args.regs, args.stack_info) return Load3Bytes(load_expr) return ErrorExpr("Unable to handle lwr; missing a corresponding lwl") def make_store(args: InstrArgs, type: Type) -> Optional[StoreStmt]: size = type.get_size_bytes() assert size is not None stack_info = args.stack_info source_reg = args.reg_ref(0) source_raw = args.regs.get_raw(source_reg) if type.is_likely_float() and size == 8: source_val = args.dreg(0) else: source_val = args.reg(0) target = args.memory_ref(1) is_stack = isinstance(target, AddressMode) and stack_info.is_stack_reg(target.rhs) if ( is_stack and source_raw is not None and stack_info.should_save(source_raw, target.offset) ): return None dest = deref(target, args.regs, stack_info, size=size, store=True) dest.type.unify(type) return StoreStmt(source=as_type(source_val, type, silent=is_stack), dest=dest) def make_storex(args: InstrArgs, type: Type) -> Optional[StoreStmt]: size = type.get_size_bytes() assert size is not None source = args.reg(0) ptr = BinaryOp.intptr(left=args.reg(1), op="+", right=args.reg(2)) dest = deref(ptr, args.regs, args.stack_info, size=size, store=True) dest.type.unify(type) return StoreStmt(source=as_type(source, type, silent=False), dest=dest) def handle_swl(args: InstrArgs) -> Optional[StoreStmt]: # swl in practice only occurs together with swr, so we can treat it as a regular # store, with the expression wrapped in UnalignedLoad if needed. source = args.reg(0) target = args.memory_ref(1) if not isinstance(early_unwrap(source), UnalignedLoad): source = UnalignedLoad(source) dest = deref_unaligned(target, args.regs, args.stack_info, store=True) return StoreStmt(source=source, dest=dest) def handle_swr(args: InstrArgs) -> Optional[StoreStmt]: expr = early_unwrap(args.reg(0)) target = args.memory_ref(1) if not isinstance(expr, Load3Bytes): # Elide swr's that don't come from 3-byte-loading lwr's; they probably return None real_target = replace(target, offset=target.offset - 2) dest = deref_unaligned(real_target, args.regs, args.stack_info, store=True) return StoreStmt(source=expr, dest=dest) def handle_sra(args: InstrArgs) -> Expression: lhs = args.reg(1) shift = args.imm(2) if isinstance(shift, Literal) and shift.value in [16, 24]: expr = early_unwrap(lhs) pow2 = 1 << shift.value if isinstance(expr, BinaryOp) and isinstance(expr.right, Literal): tp = Type.s16() if shift.value == 16 else Type.s8() rhs = expr.right.value if expr.op == "<<" and rhs == shift.value: return as_type(expr.left, tp, silent=False) elif expr.op == "<<" and rhs > shift.value: new_shift = fold_mul_chains( BinaryOp.int(expr.left, "<<", Literal(rhs - shift.value)) ) return as_type(new_shift, tp, silent=False) elif expr.op == "*" and rhs % pow2 == 0 and rhs != pow2: mul = BinaryOp.int(expr.left, "*", Literal(value=rhs // pow2)) return as_type(mul, tp, silent=False) return fold_divmod( BinaryOp(as_sintish(lhs), ">>", as_intish(shift), type=Type.s32()) ) def handle_conditional_move(args: InstrArgs, nonzero: bool) -> Expression: op = "!=" if nonzero else "==" type = Type.any_reg() return TernaryOp( BinaryOp.scmp(args.reg(2), op, Literal(0)), as_type(args.reg(1), type, silent=True), as_type(args.reg(0), type, silent=True), type, ) def format_f32_imm(num: int) -> str: packed = struct.pack(">I", num & (2 ** 32 - 1)) value = struct.unpack(">f", packed)[0] if not value or value == 4294967296.0: return str(value) if abs(math.log10(abs(value))) > 6.9: fmt_char = "e" elif abs(value) < 1: fmt_char = "f" else: fmt_char = "g" def fmt(prec: int) -> str: ret = ("{:." + str(prec) + fmt_char + "}").format(value) if fmt_char == "e": return ret.replace("e+", "e").replace("e0", "e").replace("e-0", "e-") if "e" in ret: # lead to us outputting numbers with more precision than we really have. return "0" return ret # 20 decimals is more than enough for a float. Start there, then try to shrink it. prec = 20 while prec > 0: prec -= 1 value2 = float(fmt(prec)) if struct.pack(">f", value2) != packed: prec += 1 break if prec == 20: # Uh oh, even the original value didn't format correctly. Fall back to str(), return str(value) ret = fmt(prec) if "." not in ret: ret += ".0" return ret def format_f64_imm(num: int) -> str: (value,) = struct.unpack(">d", struct.pack(">Q", num & (2 ** 64 - 1))) return str(value) def fold_divmod(original_expr: BinaryOp) -> BinaryOp: mult_high_ops = ("MULT_HI", "MULTU_HI") possible_match_ops = mult_high_ops + ("-", "+", ">>") if original_expr.is_floating() or original_expr.op not in possible_match_ops: return original_expr expr = original_expr left_expr = early_unwrap_ints(expr.left) right_expr = early_unwrap_ints(expr.right) divisor_shift = 0 if ( isinstance(left_expr, BinaryOp) and left_expr.op == ">>" and isinstance(left_expr.right, Literal) and expr.op == "+" and isinstance(right_expr, CarryBit) ): new_denom = 1 << left_expr.right.value return BinaryOp.sint( left=left_expr.left, op="/", right=Literal(new_denom), silent=True, ) if ( isinstance(left_expr, BinaryOp) and left_expr.op == "/" and isinstance(left_expr.right, Literal) and expr.op == ">>" and isinstance(right_expr, Literal) ): new_denom = left_expr.right.value << right_expr.value if new_denom < (1 << 32): return BinaryOp.int( left=left_expr.left, op="/", right=Literal(new_denom), ) if expr.op == "-" and isinstance(right_expr, BinaryOp) and right_expr.op == "*": div_expr = early_unwrap_ints(right_expr.left) mod_base = early_unwrap_ints(right_expr.right) if ( isinstance(div_expr, BinaryOp) and early_unwrap_ints(div_expr.left) == left_expr ): divisor = early_unwrap_ints(div_expr.right) if (div_expr.op == "/" and divisor == mod_base) or ( div_expr.op == ">>" and isinstance(divisor, Literal) and isinstance(mod_base, Literal) and (1 << divisor.value) == mod_base.value ): return BinaryOp.int(left=left_expr, op="%", right=right_expr.right) if ( expr.op == "-" and isinstance(left_expr, BinaryOp) and left_expr.op == ">>" and early_unwrap_ints(left_expr.right) == Literal(31) and isinstance(right_expr, BinaryOp) and right_expr.op == "/" and isinstance(right_expr.right, Literal) ): left_expr, right_expr = ( replace(right_expr, right=Literal(-right_expr.right.value)), left_expr, ) if ( expr.op == "+" and isinstance(left_expr, BinaryOp) and left_expr.op == "/" and isinstance(left_expr.right, Literal) and left_expr.right.value <= (1 << 29) and isinstance(right_expr, BinaryOp) and early_unwrap_ints(right_expr.left) == left_expr and right_expr.op == ">>" and early_unwrap_ints(right_expr.right) == Literal(31) ): return left_expr if ( expr.op == "-" and isinstance(left_expr, BinaryOp) and left_expr.op == "/" and isinstance(left_expr.right, Literal) and isinstance(right_expr, BinaryOp) and right_expr.op == ">>" and early_unwrap_ints(right_expr.right) == Literal(31) ): div_expr = left_expr shift_var_expr = early_unwrap_ints(right_expr.left) div_var_expr = early_unwrap_ints(div_expr.left) if div_var_expr == shift_var_expr: if isinstance(div_expr.right, Literal) and div_expr.right.value >= ( 1 << 30 ): return BinaryOp.int( left=div_expr.left, op=div_expr.op, right=div_expr.right, ) return div_expr # If the var is under 32 bits, the error term may look like `(x << K) >> 31` instead if ( isinstance(shift_var_expr, BinaryOp) and early_unwrap_ints(div_expr.left) == early_unwrap_ints(shift_var_expr.left) and shift_var_expr.op == "<<" and isinstance(shift_var_expr.right, Literal) ): return div_expr # Shift on the result of the mul: MULT_HI(x, N) >> M, shift the divisor by M if ( isinstance(left_expr, BinaryOp) and expr.op == ">>" and isinstance(right_expr, Literal) ): divisor_shift += right_expr.value expr = left_expr left_expr = early_unwrap_ints(expr.left) right_expr = early_unwrap_ints(expr.right) # Normalize MULT_HI(N, x) to MULT_HI(x, N) if isinstance(left_expr, Literal) and not isinstance(right_expr, Literal): left_expr, right_expr = right_expr, left_expr # Remove inner addition: (MULT_HI(x, N) + x) >> M --> MULT_HI(x, N) >> M # MULT_HI performs signed multiplication, so the `+ x` acts as setting the 32nd bit # while having a result with the same sign as x. # We can ignore it because `round_div` can work with arbitrarily large constants if ( isinstance(left_expr, BinaryOp) and left_expr.op == "MULT_HI" and expr.op == "+" and early_unwrap_ints(left_expr.left) == right_expr ): expr = left_expr left_expr = early_unwrap_ints(expr.left) right_expr = early_unwrap_ints(expr.right) # Shift on the LHS of the mul: MULT_HI(x >> M, N) --> MULT_HI(x, N) >> M if ( expr.op in mult_high_ops and isinstance(left_expr, BinaryOp) and left_expr.op == ">>" and isinstance(left_expr.right, Literal) ): divisor_shift += left_expr.right.value left_expr = early_unwrap_ints(left_expr.left) # Instead of checking for the error term precisely, just check that # the quotient is "close enough" to the integer value def round_div(x: int, y: int) -> Optional[int]: if y <= 1: return None result = round(x / y) if x / (y + 1) <= result <= x / (y - 1): return result return None if expr.op in mult_high_ops and isinstance(right_expr, Literal): denom = round_div(1 << (32 + divisor_shift), right_expr.value) if denom is not None: return BinaryOp.int( left=left_expr, op="/", right=Literal(denom), ) return original_expr def replace_clz_shift(expr: BinaryOp) -> BinaryOp: # Check that the outer expression is `>>` if expr.is_floating() or expr.op != ">>": return expr # Match `CLZ(x) >> 5`, or return the original expr left_expr = early_unwrap_ints(expr.left) right_expr = early_unwrap_ints(expr.right) if not ( isinstance(left_expr, UnaryOp) and left_expr.op == "CLZ" and isinstance(right_expr, Literal) and right_expr.value == 5 ): return expr # If the inner `x` is `(a - b)`, return `a == b` sub_expr = early_unwrap(left_expr.expr) if ( isinstance(sub_expr, BinaryOp) and not sub_expr.is_floating() and sub_expr.op == "-" ): return BinaryOp.icmp(sub_expr.left, "==", sub_expr.right) return BinaryOp.icmp(left_expr.expr, "==", Literal(0, type=left_expr.expr.type)) def replace_bitand(expr: BinaryOp) -> Expression: if not expr.is_floating() and expr.op == "&": if expr.right == Literal(0xFF): return as_type(expr.left, Type.int_of_size(8), silent=False) if expr.right == Literal(0xFFFF): return as_type(expr.left, Type.int_of_size(16), silent=False) return expr def fold_mul_chains(expr: Expression) -> Expression: def fold( expr: Expression, toplevel: bool, allow_sll: bool ) -> Tuple[Expression, int]: if isinstance(expr, BinaryOp): lbase, lnum = fold(expr.left, False, (expr.op != "<<")) rbase, rnum = fold(expr.right, False, (expr.op != "<<")) if expr.op == "<<" and isinstance(expr.right, Literal) and allow_sll: # Left-shifts by small numbers are easier to understand if # written as multiplications (they compile to the same thing). if toplevel and lnum == 1 and not (1 <= expr.right.value <= 4): return (expr, 1) return (lbase, lnum << expr.right.value) if ( expr.op == "*" and isinstance(expr.right, Literal) and (allow_sll or expr.right.value % 2 != 0) ): return (lbase, lnum * expr.right.value) if early_unwrap(lbase) == early_unwrap(rbase): if expr.op == "+": return (lbase, lnum + rnum) if expr.op == "-": return (lbase, lnum - rnum) if isinstance(expr, UnaryOp) and expr.op == "-" and not toplevel: base, num = fold(expr.expr, False, True) return (base, -num) if ( isinstance(expr, EvalOnceExpr) and not expr.emit_exactly_once and not expr.forced_emit ): base, num = fold(early_unwrap(expr), False, allow_sll) if num != 1 and is_trivial_expression(base): return (base, num) return (expr, 1) base, num = fold(expr, True, True) if num == 1: return expr return BinaryOp.int(left=base, op="*", right=Literal(num)) def array_access_from_add( expr: Expression, offset: int, stack_info: StackInfo, *, target_size: Optional[int], ptr: bool, ) -> Optional[Expression]: expr = early_unwrap(expr) if not isinstance(expr, BinaryOp) or expr.op != "+": return None base = expr.left addend = expr.right if addend.type.is_pointer_or_array() and not base.type.is_pointer_or_array(): base, addend = addend, base index: Expression scale: int uw_addend = early_unwrap(addend) if ( isinstance(uw_addend, BinaryOp) and uw_addend.op == "*" and isinstance(uw_addend.right, Literal) ): index = uw_addend.left scale = uw_addend.right.value elif ( isinstance(uw_addend, BinaryOp) and uw_addend.op == "<<" and isinstance(uw_addend.right, Literal) ): index = uw_addend.left scale = 1 << uw_addend.right.value else: index = addend scale = 1 if scale < 0: scale = -scale index = UnaryOp.sint("-", index) target_type = base.type.get_pointer_target() if target_type is None: return None uw_base = early_unwrap(base) typepool = stack_info.global_info.typepool # In `&x + index * scale`, if the type of `x` is not known, try to mark it as an array. # Skip the `scale = 1` case because this often indicates a complex `index` expression, # and is not actually a 1-byte array lookup. if ( scale > 1 and offset == 0 and isinstance(uw_base, AddressOf) and target_type.get_size_bytes() is None ): inner_type: Optional[Type] = None if ( isinstance(uw_base.expr, GlobalSymbol) and uw_base.expr.potential_array_dim(scale)[1] != 0 ): # For GlobalSymbols, use the size of the asm data to check the feasibility of being # an array with `scale`. This helps be more conservative around fake symbols. pass elif scale == 2: # This *could* be a struct, but is much more likely to be an int inner_type = Type.int_of_size(16) elif scale == 4: inner_type = Type.reg32(likely_float=False) elif typepool.unk_inference and isinstance(uw_base.expr, GlobalSymbol): # Make up a struct with a tag name based on the symbol & struct size. # Although `scale = 8` could indicate an array of longs/doubles, it seems more # common to be an array of structs. struct_name = f"_struct_{uw_base.expr.symbol_name}_0x{scale:X}" struct = typepool.get_struct_by_tag_name( struct_name, stack_info.global_info.typemap ) if struct is None: struct = StructDeclaration.unknown( typepool, size=scale, tag_name=struct_name ) elif struct.size != scale: # This should only happen if there was already a struct with this name in the context raise DecompFailure(f"sizeof(struct {struct_name}) != {scale:#x}") inner_type = Type.struct(struct) if inner_type is not None: # This might fail, if `uw_base.expr.type` can't be changed to an array uw_base.expr.type.unify(Type.array(inner_type, dim=None)) target_type.unify(inner_type) if target_type.get_size_bytes() == scale: pass else: sub_path, sub_type, remaining_offset = base.type.get_deref_field( offset, target_size=scale, exact=False ) if sub_path is None or len(sub_path) < 2 or sub_path[-1] != 0: return None sub_path.pop() base = StructAccess( struct_var=base, offset=offset - remaining_offset, target_size=None, field_path=sub_path, stack_info=stack_info, type=sub_type, ) offset = remaining_offset target_type = sub_type ret: Expression = ArrayAccess(base, index, type=target_type) ret_ref = AddressOf(ret, type=ret.type.reference()) field_path, field_type, _ = ret_ref.type.get_deref_field( offset, target_size=target_size ) if offset != 0 or (target_size is not None and target_size != scale): ret = StructAccess( struct_var=ret_ref, offset=offset, target_size=target_size, field_path=field_path, stack_info=stack_info, type=field_type, ) if ptr: ret = AddressOf(ret, type=ret.type.reference()) return ret def handle_add(args: InstrArgs) -> Expression: lhs = args.reg(1) rhs = args.reg(2) stack_info = args.stack_info type = Type.intptr() # If they are, treat them the same as pointers anyways. if lhs.type.is_pointer_or_array(): type = Type.ptr() elif rhs.type.is_pointer_or_array(): type = Type.ptr() # addiu instructions can sometimes be emitted as addu instead, when the # offset is too large. if isinstance(rhs, Literal): return handle_addi_real(args.reg_ref(0), args.reg_ref(1), lhs, rhs, stack_info) if isinstance(lhs, Literal): return handle_addi_real(args.reg_ref(0), args.reg_ref(2), rhs, lhs, stack_info) expr = BinaryOp(left=as_intptr(lhs), op="+", right=as_intptr(rhs), type=type) folded_expr = fold_mul_chains(expr) if isinstance(folded_expr, BinaryOp): folded_expr = fold_divmod(folded_expr) if folded_expr is not expr: return folded_expr array_expr = array_access_from_add(expr, 0, stack_info, target_size=None, ptr=True) if array_expr is not None: return array_expr return expr def handle_add_float(args: InstrArgs) -> Expression: if args.reg_ref(1) == args.reg_ref(2): two = Literal(1 << 30, type=Type.f32()) return BinaryOp.f32(two, "*", args.reg(1)) return BinaryOp.f32(args.reg(1), "+", args.reg(2)) def handle_add_double(args: InstrArgs) -> Expression: if args.reg_ref(1) == args.reg_ref(2): two = Literal(1 << 62, type=Type.f64()) return BinaryOp.f64(two, "*", args.dreg(1)) return BinaryOp.f64(args.dreg(1), "+", args.dreg(2)) def handle_bgez(args: InstrArgs) -> Condition: expr = args.reg(0) uw_expr = early_unwrap(expr) if ( isinstance(uw_expr, BinaryOp) and uw_expr.op == "<<" and isinstance(uw_expr.right, Literal) ): shift = uw_expr.right.value bitand = BinaryOp.int(uw_expr.left, "&", Literal(1 << (31 - shift))) return UnaryOp("!", bitand, type=Type.bool()) return BinaryOp.scmp(expr, ">=", Literal(0)) def rlwi_mask(mask_begin: int, mask_end: int) -> int: # Compute the mask constant used by the rlwi* family of PPC instructions, # referred to as the `MASK(MB, ME)` function in the processor manual. # Bit 0 is the MSB, Bit 31 is the LSB bits_upto: Callable[[int], int] = lambda m: (1 << (32 - m)) - 1 all_ones = 0xFFFFFFFF if mask_begin <= mask_end: # Set bits inside the range, fully inclusive mask = bits_upto(mask_begin) - bits_upto(mask_end + 1) else: # Set bits from [31, mask_end] and [mask_begin, 0] mask = (bits_upto(mask_end + 1) - bits_upto(mask_begin)) ^ all_ones return mask def handle_rlwinm( source: Expression, shift: int, mask_begin: int, mask_end: int, simplify: bool = True, ) -> Expression: # TODO: Detect shift + truncate, like `(x << 2) & 0xFFF3` or `(x >> 2) & 0x3FFF` # The output of the rlwinm instruction is `ROTL(source, shift) & mask`. We write this as # ((source << shift) & mask) | ((source >> (32 - shift)) & mask) # and compute both OR operands (upper_bits and lower_bits respectively). all_ones = 0xFFFFFFFF mask = rlwi_mask(mask_begin, mask_end) left_shift = shift right_shift = 32 - shift left_mask = (all_ones << left_shift) & mask right_mask = (all_ones >> right_shift) & mask # We only simplify if the `simplify` argument is True, and there will be no `|` in the # resulting expression. If there is an `|`, the expression is best left as bitwise math simplify = simplify and not (left_mask and right_mask) if isinstance(source, Literal): upper_value = (source.value << left_shift) & mask lower_value = (source.value >> right_shift) & mask return Literal(upper_value | lower_value) upper_bits: Optional[Expression] if left_mask == 0: upper_bits = None else: upper_bits = source if left_shift != 0: upper_bits = BinaryOp.int( left=upper_bits, op="<<", right=Literal(left_shift) ) if simplify: upper_bits = fold_mul_chains(upper_bits) if left_mask != (all_ones << left_shift) & all_ones: upper_bits = BinaryOp.int(left=upper_bits, op="&", right=Literal(left_mask)) if simplify: upper_bits = replace_bitand(upper_bits) lower_bits: Optional[Expression] if right_mask == 0: lower_bits = None else: lower_bits = BinaryOp.uint(left=source, op=">>", right=Literal(right_shift)) if simplify: lower_bits = replace_clz_shift(fold_divmod(lower_bits)) if right_mask != (all_ones >> right_shift) & all_ones: lower_bits = BinaryOp.int( left=lower_bits, op="&", right=Literal(right_mask) ) if simplify: lower_bits = replace_bitand(lower_bits) if upper_bits is None and lower_bits is None: return Literal(0) elif upper_bits is None: assert lower_bits is not None return lower_bits elif lower_bits is None: return upper_bits else: return BinaryOp.int(left=upper_bits, op="|", right=lower_bits) def handle_rlwimi( base: Expression, source: Expression, shift: int, mask_begin: int, mask_end: int ) -> Expression: # This instruction reads from `base`, replaces some bits with values from `source`, then # writes the result back into the first register. This can be used to copy any contiguous # bitfield from `source` into `base`, and is commonly used when manipulating flags, such # as in `x |= 0x10` or `x &= ~0x10`. # It's generally more readable to write the mask with `~` (instead of computing the inverse here) mask_literal = Literal(rlwi_mask(mask_begin, mask_end)) mask = UnaryOp("~", mask_literal, type=Type.u32()) masked_base = BinaryOp.int(left=base, op="&", right=mask) if source == Literal(0): return masked_base inserted = handle_rlwinm(source, shift, mask_begin, mask_end, simplify=False) if inserted == mask_literal: return BinaryOp.int(left=base, op="|", right=inserted) return BinaryOp.int(left=masked_base, op="|", right=inserted) def handle_loadx(args: InstrArgs, type: Type) -> Expression: size = type.get_size_bytes() assert size is not None ptr = BinaryOp.intptr(left=args.reg(1), op="+", right=args.reg(2)) expr = deref(ptr, args.regs, args.stack_info, size=size) return as_type(expr, type, silent=True) def strip_macros(arg: Argument) -> Argument: if isinstance(arg, Macro): if arg.macro_name in ["sda2", "sda21"]: return arg.argument if arg.macro_name == "hi": raise DecompFailure("%hi macro outside of lui") if arg.macro_name not in ["lo", "l"]: raise DecompFailure(f"Unrecognized linker macro %{arg.macro_name}") if isinstance(arg.argument, AsmLiteral): return AsmLiteral(arg.argument.value) return AsmLiteral(0) elif isinstance(arg, AsmAddressMode) and isinstance(arg.lhs, Macro): if arg.lhs.macro_name in ["sda2", "sda21"]: return arg.lhs.argument if arg.lhs.macro_name not in ["lo", "l"]: raise DecompFailure( f"Bad linker macro in instruction argument {arg}, expected %lo" ) return AsmAddressMode(lhs=AsmLiteral(0), rhs=arg.rhs) else: return arg @dataclass class AbiArgSlot: offset: int reg: Optional[Register] type: Type name: Optional[str] = None comment: Optional[str] = None @dataclass class Abi: arg_slots: List[AbiArgSlot] possible_slots: List[AbiArgSlot] def reg_always_set(node: Node, reg: Register, *, dom_set: bool) -> bool: if node.immediate_dominator is None: return False seen = {node.immediate_dominator} stack = node.parents[:] while stack: n = stack.pop() if n == node.immediate_dominator and not dom_set: return False if n in seen: continue seen.add(n) clobbered: Optional[bool] = None for instr in n.block.instructions: with current_instr(instr): if reg in instr.outputs: clobbered = False elif reg in instr.clobbers: clobbered = True if clobbered == True: return False if clobbered is None: stack.extend(n.parents) return True def pick_phi_assignment_nodes( reg: Register, nodes: List[Node], expr: Expression ) -> List[Node]: dominators = sorted( set.intersection(*(node.dominators for node in nodes)), key=lambda n: len(n.dominators), ) for node in dominators: regs = get_block_info(node).final_register_states raw = regs.get_raw(reg) meta = regs.get_meta(reg) if raw is None or meta is None or meta.force: continue if raw == expr: return [node] # TODO: In some cases there may be a better solution (e.g. one that requires 2 nodes) return nodes def assign_phis(used_phis: List[PhiExpr], stack_info: StackInfo) -> None: i = 0 # Iterate over used phis until there are no more remaining. New ones may # appear during iteration, hence the while loop. while i < len(used_phis): phi = used_phis[i] assert phi.num_usages > 0 assert len(phi.node.parents) >= 2 # Group parent nodes by the value of their phi register equivalent_nodes: DefaultDict[Expression, List[Node]] = defaultdict(list) for node in phi.node.parents: expr = get_block_info(node).final_register_states[phi.reg] expr.type.unify(phi.type) equivalent_nodes[expr].append(node) exprs = list(equivalent_nodes.keys()) first_uw = early_unwrap(exprs[0]) if all(early_unwrap(e) == first_uw for e in exprs[1:]): # All the phis have the same value (e.g. because we recomputed an # expression after a store, or restored a register after a function # call). Just use that value instead of introducing a phi node. # TODO: the unwrapping here is necessary, but also kinda sketchy: # we may set as replacement_expr an expression that really shouldn't # prevent_later_uses machinery). phi.replacement_expr = as_type(first_uw, phi.type, silent=True) for _ in range(phi.num_usages): first_uw.use() else: for expr, nodes in equivalent_nodes.items(): for node in pick_phi_assignment_nodes(phi.reg, nodes, expr): block_info = get_block_info(node) expr = block_info.final_register_states[phi.reg] if isinstance(expr, PhiExpr): # Explicitly mark how the expression is used if it's a phi, expr.use(from_phi=phi) else: expr.use() typed_expr = as_type(expr, phi.type, silent=True) block_info.to_write.append(SetPhiStmt(phi, typed_expr)) i += 1 name_counter: Dict[Register, int] = {} for phi in used_phis: if not phi.replacement_expr and phi.propagates_to() == phi: counter = name_counter.get(phi.reg, 0) + 1 name_counter[phi.reg] = counter output_reg_name = stack_info.function.reg_formatter.format(phi.reg) prefix = f"phi_{output_reg_name}" phi.name = f"{prefix}_{counter}" if counter > 1 else prefix stack_info.phi_vars.append(phi) def propagate_register_meta(nodes: List[Node], reg: Register) -> None: non_terminal: List[Node] = [n for n in nodes if not isinstance(n, TerminalNode)] for n in non_terminal: if reg in get_block_info(n).final_register_states.read_inherited: for p in n.parents: par_meta = get_block_info(p).final_register_states.get_meta(reg) if par_meta: par_meta.is_read = True todo = non_terminal[:] while todo: n = todo.pop() meta = get_block_info(n).final_register_states.get_meta(reg) for p in n.parents: par_meta = get_block_info(p).final_register_states.get_meta(reg) if (par_meta and not par_meta.is_read) and ( meta and meta.inherited and meta.is_read ): par_meta.is_read = True todo.append(p) for n in non_terminal: meta = get_block_info(n).final_register_states.get_meta(reg) if meta: if meta.inherited: meta.uninteresting = True meta.function_return = True meta.in_pattern = True else: meta.uninteresting |= ( meta.is_read or meta.function_return or meta.in_pattern ) todo = non_terminal[:] while todo: n = todo.pop() if isinstance(n, TerminalNode): continue meta = get_block_info(n).final_register_states.get_meta(reg) if not meta or not meta.inherited: continue all_uninteresting = True all_function_return = True all_in_pattern = True for p in n.parents: par_meta = get_block_info(p).final_register_states.get_meta(reg) if par_meta: all_uninteresting &= par_meta.uninteresting all_function_return &= par_meta.function_return all_in_pattern &= par_meta.in_pattern if meta.uninteresting and not all_uninteresting and not meta.is_read: meta.uninteresting = False todo.extend(n.children()) if meta.function_return and not all_function_return: meta.function_return = False todo.extend(n.children()) if meta.in_pattern and not all_in_pattern: meta.in_pattern = False todo.extend(n.children()) def determine_return_register( return_blocks: List[BlockInfo], fn_decl_provided: bool, arch: Arch ) -> Optional[Register]: def priority(block_info: BlockInfo, reg: Register) -> int: meta = block_info.final_register_states.get_meta(reg) if not meta: return 4 if meta.uninteresting: return 2 if meta.in_pattern: return 1 if meta.function_return: return 0 return 3 if not return_blocks: return None best_reg: Optional[Register] = None best_prio = -1 for reg in arch.base_return_regs: prios = [priority(b, reg) for b in return_blocks] max_prio = max(prios) if max_prio == 4: continue if max_prio <= 2 and not fn_decl_provided: continue if max_prio > best_prio: best_prio = max_prio best_reg = reg return best_reg def translate_node_body(node: Node, regs: RegInfo, stack_info: StackInfo) -> BlockInfo: to_write: List[Union[Statement]] = [] local_var_writes: Dict[LocalVar, Tuple[Register, Expression]] = {} subroutine_args: Dict[int, Expression] = {} branch_condition: Optional[Condition] = None switch_expr: Optional[Expression] = None has_custom_return: bool = False has_function_call: bool = False in_pattern: bool = False arch = stack_info.global_info.arch def eval_once( expr: Expression, *, emit_exactly_once: bool, trivial: bool, prefix: str = "", reuse_var: Optional[Var] = None, ) -> EvalOnceExpr: if emit_exactly_once: expr.use() elif "_fictive_" in prefix and isinstance(expr, EvalOnceExpr): return expr assert reuse_var or prefix if prefix == "condition_bit": prefix = "cond" var = reuse_var or Var(stack_info, "temp_" + prefix) expr = EvalOnceExpr( wrapped_expr=expr, var=var, type=expr.type, emit_exactly_once=emit_exactly_once, trivial=trivial, ) var.num_usages += 1 stmt = EvalOnceStmt(expr) to_write.append(stmt) stack_info.temp_vars.append(stmt) return expr def prevent_later_uses(expr_filter: Callable[[Expression], bool]) -> None: for r in regs.contents.keys(): data = regs.contents.get(r) assert data is not None expr = data.value if not data.meta.force and expr_filter(expr): # Mark the register as "if used, emit the expression's once # var". We usually always have a once var at this point, if not isinstance(expr, EvalOnceExpr): expr = eval_once( expr, emit_exactly_once=False, trivial=False, prefix=stack_info.function.reg_formatter.format(r), ) # This write isn't changing the value of the register; it didn't need # to be declared as part of the current instruction's inputs/outputs. regs.unchecked_set_with_meta(r, expr, replace(data.meta, force=True)) def prevent_later_value_uses(sub_expr: Expression) -> None: # cause them to be incorrectly passed as function arguments -- the function # call logic sees an opaque wrapper and doesn't realize that they are unused prevent_later_uses( lambda e: uses_expr(e, lambda e2: e2 == sub_expr) and not (isinstance(e, PassedInArg) and not e.copied) ) def prevent_later_function_calls() -> None: prevent_later_uses(lambda e: uses_expr(e, lambda e2: isinstance(e2, FuncCall))) def prevent_later_reads() -> None: contains_read = lambda e: isinstance(e, (StructAccess, ArrayAccess)) prevent_later_uses(lambda e: uses_expr(e, contains_read)) def set_reg_maybe_return(reg: Register, expr: Expression) -> None: regs.set_with_meta(reg, expr, RegMeta(in_pattern=in_pattern)) def set_reg(reg: Register, expr: Optional[Expression]) -> Optional[Expression]: if expr is None: if reg in regs: del regs[reg] return None if isinstance(expr, LocalVar): if ( isinstance(node, ReturnNode) and stack_info.maybe_get_register_var(reg) and stack_info.in_callee_save_reg_region(expr.value) and reg in stack_info.callee_save_regs ): # matter in other cases). return None if expr in local_var_writes: # Elide register restores (only for the same register for now, # to be conversative). orig_reg, orig_expr = local_var_writes[expr] if orig_reg == reg: expr = orig_expr uw_expr = expr if not isinstance(expr, Literal): expr = eval_once( expr, emit_exactly_once=False, trivial=is_trivial_expression(expr), prefix=stack_info.function.reg_formatter.format(reg), ) if reg == Register("zero"): # Emit the expression as is. It's probably a volatile load. expr.use() to_write.append(ExprStmt(expr)) else: dest = stack_info.maybe_get_register_var(reg) if dest is not None: stack_info.use_register_var(dest) if not (isinstance(uw_expr, RegisterVar) and uw_expr.reg == reg): source = as_type(expr, dest.type, True) source.use() to_write.append(StoreStmt(source=source, dest=dest)) expr = dest set_reg_maybe_return(reg, expr) return expr def clear_caller_save_regs() -> None: for reg in arch.temp_regs: if reg in regs: del regs[reg] def maybe_clear_local_var_writes(func_args: List[Expression]) -> None: # Clear the `local_var_writes` dict if any of the `func_args` contain # a reference to a stack var. (The called function may modify the stack, # replacing the value we have in `local_var_writes`.) for arg in func_args: if uses_expr( arg, lambda expr: isinstance(expr, AddressOf) and isinstance(expr.expr, LocalVar), ): local_var_writes.clear() return def process_instr(instr: Instruction) -> None: nonlocal branch_condition, switch_expr, has_function_call, in_pattern in_pattern = instr.in_pattern mnemonic = instr.mnemonic arch_mnemonic = instr.arch_mnemonic(arch) args = InstrArgs(instr.args, regs, stack_info) expr: Expression # Figure out what code to generate! if mnemonic in arch.instrs_ignore: pass elif mnemonic in arch.instrs_store or mnemonic in arch.instrs_store_update: # Store a value in a permanent place. if mnemonic in arch.instrs_store: to_store = arch.instrs_store[mnemonic](args) else: # PPC specific store-and-update instructions # `stwu r3, 8(r4)` is equivalent to `$r3 = *($r4 + 8); $r4 += 8;` to_store = arch.instrs_store_update[mnemonic](args) # Update the register in the second argument update = args.memory_ref(1) if not isinstance(update, AddressMode): raise DecompFailure( f"Unhandled store-and-update arg in {instr}: {update!r}" ) set_reg( update.rhs, add_imm(args.regs[update.rhs], Literal(update.offset), stack_info), ) if to_store is None: # Elided register preserval. pass elif isinstance(to_store.dest, SubroutineArg): # About to call a subroutine with this argument. Skip arguments for the # first four stack slots; they are also passed in registers. if to_store.dest.value >= 0x10: subroutine_args[to_store.dest.value] = to_store.source else: if isinstance(to_store.dest, LocalVar): stack_info.add_local_var(to_store.dest) raw_value = to_store.source if isinstance(raw_value, Cast) and raw_value.reinterpret: # When preserving values on the stack across function calls, # ignore the type of the stack variable. The same stack slot # might be used to preserve values of different types. raw_value = raw_value.expr local_var_writes[to_store.dest] = (args.reg_ref(0), raw_value) # Emit a write. This includes four steps: # - mark the expression as used (since writes are always emitted) # - mark the dest used (if it's a struct access it needs to be # - mark other usages of the dest as "emit before this point if used". # - emit the actual write. # # Note that the prevent_later_value_uses step happens after use(), since # the stored expression is allowed to reference its destination var, # but before the write is written, since prevent_later_value_uses might # emit writes of its own that should go before this write. In practice # that probably never occurs -- all relevant register contents should be # EvalOnceExpr's that can be emitted at their point of creation, but to_store.source.use() to_store.dest.use() prevent_later_value_uses(to_store.dest) prevent_later_function_calls() to_write.append(to_store) elif mnemonic in arch.instrs_source_first: set_reg(args.reg_ref(1), arch.instrs_source_first[mnemonic](args)) elif mnemonic in arch.instrs_branches: assert branch_condition is None branch_condition = arch.instrs_branches[mnemonic](args) elif mnemonic in arch.instrs_float_branches: assert branch_condition is None cond_bit = regs[Register("condition_bit")] if not isinstance(cond_bit, BinaryOp): cond_bit = ExprCondition(cond_bit, type=cond_bit.type) if arch_mnemonic == "mips:bc1t": branch_condition = cond_bit elif arch_mnemonic == "mips:bc1f": branch_condition = cond_bit.negated() elif mnemonic in arch.instrs_jumps: if arch_mnemonic == "ppc:bctr": # Switch jump assert isinstance(node, SwitchNode) switch_expr = args.regs[Register("ctr")] elif arch_mnemonic == "mips:jr": # MIPS: if args.reg_ref(0) == arch.return_address_reg: # Return from the function. assert isinstance(node, ReturnNode) else: # Switch jump. assert isinstance(node, SwitchNode) switch_expr = args.reg(0) elif arch_mnemonic == "ppc:blr": assert isinstance(node, ReturnNode) else: assert False, f"Unhandled jump mnemonic {arch_mnemonic}" elif mnemonic in arch.instrs_fn_call: if arch_mnemonic in ["mips:jal", "ppc:bl"]: fn_target = args.imm(0) if not ( ( isinstance(fn_target, AddressOf) and isinstance(fn_target.expr, GlobalSymbol) ) or isinstance(fn_target, Literal) ): raise DecompFailure( f"Target of function call must be a symbol, not {fn_target}" ) elif arch_mnemonic == "ppc:blrl": fn_target = args.regs[Register("lr")] elif arch_mnemonic == "ppc:bctrl": fn_target = args.regs[Register("ctr")] elif arch_mnemonic == "mips:jalr": fn_target = args.reg(1) else: assert False, f"Unhandled fn call mnemonic {arch_mnemonic}" fn_target = as_function_ptr(fn_target) fn_sig = fn_target.type.get_function_pointer_signature() assert fn_sig is not None, "known function pointers must have a signature" likely_regs: Dict[Register, bool] = {} for reg, data in regs.contents.items(): # We use a much stricter filter for PPC than MIPS, because the same # registers can be used arguments & return values. # The ABI can also mix & match the rN & fN registers, which makes the # "require" heuristic less powerful. # # - `meta.inherited` will only be False for registers set in *this* basic block # - `meta.function_return` will only be accurate for registers set within this # basic block because we have not called `propagate_register_meta` yet. # Within this block, it will be True for registers that were return values. if arch.arch == Target.ArchEnum.PPC and ( data.meta.inherited or data.meta.function_return ): likely_regs[reg] = False elif data.meta.in_pattern: # Like `meta.function_return` mentioned above, `meta.in_pattern` will only be # accurate for registers set within this basic block. likely_regs[reg] = False elif isinstance(data.value, PassedInArg) and not data.value.copied: likely_regs[reg] = False else: likely_regs[reg] = True abi = arch.function_abi(fn_sig, likely_regs, for_call=True) func_args: List[Expression] = [] for slot in abi.arg_slots: if slot.reg: expr = regs[slot.reg] elif slot.offset in subroutine_args: expr = subroutine_args.pop(slot.offset) else: expr = ErrorExpr( f"Unable to find stack arg {slot.offset:#x} in block" ) func_args.append( CommentExpr.wrap( as_type(expr, slot.type, True), prefix=slot.comment ) ) for slot in abi.possible_slots: assert slot.reg is not None func_args.append(regs[slot.reg]) # Add the arguments after a3. # TODO: limit this based on abi.arg_slots. If the function type is known # and not variadic, this list should be empty. for _, arg in sorted(subroutine_args.items()): if fn_sig.params_known and not fn_sig.is_variadic: func_args.append(CommentExpr.wrap(arg, prefix="extra?")) else: func_args.append(arg) if not fn_sig.params_known: while len(func_args) > len(fn_sig.params): fn_sig.params.append(FunctionParam()) # When the function signature isn't provided, the we only assume that each # Without that assumption, the logic from `function_abi` would be needed here. for i, (arg_expr, param) in enumerate(zip(func_args, fn_sig.params)): func_args[i] = as_type(arg_expr, param.type.decay(), True) # Reset subroutine_args, for the next potential function call. subroutine_args.clear() call: Expression = FuncCall( fn_target, func_args, fn_sig.return_type.weaken_void_ptr() ) call = eval_once(call, emit_exactly_once=True, trivial=False, prefix="ret") # Clear out caller-save registers, for clarity and to ensure that # argument regs don't get passed into the next function. clear_caller_save_regs() maybe_clear_local_var_writes(func_args) # and then this prevention should also be... but it's the best we prevent_later_function_calls() prevent_later_reads() return_reg_vals = arch.function_return(call) for out in instr.outputs: if not isinstance(out, Register): continue val = return_reg_vals[out] if not isinstance(val, SecondF64Half): val = eval_once( val, emit_exactly_once=False, trivial=False, prefix=stack_info.function.reg_formatter.format(out), ) regs.set_with_meta(out, val, RegMeta(function_return=True)) has_function_call = True elif mnemonic in arch.instrs_float_comp: expr = arch.instrs_float_comp[mnemonic](args) regs[Register("condition_bit")] = expr elif mnemonic in arch.instrs_hi_lo: hi, lo = arch.instrs_hi_lo[mnemonic](args) set_reg(Register("hi"), hi) set_reg(Register("lo"), lo) elif mnemonic in arch.instrs_implicit_destination: reg, expr_fn = arch.instrs_implicit_destination[mnemonic] set_reg(reg, expr_fn(args)) elif mnemonic in arch.instrs_ppc_compare: if instr.args[0] != Register("cr0"): raise DecompFailure( f"Instruction {instr} not supported (first arg is not $cr0)" ) set_reg(Register("cr0_eq"), arch.instrs_ppc_compare[mnemonic](args, "==")) set_reg(Register("cr0_gt"), arch.instrs_ppc_compare[mnemonic](args, ">")) set_reg(Register("cr0_lt"), arch.instrs_ppc_compare[mnemonic](args, "<")) set_reg(Register("cr0_so"), Literal(0)) elif mnemonic in arch.instrs_no_dest: stmt = arch.instrs_no_dest[mnemonic](args) to_write.append(stmt) elif mnemonic.rstrip(".") in arch.instrs_destination_first: target = args.reg_ref(0) val = arch.instrs_destination_first[mnemonic.rstrip(".")](args) target_val = set_reg(target, val) mn_parts = arch_mnemonic.split(".") if arch_mnemonic.startswith("ppc:") and arch_mnemonic.endswith("."): if target_val is None: target_val = val set_reg( Register("cr0_eq"), BinaryOp.icmp(target_val, "==", Literal(0, type=target_val.type)), ) target_s32 = Cast( target_val, reinterpret=True, silent=True, type=Type.s32() ) set_reg( Register("cr0_gt"), BinaryOp(target_s32, ">", Literal(0), type=Type.s32()), ) set_reg( Register("cr0_lt"), BinaryOp(target_s32, "<", Literal(0), type=Type.s32()), ) set_reg( Register("cr0_so"), fn_op("MIPS2C_OVERFLOW", [target_val], type=Type.s32()), ) elif ( len(mn_parts) >= 2 and mn_parts[0].startswith("mips:") and mn_parts[1] == "d" ) or arch_mnemonic == "mips:ldc1": set_reg(target.other_f64_reg(), SecondF64Half()) elif mnemonic in arch.instrs_load_update: target = args.reg_ref(0) val = arch.instrs_load_update[mnemonic](args) set_reg(target, val) if arch_mnemonic in ["ppc:lwzux", "ppc:lhzux", "ppc:lbzux"]: # In `rD, rA, rB`, update `rA = rA + rB` update_reg = args.reg_ref(1) offset = args.reg(2) else: # In `rD, rA(N)`, update `rA = rA + N` update = args.memory_ref(1) if not isinstance(update, AddressMode): raise DecompFailure( f"Unhandled store-and-update arg in {instr}: {update!r}" ) update_reg = update.rhs offset = Literal(update.offset) if update_reg == target: raise DecompFailure( f"Invalid instruction, rA and rD must be different in {instr}" ) set_reg(update_reg, add_imm(args.regs[update_reg], offset, stack_info)) else: expr = ErrorExpr(f"unknown instruction: {instr}") if arch_mnemonic.startswith("ppc:") and arch_mnemonic.endswith("."): # Unimplemented PPC instructions that modify CR0 set_reg(Register("cr0_eq"), expr) set_reg(Register("cr0_gt"), expr) set_reg(Register("cr0_lt"), expr) set_reg(Register("cr0_so"), expr) if args.count() >= 1 and isinstance(args.raw_arg(0), Register): reg = args.reg_ref(0) expr = eval_once( expr, emit_exactly_once=True, trivial=False, prefix=stack_info.function.reg_formatter.format(reg), ) if reg != Register("zero"): set_reg_maybe_return(reg, expr) else: to_write.append(ExprStmt(expr)) for instr in node.block.instructions: with regs.current_instr(instr): process_instr(instr) if branch_condition is not None: branch_condition.use() switch_control: Optional[SwitchControl] = None if switch_expr is not None: switch_control = SwitchControl.from_expr(switch_expr) switch_control.control_expr.use() return BlockInfo( to_write=to_write, return_value=None, switch_control=switch_control, branch_condition=branch_condition, final_register_states=regs, has_function_call=has_function_call, ) def translate_graph_from_block( node: Node, regs: RegInfo, stack_info: StackInfo, used_phis: List[PhiExpr], return_blocks: List[BlockInfo], options: Options, ) -> None: if options.debug: print(f"\nNode in question: {node}") # Translate the given node and discover final register states. try: block_info = translate_node_body(node, regs, stack_info) if options.debug: print(block_info) except Exception as e: # TODO: handle issues better if options.stop_on_error: raise instr: Optional[Instruction] = None if isinstance(e, InstrProcessingFailure) and isinstance(e.__cause__, Exception): instr = e.instr e = e.__cause__ if isinstance(e, DecompFailure): emsg = str(e) print(emsg) else: tb = e.__traceback__ traceback.print_exception(None, e, tb) emsg = str(e) or traceback.format_tb(tb)[-1] emsg = emsg.strip().split("\n")[-1].strip() error_stmts: List[Statement] = [CommentStmt(f"Error: {emsg}")] if instr is not None: print( f"Error occurred while processing instruction: {instr}", file=sys.stderr ) error_stmts.append(CommentStmt(f"At instruction: {instr}")) print(file=sys.stderr) block_info = BlockInfo( to_write=error_stmts, return_value=None, switch_control=None, branch_condition=ErrorExpr(), final_register_states=regs, has_function_call=False, ) node.block.add_block_info(block_info) if isinstance(node, ReturnNode): return_blocks.append(block_info) # Translate everything dominated by this node, now that we know our own # final register state. This will eventually reach every node. for child in node.immediately_dominates: if isinstance(child, TerminalNode): continue new_regs = RegInfo(stack_info=stack_info) for reg, data in regs.contents.items(): new_regs.set_with_meta( reg, data.value, RegMeta(inherited=True, force=data.meta.force) ) phi_regs = ( r for r in locs_clobbered_until_dominator(child) if isinstance(r, Register) ) for reg in phi_regs: if reg_always_set(child, reg, dom_set=(reg in regs)): expr: Optional[Expression] = stack_info.maybe_get_register_var(reg) if expr is None: expr = PhiExpr( reg=reg, node=child, used_phis=used_phis, type=Type.any_reg() ) new_regs.set_with_meta(reg, expr, RegMeta(inherited=True)) elif reg in new_regs: del new_regs[reg] translate_graph_from_block( child, new_regs, stack_info, used_phis, return_blocks, options ) def resolve_types_late(stack_info: StackInfo) -> None: # Final check over stack var types. Because of delayed type unification, some # locations should now be marked as "weak". for location in stack_info.weak_stack_var_types.keys(): stack_info.get_stack_var(location, store=False) # Use dereferences to determine pointer types struct_type_map = stack_info.get_struct_type_map() for var, offset_type_map in struct_type_map.items(): if len(offset_type_map) == 1 and 0 in offset_type_map: # var was probably a plain pointer, not a struct # Try to unify it with the appropriate pointer type, # to fill in the type if it does not already have one type = offset_type_map[0] var.type.unify(Type.ptr(type)) @dataclass class FunctionInfo: stack_info: StackInfo flow_graph: FlowGraph return_type: Type symbol: GlobalSymbol @dataclass class GlobalInfo: asm_data: AsmData arch: Arch target: Target local_functions: Set[str] typemap: TypeMap typepool: TypePool global_symbol_map: Dict[str, GlobalSymbol] = field(default_factory=dict) def asm_data_value(self, sym_name: str) -> Optional[AsmDataEntry]: return self.asm_data.values.get(sym_name) def address_of_gsym(self, sym_name: str) -> AddressOf: if sym_name in self.global_symbol_map: sym = self.global_symbol_map[sym_name] else: demangled_symbol: Optional[CxxSymbol] = None demangled_str: Optional[str] = None if self.target.language == Target.LanguageEnum.CXX: try: demangled_symbol = demangle_codewarrior_parse(sym_name) except ValueError: pass else: demangled_str = str(demangled_symbol) sym = self.global_symbol_map[sym_name] = GlobalSymbol( symbol_name=sym_name, type=Type.any(), asm_data_entry=self.asm_data_value(sym_name), demangled_str=demangled_str, ) # If the symbol is a C++ vtable, try to build a custom type for it by parsing it if ( self.target.language == Target.LanguageEnum.CXX and sym_name.startswith("__vt__") and sym.asm_data_entry is not None ): sym.type.unify(self.vtable_type(sym_name, sym.asm_data_entry)) fn = self.typemap.functions.get(sym_name) ctype: Optional[CType] if fn is not None: ctype = fn.type else: ctype = self.typemap.var_types.get(sym_name) if ctype is not None: sym.symbol_in_context = True sym.initializer_in_typemap = ( sym_name in self.typemap.vars_with_initializers ) sym.type.unify(Type.ctype(ctype, self.typemap, self.typepool)) if sym_name not in self.typepool.unknown_decls: sym.type_provided = True elif sym_name in self.local_functions: sym.type.unify(Type.function()) # Do this after unifying the type in the typemap, so that it has lower precedence if demangled_symbol is not None: sym.type.unify( Type.demangled_symbol(self.typemap, self.typepool, demangled_symbol) ) return AddressOf(sym, type=sym.type.reference()) def vtable_type(self, sym_name: str, asm_data_entry: AsmDataEntry) -> Type: size = asm_data_entry.size_range_bytes()[1] struct = StructDeclaration.unknown( self.typepool, size=size, align=4, tag_name=sym_name ) offset = 0 for entry in asm_data_entry.data: if isinstance(entry, bytes): # MWCC vtables start with a pointer to a typeid struct (or NULL) and an offset if len(entry) % 4 != 0: raise DecompFailure( f"Unable to parse misaligned vtable data in {sym_name}" ) for i in range(len(entry) // 4): field_name = f"{struct.new_field_prefix}{offset:X}" struct.try_add_field( Type.reg32(likely_float=False), offset, field_name, size=4 ) offset += 4 else: entry_name = entry try: demangled_field_sym = demangle_codewarrior_parse(entry) if demangled_field_sym.name.qualified_name is not None: entry_name = str(demangled_field_sym.name.qualified_name[-1]) except ValueError: pass field = struct.try_add_field( self.address_of_gsym(entry).type, offset, name=entry_name, size=4, ) assert field is not None field.known = True offset += 4 return Type.struct(struct) def is_function_known_void(self, sym_name: str) -> bool: fn = self.typemap.functions.get(sym_name) if fn is None: return False return fn.ret_type is None def initializer_for_symbol( self, sym: GlobalSymbol, fmt: Formatter ) -> Optional[str]: assert sym.asm_data_entry is not None data = sym.asm_data_entry.data[:] def read_uint(n: int) -> Optional[int]: assert 0 < n <= 8 if not data or not isinstance(data[0], bytes): return None if len(data[0]) < n: return None bs = data[0][:n] data[0] = data[0][n:] if not data[0]: del data[0] value = 0 for b in bs: value = (value << 8) | b return value def read_pointer() -> Optional[Expression]: if not data or not isinstance(data[0], str): return None label = data[0] data.pop(0) return self.address_of_gsym(label) def for_type(type: Type) -> Optional[str]: if type.is_struct() or type.is_array(): struct_fields = type.get_initializer_fields() if not struct_fields: return None members = [] for field in struct_fields: if isinstance(field, int): # Check that all padding bytes are 0 for i in range(field): padding = read_uint(1) if padding != 0: return None else: m = for_type(field) if m is None: return None members.append(m) return fmt.format_array(members) if type.is_reg(): size = type.get_size_bytes() if not size: return None if size == 4: ptr = read_pointer() if ptr is not None: return as_type(ptr, type, silent=True).format(fmt) value = read_uint(size) if value is not None: enum_name = type.get_enum_name(value) if enum_name is not None: return enum_name expr = as_type(Literal(value), type, True) return elide_casts_for_store(expr).format(fmt) # Type kinds K_FN and K_VOID do not have initializers return None return for_type(sym.type) def find_forward_declares_needed(self, functions: List[FunctionInfo]) -> Set[str]: funcs_seen = set() forward_declares_needed = self.asm_data.mentioned_labels for func in functions: funcs_seen.add(func.stack_info.function.name) for instr in func.stack_info.function.body: if not isinstance(instr, Instruction): continue for arg in instr.args: if isinstance(arg, AsmGlobalSymbol): func_name = arg.symbol_name elif isinstance(arg, Macro) and isinstance( arg.argument, AsmGlobalSymbol ): func_name = arg.argument.symbol_name else: continue if func_name in self.local_functions: if func_name not in funcs_seen: forward_declares_needed.add(func_name) return forward_declares_needed def global_decls( self, fmt: Formatter, decls: Options.GlobalDeclsEnum, functions: List[FunctionInfo], ) -> str: # Format labels from symbol_type_map into global declarations. # As the initializers are formatted, this may cause more symbols # to be added to the global_symbol_map. forward_declares_needed = self.find_forward_declares_needed(functions) lines = [] processed_names: Set[str] = set() while True: names: AbstractSet[str] = self.global_symbol_map.keys() if decls == Options.GlobalDeclsEnum.ALL: names |= self.asm_data.values.keys() names -= processed_names if not names: break for name in sorted(names): processed_names.add(name) sym = self.address_of_gsym(name).expr assert isinstance(sym, GlobalSymbol) data_entry = sym.asm_data_entry # Is the label defined in this unit (in the active AsmData file(s)) is_in_file = data_entry is not None or name in self.local_functions # Is the label externally visible (mentioned in the context file) is_global = sym.symbol_in_context # Is the label a symbol in .rodata? is_const = data_entry is not None and data_entry.is_readonly if data_entry and data_entry.is_jtbl: # Skip jump tables continue if is_in_file and is_global and sym.type.is_function(): # Skip externally-declared functions that are defined here continue if self.local_functions == {name}: # Skip the function being decompiled if just a single one continue if not is_in_file and sym.type_provided: # Skip externally-declared symbols that are defined in other files continue # TODO: Use original MIPSFile ordering for variables sort_order = ( not sym.type.is_function(), is_global, is_in_file, is_const, name, ) qualifier = "" value: Optional[str] = None comments = [] # Determine type qualifier: static, extern, or neither if is_in_file and is_global: qualifier = "" elif is_in_file: qualifier = "static" else: qualifier = "extern" if sym.type.is_function(): comments.append(qualifier) qualifier = "" # Try to guess if the symbol is an array (and if it is, its dimension) if # we have a data entry for it, and the symbol is either not in the typemap # or was a variable-length array there ("VLA", e.g. `int []`) # (Otherwise, if the dim is provided by the typemap, we trust it.) element_type, array_dim = sym.type.get_array() is_vla = element_type is not None and ( array_dim is None or array_dim <= 0 ) if data_entry and (not sym.type_provided or is_vla): # The size of the data entry is uncertain, because of padding # between sections. Generally `(max_data_size - data_size) < 16`. min_data_size, max_data_size = data_entry.size_range_bytes() # The size of the element type (not the size of the array type) if element_type is None: element_type = sym.type # If we don't know the type, we can't guess the array_dim type_size = element_type.get_size_bytes() if type_size: potential_dim, extra_bytes = sym.potential_array_dim(type_size) if potential_dim == 0 and extra_bytes > 0: # The type is too big for our data. (not an array) comments.append( f"type too large by {fmt.format_int(type_size - extra_bytes)}" ) elif potential_dim > 1 or is_vla: # NB: In general, replacing the types of Expressions can be sketchy. # However, the GlobalSymbol here came from address_of_gsym(), which # always returns a reference to the element_type. array_dim = potential_dim sym.type = Type.array(element_type, array_dim) if potential_dim != 0 and extra_bytes > 0: comments.append( f"extra bytes: {fmt.format_int(extra_bytes)}" ) # Try to convert the data from .data/.rodata into an initializer if data_entry and not data_entry.is_bss: value = self.initializer_for_symbol(sym, fmt) if value is None: # This warning helps distinguish .bss symbols from .data/.rodata, # IDO only puts symbols in .bss if they don't have any initializer comments.append("unable to generate initializer") if is_const: comments.append("const") if sym.is_string_constant(): continue if array_dim is None and sym.type.is_likely_float(): continue if decls == Options.GlobalDeclsEnum.NONE: continue if decls != Options.GlobalDeclsEnum.ALL and sym.initializer_in_typemap: continue if ( decls != Options.GlobalDeclsEnum.ALL and self.target.language == Target.LanguageEnum.CXX and name.startswith("__vt__") ): continue if ( sym.type.is_function() and decls != Options.GlobalDeclsEnum.ALL and name in self.local_functions and name not in forward_declares_needed ): continue qualifier = f"{qualifier} " if qualifier else "" value = f" = {value}" if value else "" lines.append( ( sort_order, fmt.with_comments( f"{qualifier}{sym.type.to_decl(name, fmt)}{value};", comments, ) + "\n", ) ) lines.sort() return "".join(line for _, line in lines) def narrow_func_call_outputs( function: Function, global_info: GlobalInfo, ) -> None: for instr in function.body: if ( isinstance(instr, Instruction) and isinstance(instr.function_target, AsmGlobalSymbol) and global_info.is_function_known_void(instr.function_target.symbol_name) ): instr.outputs.clear() def translate_to_ast( function: Function, flow_graph: FlowGraph, options: Options, global_info: GlobalInfo, ) -> FunctionInfo: stack_info = get_stack_info(function, global_info, flow_graph) start_regs: RegInfo = RegInfo(stack_info=stack_info) arch = global_info.arch start_regs[arch.stack_pointer_reg] = GlobalSymbol("sp", type=Type.ptr()) for reg in arch.saved_regs: start_regs[reg] = stack_info.saved_reg_symbol(reg.register_name) fn_sym = global_info.address_of_gsym(function.name).expr assert isinstance(fn_sym, GlobalSymbol) fn_type = fn_sym.type fn_type.unify(Type.function()) fn_sig = Type.ptr(fn_type).get_function_pointer_signature() assert fn_sig is not None, "fn_type is known to be a function" return_type = fn_sig.return_type stack_info.is_variadic = fn_sig.is_variadic def make_arg(offset: int, type: Type) -> PassedInArg: assert offset % 4 == 0 return PassedInArg(offset, copied=False, stack_info=stack_info, type=type) abi = arch.function_abi( fn_sig, likely_regs={reg: True for reg in arch.argument_regs}, for_call=False, ) for slot in abi.arg_slots: stack_info.add_known_param(slot.offset, slot.name, slot.type) if slot.reg is not None: start_regs.set_with_meta( slot.reg, make_arg(slot.offset, slot.type), RegMeta(uninteresting=True) ) for slot in abi.possible_slots: if slot.reg is not None: start_regs.set_with_meta( slot.reg, make_arg(slot.offset, slot.type), RegMeta(uninteresting=True) ) if options.reg_vars == ["saved"]: reg_vars = arch.saved_regs elif options.reg_vars == ["most"]: reg_vars = arch.saved_regs + arch.simple_temp_regs elif options.reg_vars == ["all"]: reg_vars = arch.saved_regs + arch.simple_temp_regs + arch.argument_regs else: reg_vars = [ stack_info.function.reg_formatter.parse(x, arch) for x in options.reg_vars ] for reg in reg_vars: reg_name = stack_info.function.reg_formatter.format(reg) stack_info.add_register_var(reg, reg_name) if options.debug: print(stack_info) print("\nNow, we attempt to translate:") used_phis: List[PhiExpr] = [] return_blocks: List[BlockInfo] = [] translate_graph_from_block( flow_graph.entry_node(), start_regs, stack_info, used_phis, return_blocks, options, ) for reg in arch.base_return_regs: propagate_register_meta(flow_graph.nodes, reg) return_reg: Optional[Register] = None if not options.void and not return_type.is_void(): return_reg = determine_return_register( return_blocks, fn_sym.type_provided, arch ) if return_reg is not None: for b in return_blocks: if return_reg in b.final_register_states: ret_val = b.final_register_states[return_reg] ret_val = as_type(ret_val, return_type, True) ret_val.use() b.return_value = ret_val else: return_type.unify(Type.void()) if not fn_sig.params_known: while len(fn_sig.params) < len(stack_info.arguments): fn_sig.params.append(FunctionParam()) for param, arg in zip(fn_sig.params, stack_info.arguments): param.type.unify(arg.type) if not param.name: param.name = arg.format(Formatter()) assign_phis(used_phis, stack_info) resolve_types_late(stack_info) if options.pdb_translate: import pdb v: Dict[str, object] = {} fmt = Formatter() for local in stack_info.local_vars: var_name = local.format(fmt) v[var_name] = local for temp in stack_info.temp_vars: if temp.need_decl(): var_name = temp.expr.var.format(fmt) v[var_name] = temp.expr for phi in stack_info.phi_vars: assert phi.name is not None v[phi.name] = phi pdb.set_trace() return FunctionInfo(stack_info, flow_graph, return_type, fn_sym)
true
true
f725ad7f8cee325b6f43a8b62288b6b7f43cee75
2,727
py
Python
ibis/backends/clickhouse/tests/test_types.py
GrapeBaBa/ibis
507bb14efdcfd719a0487ee23fe1c85c177517f6
[ "Apache-2.0" ]
1
2015-11-05T15:40:12.000Z
2015-11-05T15:40:12.000Z
ibis/backends/clickhouse/tests/test_types.py
GrapeBaBa/ibis
507bb14efdcfd719a0487ee23fe1c85c177517f6
[ "Apache-2.0" ]
7
2021-09-02T21:18:10.000Z
2022-01-31T12:03:40.000Z
ibis/backends/clickhouse/tests/test_types.py
GrapeBaBa/ibis
507bb14efdcfd719a0487ee23fe1c85c177517f6
[ "Apache-2.0" ]
null
null
null
import pytest from pkg_resources import parse_version import ibis.expr.datatypes as dt from ibis.backends.clickhouse.client import ClickhouseDataType def test_column_types(alltypes): df = alltypes.execute() assert df.tinyint_col.dtype.name == 'int8' assert df.smallint_col.dtype.name == 'int16' assert df.int_col.dtype.name == 'int32' assert df.bigint_col.dtype.name == 'int64' assert df.float_col.dtype.name == 'float32' assert df.double_col.dtype.name == 'float64' assert df.timestamp_col.dtype.name == 'datetime64[ns]' def test_columns_types_with_additional_argument(con): sql_types = ["toFixedString('foo', 8) AS fixedstring_col"] if parse_version(con.version).base_version >= '1.1.54337': sql_types.append( "toDateTime('2018-07-02 00:00:00', 'UTC') AS datetime_col" ) sql = 'SELECT {}'.format(', '.join(sql_types)) df = con.sql(sql).execute() assert df.fixedstring_col.dtype.name == 'object' if parse_version(con.version).base_version >= '1.1.54337': assert df.datetime_col.dtype.name == 'datetime64[ns]' @pytest.mark.parametrize( ('ch_type', 'ibis_type'), [ ('Array(Int8)', dt.Array(dt.Int8(nullable=False))), ('Array(Int16)', dt.Array(dt.Int16(nullable=False))), ('Array(Int32)', dt.Array(dt.Int32(nullable=False))), ('Array(Int64)', dt.Array(dt.Int64(nullable=False))), ('Array(UInt8)', dt.Array(dt.UInt8(nullable=False))), ('Array(UInt16)', dt.Array(dt.UInt16(nullable=False))), ('Array(UInt32)', dt.Array(dt.UInt32(nullable=False))), ('Array(UInt64)', dt.Array(dt.UInt64(nullable=False))), ('Array(Float32)', dt.Array(dt.Float32(nullable=False))), ('Array(Float64)', dt.Array(dt.Float64(nullable=False))), ('Array(String)', dt.Array(dt.String(nullable=False))), ('Array(FixedString(32))', dt.Array(dt.String(nullable=False))), ('Array(Date)', dt.Array(dt.Date(nullable=False))), ('Array(DateTime)', dt.Array(dt.Timestamp(nullable=False))), ('Array(DateTime64)', dt.Array(dt.Timestamp(nullable=False))), ('Array(Nothing)', dt.Array(dt.Null(nullable=False))), ('Array(Null)', dt.Array(dt.Null(nullable=False))), ('Array(Array(Int8))', dt.Array(dt.Array(dt.Int8(nullable=False)))), ( 'Array(Array(Array(Int8)))', dt.Array(dt.Array(dt.Array(dt.Int8(nullable=False)))), ), ( 'Array(Array(Array(Array(Int8))))', dt.Array(dt.Array(dt.Array(dt.Array(dt.Int8(nullable=False))))), ), ], ) def test_array_type(ch_type, ibis_type): assert ClickhouseDataType(ch_type).to_ibis() == ibis_type
41.953846
76
0.635497
import pytest from pkg_resources import parse_version import ibis.expr.datatypes as dt from ibis.backends.clickhouse.client import ClickhouseDataType def test_column_types(alltypes): df = alltypes.execute() assert df.tinyint_col.dtype.name == 'int8' assert df.smallint_col.dtype.name == 'int16' assert df.int_col.dtype.name == 'int32' assert df.bigint_col.dtype.name == 'int64' assert df.float_col.dtype.name == 'float32' assert df.double_col.dtype.name == 'float64' assert df.timestamp_col.dtype.name == 'datetime64[ns]' def test_columns_types_with_additional_argument(con): sql_types = ["toFixedString('foo', 8) AS fixedstring_col"] if parse_version(con.version).base_version >= '1.1.54337': sql_types.append( "toDateTime('2018-07-02 00:00:00', 'UTC') AS datetime_col" ) sql = 'SELECT {}'.format(', '.join(sql_types)) df = con.sql(sql).execute() assert df.fixedstring_col.dtype.name == 'object' if parse_version(con.version).base_version >= '1.1.54337': assert df.datetime_col.dtype.name == 'datetime64[ns]' @pytest.mark.parametrize( ('ch_type', 'ibis_type'), [ ('Array(Int8)', dt.Array(dt.Int8(nullable=False))), ('Array(Int16)', dt.Array(dt.Int16(nullable=False))), ('Array(Int32)', dt.Array(dt.Int32(nullable=False))), ('Array(Int64)', dt.Array(dt.Int64(nullable=False))), ('Array(UInt8)', dt.Array(dt.UInt8(nullable=False))), ('Array(UInt16)', dt.Array(dt.UInt16(nullable=False))), ('Array(UInt32)', dt.Array(dt.UInt32(nullable=False))), ('Array(UInt64)', dt.Array(dt.UInt64(nullable=False))), ('Array(Float32)', dt.Array(dt.Float32(nullable=False))), ('Array(Float64)', dt.Array(dt.Float64(nullable=False))), ('Array(String)', dt.Array(dt.String(nullable=False))), ('Array(FixedString(32))', dt.Array(dt.String(nullable=False))), ('Array(Date)', dt.Array(dt.Date(nullable=False))), ('Array(DateTime)', dt.Array(dt.Timestamp(nullable=False))), ('Array(DateTime64)', dt.Array(dt.Timestamp(nullable=False))), ('Array(Nothing)', dt.Array(dt.Null(nullable=False))), ('Array(Null)', dt.Array(dt.Null(nullable=False))), ('Array(Array(Int8))', dt.Array(dt.Array(dt.Int8(nullable=False)))), ( 'Array(Array(Array(Int8)))', dt.Array(dt.Array(dt.Array(dt.Int8(nullable=False)))), ), ( 'Array(Array(Array(Array(Int8))))', dt.Array(dt.Array(dt.Array(dt.Array(dt.Int8(nullable=False))))), ), ], ) def test_array_type(ch_type, ibis_type): assert ClickhouseDataType(ch_type).to_ibis() == ibis_type
true
true
f725adf48debebf7012aabc4bd719b3c1bf15fb2
13,130
py
Python
torchreid/data_manager/cuhk03.py
phoenix1712/deep-person-reid
8537a9d94b31cbf85e475bd115bb2714086f9be0
[ "MIT" ]
11
2019-01-10T08:03:31.000Z
2020-10-23T03:14:23.000Z
torchreid/data_manager/cuhk03.py
xinshengwang/deep-person-reid
70365320f5319e180d7fce4993003382b06906b0
[ "MIT" ]
1
2020-11-13T08:20:53.000Z
2021-01-12T23:06:55.000Z
torchreid/data_manager/cuhk03.py
xinshengwang/deep-person-reid
70365320f5319e180d7fce4993003382b06906b0
[ "MIT" ]
8
2019-03-05T09:12:54.000Z
2022-02-05T06:21:21.000Z
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import glob import re import sys import urllib import tarfile import zipfile import os.path as osp from scipy.io import loadmat import numpy as np import h5py from scipy.misc import imsave from torchreid.utils.iotools import mkdir_if_missing, write_json, read_json class CUHK03(object): """ CUHK03 Reference: Li et al. DeepReID: Deep Filter Pairing Neural Network for Person Re-identification. CVPR 2014. URL: http://www.ee.cuhk.edu.hk/~xgwang/CUHK_identification.html#! Dataset statistics: # identities: 1360 # images: 13164 # cameras: 6 # splits: 20 (classic) Args: split_id (int): split index (default: 0) cuhk03_labeled (bool): whether to load labeled images; if false, detected images are loaded (default: False) """ dataset_dir = 'cuhk03' def __init__(self, root='data', split_id=0, cuhk03_labeled=False, cuhk03_classic_split=False, verbose=True, **kwargs): super(CUHK03, self).__init__() self.dataset_dir = osp.join(root, self.dataset_dir) self.data_dir = osp.join(self.dataset_dir, 'cuhk03_release') self.raw_mat_path = osp.join(self.data_dir, 'cuhk-03.mat') self.imgs_detected_dir = osp.join(self.dataset_dir, 'images_detected') self.imgs_labeled_dir = osp.join(self.dataset_dir, 'images_labeled') self.split_classic_det_json_path = osp.join(self.dataset_dir, 'splits_classic_detected.json') self.split_classic_lab_json_path = osp.join(self.dataset_dir, 'splits_classic_labeled.json') self.split_new_det_json_path = osp.join(self.dataset_dir, 'splits_new_detected.json') self.split_new_lab_json_path = osp.join(self.dataset_dir, 'splits_new_labeled.json') self.split_new_det_mat_path = osp.join(self.dataset_dir, 'cuhk03_new_protocol_config_detected.mat') self.split_new_lab_mat_path = osp.join(self.dataset_dir, 'cuhk03_new_protocol_config_labeled.mat') self._check_before_run() self._preprocess() if cuhk03_labeled: image_type = 'labeled' split_path = self.split_classic_lab_json_path if cuhk03_classic_split else self.split_new_lab_json_path else: image_type = 'detected' split_path = self.split_classic_det_json_path if cuhk03_classic_split else self.split_new_det_json_path splits = read_json(split_path) assert split_id < len(splits), "Condition split_id ({}) < len(splits) ({}) is false".format(split_id, len(splits)) split = splits[split_id] print("Split index = {}".format(split_id)) train = split['train'] query = split['query'] gallery = split['gallery'] num_train_pids = split['num_train_pids'] num_query_pids = split['num_query_pids'] num_gallery_pids = split['num_gallery_pids'] num_total_pids = num_train_pids + num_query_pids num_train_imgs = split['num_train_imgs'] num_query_imgs = split['num_query_imgs'] num_gallery_imgs = split['num_gallery_imgs'] num_total_imgs = num_train_imgs + num_query_imgs if verbose: print("=> CUHK03 ({}) loaded".format(image_type)) print("Dataset statistics:") print(" ------------------------------") print(" subset | # ids | # images") print(" ------------------------------") print(" train | {:5d} | {:8d}".format(num_train_pids, num_train_imgs)) print(" query | {:5d} | {:8d}".format(num_query_pids, num_query_imgs)) print(" gallery | {:5d} | {:8d}".format(num_gallery_pids, num_gallery_imgs)) print(" ------------------------------") print(" total | {:5d} | {:8d}".format(num_total_pids, num_total_imgs)) print(" ------------------------------") self.train = train self.query = query self.gallery = gallery self.num_train_pids = num_train_pids self.num_query_pids = num_query_pids self.num_gallery_pids = num_gallery_pids def _check_before_run(self): """Check if all files are available before going deeper""" if not osp.exists(self.dataset_dir): raise RuntimeError("'{}' is not available".format(self.dataset_dir)) if not osp.exists(self.data_dir): raise RuntimeError("'{}' is not available".format(self.data_dir)) if not osp.exists(self.raw_mat_path): raise RuntimeError("'{}' is not available".format(self.raw_mat_path)) if not osp.exists(self.split_new_det_mat_path): raise RuntimeError("'{}' is not available".format(self.split_new_det_mat_path)) if not osp.exists(self.split_new_lab_mat_path): raise RuntimeError("'{}' is not available".format(self.split_new_lab_mat_path)) def _preprocess(self): """ This function is a bit complex and ugly, what it does is 1. Extract data from cuhk-03.mat and save as png images. 2. Create 20 classic splits. (Li et al. CVPR'14) 3. Create new split. (Zhong et al. CVPR'17) """ print("Note: if root path is changed, the previously generated json files need to be re-generated (delete them first)") if osp.exists(self.imgs_labeled_dir) and \ osp.exists(self.imgs_detected_dir) and \ osp.exists(self.split_classic_det_json_path) and \ osp.exists(self.split_classic_lab_json_path) and \ osp.exists(self.split_new_det_json_path) and \ osp.exists(self.split_new_lab_json_path): return mkdir_if_missing(self.imgs_detected_dir) mkdir_if_missing(self.imgs_labeled_dir) print("Extract image data from {} and save as png".format(self.raw_mat_path)) mat = h5py.File(self.raw_mat_path, 'r') def _deref(ref): return mat[ref][:].T def _process_images(img_refs, campid, pid, save_dir): img_paths = [] # Note: some persons only have images for one view for imgid, img_ref in enumerate(img_refs): img = _deref(img_ref) # skip empty cell if img.size == 0 or img.ndim < 3: continue # images are saved with the following format, index-1 (ensure uniqueness) # campid: index of camera pair (1-5) # pid: index of person in 'campid'-th camera pair # viewid: index of view, {1, 2} # imgid: index of image, (1-10) viewid = 1 if imgid < 5 else 2 img_name = '{:01d}_{:03d}_{:01d}_{:02d}.png'.format(campid+1, pid+1, viewid, imgid+1) img_path = osp.join(save_dir, img_name) imsave(img_path, img) img_paths.append(img_path) return img_paths def _extract_img(name): print("Processing {} images (extract and save) ...".format(name)) meta_data = [] imgs_dir = self.imgs_detected_dir if name == 'detected' else self.imgs_labeled_dir for campid, camp_ref in enumerate(mat[name][0]): camp = _deref(camp_ref) num_pids = camp.shape[0] for pid in range(num_pids): img_paths = _process_images(camp[pid,:], campid, pid, imgs_dir) assert len(img_paths) > 0, "campid{}-pid{} has no images".format(campid, pid) meta_data.append((campid+1, pid+1, img_paths)) print("done camera pair {} with {} identities".format(campid+1, num_pids)) return meta_data meta_detected = _extract_img('detected') meta_labeled = _extract_img('labeled') def _extract_classic_split(meta_data, test_split): train, test = [], [] num_train_pids, num_test_pids = 0, 0 num_train_imgs, num_test_imgs = 0, 0 for i, (campid, pid, img_paths) in enumerate(meta_data): if [campid, pid] in test_split: for img_path in img_paths: camid = int(osp.basename(img_path).split('_')[2]) test.append((img_path, num_test_pids, camid)) num_test_pids += 1 num_test_imgs += len(img_paths) else: for img_path in img_paths: camid = int(osp.basename(img_path).split('_')[2]) train.append((img_path, num_train_pids, camid)) num_train_pids += 1 num_train_imgs += len(img_paths) return train, num_train_pids, num_train_imgs, test, num_test_pids, num_test_imgs print("Creating classic splits (# = 20) ...") splits_classic_det, splits_classic_lab = [], [] for split_ref in mat['testsets'][0]: test_split = _deref(split_ref).tolist() # create split for detected images train, num_train_pids, num_train_imgs, test, num_test_pids, num_test_imgs = \ _extract_classic_split(meta_detected, test_split) splits_classic_det.append({ 'train': train, 'query': test, 'gallery': test, 'num_train_pids': num_train_pids, 'num_train_imgs': num_train_imgs, 'num_query_pids': num_test_pids, 'num_query_imgs': num_test_imgs, 'num_gallery_pids': num_test_pids, 'num_gallery_imgs': num_test_imgs, }) # create split for labeled images train, num_train_pids, num_train_imgs, test, num_test_pids, num_test_imgs = \ _extract_classic_split(meta_labeled, test_split) splits_classic_lab.append({ 'train': train, 'query': test, 'gallery': test, 'num_train_pids': num_train_pids, 'num_train_imgs': num_train_imgs, 'num_query_pids': num_test_pids, 'num_query_imgs': num_test_imgs, 'num_gallery_pids': num_test_pids, 'num_gallery_imgs': num_test_imgs, }) write_json(splits_classic_det, self.split_classic_det_json_path) write_json(splits_classic_lab, self.split_classic_lab_json_path) def _extract_set(filelist, pids, pid2label, idxs, img_dir, relabel): tmp_set = [] unique_pids = set() for idx in idxs: img_name = filelist[idx][0] camid = int(img_name.split('_')[2]) pid = pids[idx] if relabel: pid = pid2label[pid] img_path = osp.join(img_dir, img_name) tmp_set.append((img_path, int(pid), camid)) unique_pids.add(pid) return tmp_set, len(unique_pids), len(idxs) def _extract_new_split(split_dict, img_dir): train_idxs = split_dict['train_idx'].flatten() - 1 # index-0 pids = split_dict['labels'].flatten() train_pids = set(pids[train_idxs]) pid2label = {pid: label for label, pid in enumerate(train_pids)} query_idxs = split_dict['query_idx'].flatten() - 1 gallery_idxs = split_dict['gallery_idx'].flatten() - 1 filelist = split_dict['filelist'].flatten() train_info = _extract_set(filelist, pids, pid2label, train_idxs, img_dir, relabel=True) query_info = _extract_set(filelist, pids, pid2label, query_idxs, img_dir, relabel=False) gallery_info = _extract_set(filelist, pids, pid2label, gallery_idxs, img_dir, relabel=False) return train_info, query_info, gallery_info print("Creating new splits for detected images (767/700) ...") train_info, query_info, gallery_info = _extract_new_split( loadmat(self.split_new_det_mat_path), self.imgs_detected_dir, ) splits = [{ 'train': train_info[0], 'query': query_info[0], 'gallery': gallery_info[0], 'num_train_pids': train_info[1], 'num_train_imgs': train_info[2], 'num_query_pids': query_info[1], 'num_query_imgs': query_info[2], 'num_gallery_pids': gallery_info[1], 'num_gallery_imgs': gallery_info[2], }] write_json(splits, self.split_new_det_json_path) print("Creating new splits for labeled images (767/700) ...") train_info, query_info, gallery_info = _extract_new_split( loadmat(self.split_new_lab_mat_path), self.imgs_labeled_dir, ) splits = [{ 'train': train_info[0], 'query': query_info[0], 'gallery': gallery_info[0], 'num_train_pids': train_info[1], 'num_train_imgs': train_info[2], 'num_query_pids': query_info[1], 'num_query_imgs': query_info[2], 'num_gallery_pids': gallery_info[1], 'num_gallery_imgs': gallery_info[2], }] write_json(splits, self.split_new_lab_json_path)
46.560284
127
0.6131
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import glob import re import sys import urllib import tarfile import zipfile import os.path as osp from scipy.io import loadmat import numpy as np import h5py from scipy.misc import imsave from torchreid.utils.iotools import mkdir_if_missing, write_json, read_json class CUHK03(object): dataset_dir = 'cuhk03' def __init__(self, root='data', split_id=0, cuhk03_labeled=False, cuhk03_classic_split=False, verbose=True, **kwargs): super(CUHK03, self).__init__() self.dataset_dir = osp.join(root, self.dataset_dir) self.data_dir = osp.join(self.dataset_dir, 'cuhk03_release') self.raw_mat_path = osp.join(self.data_dir, 'cuhk-03.mat') self.imgs_detected_dir = osp.join(self.dataset_dir, 'images_detected') self.imgs_labeled_dir = osp.join(self.dataset_dir, 'images_labeled') self.split_classic_det_json_path = osp.join(self.dataset_dir, 'splits_classic_detected.json') self.split_classic_lab_json_path = osp.join(self.dataset_dir, 'splits_classic_labeled.json') self.split_new_det_json_path = osp.join(self.dataset_dir, 'splits_new_detected.json') self.split_new_lab_json_path = osp.join(self.dataset_dir, 'splits_new_labeled.json') self.split_new_det_mat_path = osp.join(self.dataset_dir, 'cuhk03_new_protocol_config_detected.mat') self.split_new_lab_mat_path = osp.join(self.dataset_dir, 'cuhk03_new_protocol_config_labeled.mat') self._check_before_run() self._preprocess() if cuhk03_labeled: image_type = 'labeled' split_path = self.split_classic_lab_json_path if cuhk03_classic_split else self.split_new_lab_json_path else: image_type = 'detected' split_path = self.split_classic_det_json_path if cuhk03_classic_split else self.split_new_det_json_path splits = read_json(split_path) assert split_id < len(splits), "Condition split_id ({}) < len(splits) ({}) is false".format(split_id, len(splits)) split = splits[split_id] print("Split index = {}".format(split_id)) train = split['train'] query = split['query'] gallery = split['gallery'] num_train_pids = split['num_train_pids'] num_query_pids = split['num_query_pids'] num_gallery_pids = split['num_gallery_pids'] num_total_pids = num_train_pids + num_query_pids num_train_imgs = split['num_train_imgs'] num_query_imgs = split['num_query_imgs'] num_gallery_imgs = split['num_gallery_imgs'] num_total_imgs = num_train_imgs + num_query_imgs if verbose: print("=> CUHK03 ({}) loaded".format(image_type)) print("Dataset statistics:") print(" ------------------------------") print(" subset | # ids | # images") print(" ------------------------------") print(" train | {:5d} | {:8d}".format(num_train_pids, num_train_imgs)) print(" query | {:5d} | {:8d}".format(num_query_pids, num_query_imgs)) print(" gallery | {:5d} | {:8d}".format(num_gallery_pids, num_gallery_imgs)) print(" ------------------------------") print(" total | {:5d} | {:8d}".format(num_total_pids, num_total_imgs)) print(" ------------------------------") self.train = train self.query = query self.gallery = gallery self.num_train_pids = num_train_pids self.num_query_pids = num_query_pids self.num_gallery_pids = num_gallery_pids def _check_before_run(self): if not osp.exists(self.dataset_dir): raise RuntimeError("'{}' is not available".format(self.dataset_dir)) if not osp.exists(self.data_dir): raise RuntimeError("'{}' is not available".format(self.data_dir)) if not osp.exists(self.raw_mat_path): raise RuntimeError("'{}' is not available".format(self.raw_mat_path)) if not osp.exists(self.split_new_det_mat_path): raise RuntimeError("'{}' is not available".format(self.split_new_det_mat_path)) if not osp.exists(self.split_new_lab_mat_path): raise RuntimeError("'{}' is not available".format(self.split_new_lab_mat_path)) def _preprocess(self): print("Note: if root path is changed, the previously generated json files need to be re-generated (delete them first)") if osp.exists(self.imgs_labeled_dir) and \ osp.exists(self.imgs_detected_dir) and \ osp.exists(self.split_classic_det_json_path) and \ osp.exists(self.split_classic_lab_json_path) and \ osp.exists(self.split_new_det_json_path) and \ osp.exists(self.split_new_lab_json_path): return mkdir_if_missing(self.imgs_detected_dir) mkdir_if_missing(self.imgs_labeled_dir) print("Extract image data from {} and save as png".format(self.raw_mat_path)) mat = h5py.File(self.raw_mat_path, 'r') def _deref(ref): return mat[ref][:].T def _process_images(img_refs, campid, pid, save_dir): img_paths = [] for imgid, img_ref in enumerate(img_refs): img = _deref(img_ref) if img.size == 0 or img.ndim < 3: continue viewid = 1 if imgid < 5 else 2 img_name = '{:01d}_{:03d}_{:01d}_{:02d}.png'.format(campid+1, pid+1, viewid, imgid+1) img_path = osp.join(save_dir, img_name) imsave(img_path, img) img_paths.append(img_path) return img_paths def _extract_img(name): print("Processing {} images (extract and save) ...".format(name)) meta_data = [] imgs_dir = self.imgs_detected_dir if name == 'detected' else self.imgs_labeled_dir for campid, camp_ref in enumerate(mat[name][0]): camp = _deref(camp_ref) num_pids = camp.shape[0] for pid in range(num_pids): img_paths = _process_images(camp[pid,:], campid, pid, imgs_dir) assert len(img_paths) > 0, "campid{}-pid{} has no images".format(campid, pid) meta_data.append((campid+1, pid+1, img_paths)) print("done camera pair {} with {} identities".format(campid+1, num_pids)) return meta_data meta_detected = _extract_img('detected') meta_labeled = _extract_img('labeled') def _extract_classic_split(meta_data, test_split): train, test = [], [] num_train_pids, num_test_pids = 0, 0 num_train_imgs, num_test_imgs = 0, 0 for i, (campid, pid, img_paths) in enumerate(meta_data): if [campid, pid] in test_split: for img_path in img_paths: camid = int(osp.basename(img_path).split('_')[2]) test.append((img_path, num_test_pids, camid)) num_test_pids += 1 num_test_imgs += len(img_paths) else: for img_path in img_paths: camid = int(osp.basename(img_path).split('_')[2]) train.append((img_path, num_train_pids, camid)) num_train_pids += 1 num_train_imgs += len(img_paths) return train, num_train_pids, num_train_imgs, test, num_test_pids, num_test_imgs print("Creating classic splits (# = 20) ...") splits_classic_det, splits_classic_lab = [], [] for split_ref in mat['testsets'][0]: test_split = _deref(split_ref).tolist() train, num_train_pids, num_train_imgs, test, num_test_pids, num_test_imgs = \ _extract_classic_split(meta_detected, test_split) splits_classic_det.append({ 'train': train, 'query': test, 'gallery': test, 'num_train_pids': num_train_pids, 'num_train_imgs': num_train_imgs, 'num_query_pids': num_test_pids, 'num_query_imgs': num_test_imgs, 'num_gallery_pids': num_test_pids, 'num_gallery_imgs': num_test_imgs, }) train, num_train_pids, num_train_imgs, test, num_test_pids, num_test_imgs = \ _extract_classic_split(meta_labeled, test_split) splits_classic_lab.append({ 'train': train, 'query': test, 'gallery': test, 'num_train_pids': num_train_pids, 'num_train_imgs': num_train_imgs, 'num_query_pids': num_test_pids, 'num_query_imgs': num_test_imgs, 'num_gallery_pids': num_test_pids, 'num_gallery_imgs': num_test_imgs, }) write_json(splits_classic_det, self.split_classic_det_json_path) write_json(splits_classic_lab, self.split_classic_lab_json_path) def _extract_set(filelist, pids, pid2label, idxs, img_dir, relabel): tmp_set = [] unique_pids = set() for idx in idxs: img_name = filelist[idx][0] camid = int(img_name.split('_')[2]) pid = pids[idx] if relabel: pid = pid2label[pid] img_path = osp.join(img_dir, img_name) tmp_set.append((img_path, int(pid), camid)) unique_pids.add(pid) return tmp_set, len(unique_pids), len(idxs) def _extract_new_split(split_dict, img_dir): train_idxs = split_dict['train_idx'].flatten() - 1 pids = split_dict['labels'].flatten() train_pids = set(pids[train_idxs]) pid2label = {pid: label for label, pid in enumerate(train_pids)} query_idxs = split_dict['query_idx'].flatten() - 1 gallery_idxs = split_dict['gallery_idx'].flatten() - 1 filelist = split_dict['filelist'].flatten() train_info = _extract_set(filelist, pids, pid2label, train_idxs, img_dir, relabel=True) query_info = _extract_set(filelist, pids, pid2label, query_idxs, img_dir, relabel=False) gallery_info = _extract_set(filelist, pids, pid2label, gallery_idxs, img_dir, relabel=False) return train_info, query_info, gallery_info print("Creating new splits for detected images (767/700) ...") train_info, query_info, gallery_info = _extract_new_split( loadmat(self.split_new_det_mat_path), self.imgs_detected_dir, ) splits = [{ 'train': train_info[0], 'query': query_info[0], 'gallery': gallery_info[0], 'num_train_pids': train_info[1], 'num_train_imgs': train_info[2], 'num_query_pids': query_info[1], 'num_query_imgs': query_info[2], 'num_gallery_pids': gallery_info[1], 'num_gallery_imgs': gallery_info[2], }] write_json(splits, self.split_new_det_json_path) print("Creating new splits for labeled images (767/700) ...") train_info, query_info, gallery_info = _extract_new_split( loadmat(self.split_new_lab_mat_path), self.imgs_labeled_dir, ) splits = [{ 'train': train_info[0], 'query': query_info[0], 'gallery': gallery_info[0], 'num_train_pids': train_info[1], 'num_train_imgs': train_info[2], 'num_query_pids': query_info[1], 'num_query_imgs': query_info[2], 'num_gallery_pids': gallery_info[1], 'num_gallery_imgs': gallery_info[2], }] write_json(splits, self.split_new_lab_json_path)
true
true
f725ae061cedbfc0818ee7c7320e4bbe82b540ad
62,902
py
Python
pandas/core/groupby/generic.py
selasley/pandas
5b5574520dba1e79ac95e5079724a41151c20b9a
[ "BSD-3-Clause" ]
null
null
null
pandas/core/groupby/generic.py
selasley/pandas
5b5574520dba1e79ac95e5079724a41151c20b9a
[ "BSD-3-Clause" ]
null
null
null
pandas/core/groupby/generic.py
selasley/pandas
5b5574520dba1e79ac95e5079724a41151c20b9a
[ "BSD-3-Clause" ]
null
null
null
""" Define the SeriesGroupBy and DataFrameGroupBy classes that hold the groupby interfaces (and some implementations). These are user facing as the result of the ``df.groupby(...)`` operations, which here returns a DataFrameGroupBy object. """ from __future__ import annotations from collections import abc from functools import partial from textwrap import dedent from typing import ( Any, Callable, Hashable, Iterable, Mapping, NamedTuple, Sequence, TypeVar, Union, cast, ) import warnings import numpy as np from pandas._libs import ( Interval, reduction as libreduction, ) from pandas._typing import ( ArrayLike, Manager, Manager2D, SingleManager, ) from pandas.util._decorators import ( Appender, Substitution, doc, ) from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( ensure_int64, is_bool, is_categorical_dtype, is_dict_like, is_integer_dtype, is_interval_dtype, is_scalar, ) from pandas.core.dtypes.missing import ( isna, notna, ) from pandas.core import ( algorithms, nanops, ) from pandas.core.apply import ( GroupByApply, maybe_mangle_lambdas, reconstruct_func, validate_func_kwargs, ) from pandas.core.base import SpecificationError import pandas.core.common as com from pandas.core.construction import create_series_with_explicit_dtype from pandas.core.frame import DataFrame from pandas.core.generic import NDFrame from pandas.core.groupby import base from pandas.core.groupby.groupby import ( GroupBy, _agg_template, _apply_docs, _transform_template, warn_dropping_nuisance_columns_deprecated, ) from pandas.core.groupby.grouper import get_grouper from pandas.core.indexes.api import ( Index, MultiIndex, all_indexes_same, ) from pandas.core.series import Series from pandas.core.shared_docs import _shared_docs from pandas.core.util.numba_ import maybe_use_numba from pandas.plotting import boxplot_frame_groupby # TODO(typing) the return value on this callable should be any *scalar*. AggScalar = Union[str, Callable[..., Any]] # TODO: validate types on ScalarResult and move to _typing # Blocked from using by https://github.com/python/mypy/issues/1484 # See note at _mangle_lambda_list ScalarResult = TypeVar("ScalarResult") class NamedAgg(NamedTuple): column: Hashable aggfunc: AggScalar def generate_property(name: str, klass: type[DataFrame | Series]): """ Create a property for a GroupBy subclass to dispatch to DataFrame/Series. Parameters ---------- name : str klass : {DataFrame, Series} Returns ------- property """ def prop(self): return self._make_wrapper(name) parent_method = getattr(klass, name) prop.__doc__ = parent_method.__doc__ or "" prop.__name__ = name return property(prop) def pin_allowlisted_properties( klass: type[DataFrame | Series], allowlist: frozenset[str] ): """ Create GroupBy member defs for DataFrame/Series names in a allowlist. Parameters ---------- klass : DataFrame or Series class class where members are defined. allowlist : frozenset[str] Set of names of klass methods to be constructed Returns ------- class decorator Notes ----- Since we don't want to override methods explicitly defined in the base class, any such name is skipped. """ def pinner(cls): for name in allowlist: if hasattr(cls, name): # don't override anything that was explicitly defined # in the base class continue prop = generate_property(name, klass) setattr(cls, name, prop) return cls return pinner @pin_allowlisted_properties(Series, base.series_apply_allowlist) class SeriesGroupBy(GroupBy[Series]): _apply_allowlist = base.series_apply_allowlist def _wrap_agged_manager(self, mgr: Manager) -> Series: if mgr.ndim == 1: mgr = cast(SingleManager, mgr) single = mgr else: mgr = cast(Manager2D, mgr) single = mgr.iget(0) ser = self.obj._constructor(single, name=self.obj.name) # NB: caller is responsible for setting ser.index return ser def _get_data_to_aggregate(self) -> SingleManager: ser = self._obj_with_exclusions single = ser._mgr return single def _iterate_slices(self) -> Iterable[Series]: yield self._selected_obj _agg_examples_doc = dedent( """ Examples -------- >>> s = pd.Series([1, 2, 3, 4]) >>> s 0 1 1 2 2 3 3 4 dtype: int64 >>> s.groupby([1, 1, 2, 2]).min() 1 1 2 3 dtype: int64 >>> s.groupby([1, 1, 2, 2]).agg('min') 1 1 2 3 dtype: int64 >>> s.groupby([1, 1, 2, 2]).agg(['min', 'max']) min max 1 1 2 2 3 4 The output column names can be controlled by passing the desired column names and aggregations as keyword arguments. >>> s.groupby([1, 1, 2, 2]).agg( ... minimum='min', ... maximum='max', ... ) minimum maximum 1 1 2 2 3 4 .. versionchanged:: 1.3.0 The resulting dtype will reflect the return value of the aggregating function. >>> s.groupby([1, 1, 2, 2]).agg(lambda x: x.astype(float).min()) 1 1.0 2 3.0 dtype: float64 """ ) @Appender( _apply_docs["template"].format( input="series", examples=_apply_docs["series_examples"] ) ) def apply(self, func, *args, **kwargs) -> Series: return super().apply(func, *args, **kwargs) @doc(_agg_template, examples=_agg_examples_doc, klass="Series") def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs): if maybe_use_numba(engine): with self._group_selection_context(): data = self._selected_obj result = self._aggregate_with_numba( data.to_frame(), func, *args, engine_kwargs=engine_kwargs, **kwargs ) index = self.grouper.result_index return self.obj._constructor(result.ravel(), index=index, name=data.name) relabeling = func is None columns = None if relabeling: columns, func = validate_func_kwargs(kwargs) kwargs = {} if isinstance(func, str): return getattr(self, func)(*args, **kwargs) elif isinstance(func, abc.Iterable): # Catch instances of lists / tuples # but not the class list / tuple itself. func = maybe_mangle_lambdas(func) ret = self._aggregate_multiple_funcs(func) if relabeling: # error: Incompatible types in assignment (expression has type # "Optional[List[str]]", variable has type "Index") ret.columns = columns # type: ignore[assignment] return ret else: cyfunc = com.get_cython_func(func) if cyfunc and not args and not kwargs: return getattr(self, cyfunc)() if self.grouper.nkeys > 1: return self._python_agg_general(func, *args, **kwargs) try: return self._python_agg_general(func, *args, **kwargs) except KeyError: # TODO: KeyError is raised in _python_agg_general, # see test_groupby.test_basic result = self._aggregate_named(func, *args, **kwargs) # result is a dict whose keys are the elements of result_index index = self.grouper.result_index return create_series_with_explicit_dtype( result, index=index, dtype_if_empty=object ) agg = aggregate def _aggregate_multiple_funcs(self, arg) -> DataFrame: if isinstance(arg, dict): # show the deprecation, but only if we # have not shown a higher level one # GH 15931 raise SpecificationError("nested renamer is not supported") elif any(isinstance(x, (tuple, list)) for x in arg): arg = [(x, x) if not isinstance(x, (tuple, list)) else x for x in arg] # indicated column order columns = next(zip(*arg)) else: # list of functions / function names columns = [] for f in arg: columns.append(com.get_callable_name(f) or f) arg = zip(columns, arg) results: dict[base.OutputKey, DataFrame | Series] = {} for idx, (name, func) in enumerate(arg): key = base.OutputKey(label=name, position=idx) results[key] = self.aggregate(func) if any(isinstance(x, DataFrame) for x in results.values()): from pandas import concat res_df = concat( results.values(), axis=1, keys=[key.label for key in results.keys()] ) return res_df indexed_output = {key.position: val for key, val in results.items()} output = self.obj._constructor_expanddim(indexed_output, index=None) output.columns = Index(key.label for key in results) output = self._reindex_output(output) return output def _indexed_output_to_ndframe( self, output: Mapping[base.OutputKey, ArrayLike] ) -> Series: """ Wrap the dict result of a GroupBy aggregation into a Series. """ assert len(output) == 1 values = next(iter(output.values())) result = self.obj._constructor(values) result.name = self.obj.name return result def _wrap_applied_output( self, data: Series, values: list[Any], not_indexed_same: bool = False, override_group_keys: bool = False, ) -> DataFrame | Series: """ Wrap the output of SeriesGroupBy.apply into the expected result. Parameters ---------- data : Series Input data for groupby operation. values : List[Any] Applied output for each group. not_indexed_same : bool, default False Whether the applied outputs are not indexed the same as the group axes. Returns ------- DataFrame or Series """ if len(values) == 0: # GH #6265 return self.obj._constructor( [], name=self.obj.name, index=self.grouper.result_index, dtype=data.dtype, ) assert values is not None if isinstance(values[0], dict): # GH #823 #24880 index = self.grouper.result_index res_df = self.obj._constructor_expanddim(values, index=index) res_df = self._reindex_output(res_df) # if self.observed is False, # keep all-NaN rows created while re-indexing res_ser = res_df.stack(dropna=self.observed) res_ser.name = self.obj.name return res_ser elif isinstance(values[0], (Series, DataFrame)): result = self._concat_objects( values, not_indexed_same=not_indexed_same, override_group_keys=override_group_keys, ) result.name = self.obj.name return result else: # GH #6265 #24880 result = self.obj._constructor( data=values, index=self.grouper.result_index, name=self.obj.name ) return self._reindex_output(result) def _aggregate_named(self, func, *args, **kwargs): # Note: this is very similar to _aggregate_series_pure_python, # but that does not pin group.name result = {} initialized = False for name, group in self: object.__setattr__(group, "name", name) output = func(group, *args, **kwargs) output = libreduction.extract_result(output) if not initialized: # We only do this validation on the first iteration libreduction.check_result_array(output, group.dtype) initialized = True result[name] = output return result @Substitution(klass="Series") @Appender(_transform_template) def transform(self, func, *args, engine=None, engine_kwargs=None, **kwargs): return self._transform( func, *args, engine=engine, engine_kwargs=engine_kwargs, **kwargs ) def _cython_transform( self, how: str, numeric_only: bool = True, axis: int = 0, **kwargs ): assert axis == 0 # handled by caller obj = self._selected_obj try: result = self.grouper._cython_operation( "transform", obj._values, how, axis, **kwargs ) except NotImplementedError as err: raise TypeError(f"{how} is not supported for {obj.dtype} dtype") from err return obj._constructor(result, index=self.obj.index, name=obj.name) def _transform_general(self, func: Callable, *args, **kwargs) -> Series: """ Transform with a callable func`. """ assert callable(func) klass = type(self.obj) results = [] for name, group in self: # this setattr is needed for test_transform_lambda_with_datetimetz object.__setattr__(group, "name", name) res = func(group, *args, **kwargs) results.append(klass(res, index=group.index)) # check for empty "results" to avoid concat ValueError if results: from pandas.core.reshape.concat import concat concatenated = concat(results) result = self._set_result_index_ordered(concatenated) else: result = self.obj._constructor(dtype=np.float64) result.name = self.obj.name return result def filter(self, func, dropna: bool = True, *args, **kwargs): """ Return a copy of a Series excluding elements from groups that do not satisfy the boolean criterion specified by func. Parameters ---------- func : function To apply to each group. Should return True or False. dropna : Drop groups that do not pass the filter. True by default; if False, groups that evaluate False are filled with NaNs. Notes ----- Functions that mutate the passed object can produce unexpected behavior or errors and are not supported. See :ref:`gotchas.udf-mutation` for more details. Examples -------- >>> df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', ... 'foo', 'bar'], ... 'B' : [1, 2, 3, 4, 5, 6], ... 'C' : [2.0, 5., 8., 1., 2., 9.]}) >>> grouped = df.groupby('A') >>> df.groupby('A').B.filter(lambda x: x.mean() > 3.) 1 2 3 4 5 6 Name: B, dtype: int64 Returns ------- filtered : Series """ if isinstance(func, str): wrapper = lambda x: getattr(x, func)(*args, **kwargs) else: wrapper = lambda x: func(x, *args, **kwargs) # Interpret np.nan as False. def true_and_notna(x) -> bool: b = wrapper(x) return b and notna(b) try: indices = [ self._get_index(name) for name, group in self if true_and_notna(group) ] except (ValueError, TypeError) as err: raise TypeError("the filter must return a boolean result") from err filtered = self._apply_filter(indices, dropna) return filtered def nunique(self, dropna: bool = True) -> Series: """ Return number of unique elements in the group. Returns ------- Series Number of unique values within each group. """ ids, _, _ = self.grouper.group_info val = self.obj._values codes, _ = algorithms.factorize(val, sort=False) sorter = np.lexsort((codes, ids)) codes = codes[sorter] ids = ids[sorter] # group boundaries are where group ids change # unique observations are where sorted values change idx = np.r_[0, 1 + np.nonzero(ids[1:] != ids[:-1])[0]] inc = np.r_[1, codes[1:] != codes[:-1]] # 1st item of each group is a new unique observation mask = codes == -1 if dropna: inc[idx] = 1 inc[mask] = 0 else: inc[mask & np.r_[False, mask[:-1]]] = 0 inc[idx] = 1 out = np.add.reduceat(inc, idx).astype("int64", copy=False) if len(ids): # NaN/NaT group exists if the head of ids is -1, # so remove it from res and exclude its index from idx if ids[0] == -1: res = out[1:] idx = idx[np.flatnonzero(idx)] else: res = out else: res = out[1:] ri = self.grouper.result_index # we might have duplications among the bins if len(res) != len(ri): res, out = np.zeros(len(ri), dtype=out.dtype), res res[ids[idx]] = out result = self.obj._constructor(res, index=ri, name=self.obj.name) return self._reindex_output(result, fill_value=0) @doc(Series.describe) def describe(self, **kwargs): return super().describe(**kwargs) def value_counts( self, normalize: bool = False, sort: bool = True, ascending: bool = False, bins=None, dropna: bool = True, ): from pandas.core.reshape.merge import get_join_indexers from pandas.core.reshape.tile import cut ids, _, _ = self.grouper.group_info val = self.obj._values names = self.grouper.names + [self.obj.name] if is_categorical_dtype(val.dtype) or ( bins is not None and not np.iterable(bins) ): # scalar bins cannot be done at top level # in a backward compatible way # GH38672 relates to categorical dtype ser = self.apply( Series.value_counts, normalize=normalize, sort=sort, ascending=ascending, bins=bins, ) ser.index.names = names return ser # groupby removes null keys from groupings mask = ids != -1 ids, val = ids[mask], val[mask] if bins is None: lab, lev = algorithms.factorize(val, sort=True) llab = lambda lab, inc: lab[inc] else: # lab is a Categorical with categories an IntervalIndex lab = cut(Series(val), bins, include_lowest=True) # error: "ndarray" has no attribute "cat" lev = lab.cat.categories # type: ignore[attr-defined] # error: No overload variant of "take" of "_ArrayOrScalarCommon" matches # argument types "Any", "bool", "Union[Any, float]" lab = lev.take( # type: ignore[call-overload] # error: "ndarray" has no attribute "cat" lab.cat.codes, # type: ignore[attr-defined] allow_fill=True, # error: Item "ndarray" of "Union[ndarray, Index]" has no attribute # "_na_value" fill_value=lev._na_value, # type: ignore[union-attr] ) llab = lambda lab, inc: lab[inc]._multiindex.codes[-1] if is_interval_dtype(lab.dtype): # TODO: should we do this inside II? lab_interval = cast(Interval, lab) sorter = np.lexsort((lab_interval.left, lab_interval.right, ids)) else: sorter = np.lexsort((lab, ids)) ids, lab = ids[sorter], lab[sorter] # group boundaries are where group ids change idchanges = 1 + np.nonzero(ids[1:] != ids[:-1])[0] idx = np.r_[0, idchanges] if not len(ids): idx = idchanges # new values are where sorted labels change lchanges = llab(lab, slice(1, None)) != llab(lab, slice(None, -1)) inc = np.r_[True, lchanges] if not len(val): inc = lchanges inc[idx] = True # group boundaries are also new values out = np.diff(np.nonzero(np.r_[inc, True])[0]) # value counts # num. of times each group should be repeated rep = partial(np.repeat, repeats=np.add.reduceat(inc, idx)) # multi-index components codes = self.grouper.reconstructed_codes codes = [rep(level_codes) for level_codes in codes] + [llab(lab, inc)] # error: List item 0 has incompatible type "Union[ndarray[Any, Any], Index]"; # expected "Index" levels = [ping.group_index for ping in self.grouper.groupings] + [ lev # type: ignore[list-item] ] if dropna: mask = codes[-1] != -1 if mask.all(): dropna = False else: out, codes = out[mask], [level_codes[mask] for level_codes in codes] if normalize: out = out.astype("float") d = np.diff(np.r_[idx, len(ids)]) if dropna: m = ids[lab == -1] np.add.at(d, m, -1) acc = rep(d)[mask] else: acc = rep(d) out /= acc if sort and bins is None: cat = ids[inc][mask] if dropna else ids[inc] sorter = np.lexsort((out if ascending else -out, cat)) out, codes[-1] = out[sorter], codes[-1][sorter] if bins is not None: # for compat. with libgroupby.value_counts need to ensure every # bin is present at every index level, null filled with zeros diff = np.zeros(len(out), dtype="bool") for level_codes in codes[:-1]: diff |= np.r_[True, level_codes[1:] != level_codes[:-1]] ncat, nbin = diff.sum(), len(levels[-1]) left = [np.repeat(np.arange(ncat), nbin), np.tile(np.arange(nbin), ncat)] right = [diff.cumsum() - 1, codes[-1]] _, idx = get_join_indexers(left, right, sort=False, how="left") out = np.where(idx != -1, out[idx], 0) if sort: sorter = np.lexsort((out if ascending else -out, left[0])) out, left[-1] = out[sorter], left[-1][sorter] # build the multi-index w/ full levels def build_codes(lev_codes: np.ndarray) -> np.ndarray: return np.repeat(lev_codes[diff], nbin) codes = [build_codes(lev_codes) for lev_codes in codes[:-1]] codes.append(left[-1]) mi = MultiIndex(levels=levels, codes=codes, names=names, verify_integrity=False) if is_integer_dtype(out.dtype): out = ensure_int64(out) return self.obj._constructor(out, index=mi, name=self.obj.name) @doc(Series.nlargest) def nlargest(self, n: int = 5, keep: str = "first"): f = partial(Series.nlargest, n=n, keep=keep) data = self._obj_with_exclusions # Don't change behavior if result index happens to be the same, i.e. # already ordered and n >= all group sizes. result = self._python_apply_general(f, data, not_indexed_same=True) return result @doc(Series.nsmallest) def nsmallest(self, n: int = 5, keep: str = "first"): f = partial(Series.nsmallest, n=n, keep=keep) data = self._obj_with_exclusions # Don't change behavior if result index happens to be the same, i.e. # already ordered and n >= all group sizes. result = self._python_apply_general(f, data, not_indexed_same=True) return result @pin_allowlisted_properties(DataFrame, base.dataframe_apply_allowlist) class DataFrameGroupBy(GroupBy[DataFrame]): _apply_allowlist = base.dataframe_apply_allowlist _agg_examples_doc = dedent( """ Examples -------- >>> df = pd.DataFrame( ... { ... "A": [1, 1, 2, 2], ... "B": [1, 2, 3, 4], ... "C": [0.362838, 0.227877, 1.267767, -0.562860], ... } ... ) >>> df A B C 0 1 1 0.362838 1 1 2 0.227877 2 2 3 1.267767 3 2 4 -0.562860 The aggregation is for each column. >>> df.groupby('A').agg('min') B C A 1 1 0.227877 2 3 -0.562860 Multiple aggregations >>> df.groupby('A').agg(['min', 'max']) B C min max min max A 1 1 2 0.227877 0.362838 2 3 4 -0.562860 1.267767 Select a column for aggregation >>> df.groupby('A').B.agg(['min', 'max']) min max A 1 1 2 2 3 4 Different aggregations per column >>> df.groupby('A').agg({'B': ['min', 'max'], 'C': 'sum'}) B C min max sum A 1 1 2 0.590715 2 3 4 0.704907 To control the output names with different aggregations per column, pandas supports "named aggregation" >>> df.groupby("A").agg( ... b_min=pd.NamedAgg(column="B", aggfunc="min"), ... c_sum=pd.NamedAgg(column="C", aggfunc="sum")) b_min c_sum A 1 1 0.590715 2 3 0.704907 - The keywords are the *output* column names - The values are tuples whose first element is the column to select and the second element is the aggregation to apply to that column. Pandas provides the ``pandas.NamedAgg`` namedtuple with the fields ``['column', 'aggfunc']`` to make it clearer what the arguments are. As usual, the aggregation can be a callable or a string alias. See :ref:`groupby.aggregate.named` for more. .. versionchanged:: 1.3.0 The resulting dtype will reflect the return value of the aggregating function. >>> df.groupby("A")[["B"]].agg(lambda x: x.astype(float).min()) B A 1 1.0 2 3.0 """ ) @doc(_agg_template, examples=_agg_examples_doc, klass="DataFrame") def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs): if maybe_use_numba(engine): with self._group_selection_context(): data = self._selected_obj result = self._aggregate_with_numba( data, func, *args, engine_kwargs=engine_kwargs, **kwargs ) index = self.grouper.result_index return self.obj._constructor(result, index=index, columns=data.columns) relabeling, func, columns, order = reconstruct_func(func, **kwargs) func = maybe_mangle_lambdas(func) op = GroupByApply(self, func, args, kwargs) result = op.agg() if not is_dict_like(func) and result is not None: return result elif relabeling and result is not None: # this should be the only (non-raising) case with relabeling # used reordered index of columns result = result.iloc[:, order] result.columns = columns if result is None: # grouper specific aggregations if self.grouper.nkeys > 1: # test_groupby_as_index_series_scalar gets here with 'not self.as_index' return self._python_agg_general(func, *args, **kwargs) elif args or kwargs: # test_pass_args_kwargs gets here (with and without as_index) # can't return early result = self._aggregate_frame(func, *args, **kwargs) elif self.axis == 1: # _aggregate_multiple_funcs does not allow self.axis == 1 # Note: axis == 1 precludes 'not self.as_index', see __init__ result = self._aggregate_frame(func) return result else: # try to treat as if we are passing a list gba = GroupByApply(self, [func], args=(), kwargs={}) try: result = gba.agg() except ValueError as err: if "no results" not in str(err): # raised directly by _aggregate_multiple_funcs raise result = self._aggregate_frame(func) else: sobj = self._selected_obj if isinstance(sobj, Series): # GH#35246 test_groupby_as_index_select_column_sum_empty_df result.columns = self._obj_with_exclusions.columns.copy() else: # Retain our column names result.columns._set_names( sobj.columns.names, level=list(range(sobj.columns.nlevels)) ) # select everything except for the last level, which is the one # containing the name of the function(s), see GH#32040 result.columns = result.columns.droplevel(-1) if not self.as_index: self._insert_inaxis_grouper_inplace(result) result.index = Index(range(len(result))) return result agg = aggregate def _iterate_slices(self) -> Iterable[Series]: obj = self._selected_obj if self.axis == 1: obj = obj.T if isinstance(obj, Series) and obj.name not in self.exclusions: # Occurs when doing DataFrameGroupBy(...)["X"] yield obj else: for label, values in obj.items(): if label in self.exclusions: continue yield values def _aggregate_frame(self, func, *args, **kwargs) -> DataFrame: if self.grouper.nkeys != 1: raise AssertionError("Number of keys must be 1") obj = self._obj_with_exclusions result: dict[Hashable, NDFrame | np.ndarray] = {} if self.axis == 0: # test_pass_args_kwargs_duplicate_columns gets here with non-unique columns for name, data in self: fres = func(data, *args, **kwargs) result[name] = fres else: # we get here in a number of test_multilevel tests for name in self.indices: grp_df = self.get_group(name, obj=obj) fres = func(grp_df, *args, **kwargs) result[name] = fres result_index = self.grouper.result_index other_ax = obj.axes[1 - self.axis] out = self.obj._constructor(result, index=other_ax, columns=result_index) if self.axis == 0: out = out.T return out def _aggregate_item_by_item(self, func, *args, **kwargs) -> DataFrame: # only for axis==0 # tests that get here with non-unique cols: # test_resample_with_timedelta_yields_no_empty_groups, # test_resample_apply_product obj = self._obj_with_exclusions result: dict[int, NDFrame] = {} for i, (item, sgb) in enumerate(self._iterate_column_groupbys(obj)): result[i] = sgb.aggregate(func, *args, **kwargs) res_df = self.obj._constructor(result) res_df.columns = obj.columns return res_df def _wrap_applied_output( self, data: DataFrame, values: list, not_indexed_same: bool = False, override_group_keys: bool = False, ): if len(values) == 0: result = self.obj._constructor( index=self.grouper.result_index, columns=data.columns ) result = result.astype(data.dtypes, copy=False) return result # GH12824 first_not_none = next(com.not_none(*values), None) if first_not_none is None: # GH9684 - All values are None, return an empty frame. return self.obj._constructor() elif isinstance(first_not_none, DataFrame): return self._concat_objects( values, not_indexed_same=not_indexed_same, override_group_keys=override_group_keys, ) key_index = self.grouper.result_index if self.as_index else None if isinstance(first_not_none, (np.ndarray, Index)): # GH#1738: values is list of arrays of unequal lengths # fall through to the outer else clause # TODO: sure this is right? we used to do this # after raising AttributeError above return self.obj._constructor_sliced( values, index=key_index, name=self._selection ) elif not isinstance(first_not_none, Series): # values are not series or array-like but scalars # self._selection not passed through to Series as the # result should not take the name of original selection # of columns if self.as_index: return self.obj._constructor_sliced(values, index=key_index) else: result = self.obj._constructor(values, columns=[self._selection]) self._insert_inaxis_grouper_inplace(result) return result else: # values are Series return self._wrap_applied_output_series( values, not_indexed_same, first_not_none, key_index, override_group_keys, ) def _wrap_applied_output_series( self, values: list[Series], not_indexed_same: bool, first_not_none, key_index, override_group_keys: bool, ) -> DataFrame | Series: # this is to silence a DeprecationWarning # TODO(2.0): Remove when default dtype of empty Series is object kwargs = first_not_none._construct_axes_dict() backup = create_series_with_explicit_dtype(dtype_if_empty=object, **kwargs) values = [x if (x is not None) else backup for x in values] all_indexed_same = all_indexes_same(x.index for x in values) # GH3596 # provide a reduction (Frame -> Series) if groups are # unique if self.squeeze: applied_index = self._selected_obj._get_axis(self.axis) singular_series = len(values) == 1 and applied_index.nlevels == 1 if singular_series: # GH2893 # we have series in the values array, we want to # produce a series: # if any of the sub-series are not indexed the same # OR we don't have a multi-index and we have only a # single values return self._concat_objects( values, not_indexed_same=not_indexed_same, override_group_keys=override_group_keys, ) # still a series # path added as of GH 5545 elif all_indexed_same: from pandas.core.reshape.concat import concat return concat(values) if not all_indexed_same: # GH 8467 return self._concat_objects( values, not_indexed_same=True, override_group_keys=override_group_keys, ) # Combine values # vstack+constructor is faster than concat and handles MI-columns stacked_values = np.vstack([np.asarray(v) for v in values]) if self.axis == 0: index = key_index columns = first_not_none.index.copy() if columns.name is None: # GH6124 - propagate name of Series when it's consistent names = {v.name for v in values} if len(names) == 1: columns.name = list(names)[0] else: index = first_not_none.index columns = key_index stacked_values = stacked_values.T if stacked_values.dtype == object: # We'll have the DataFrame constructor do inference stacked_values = stacked_values.tolist() result = self.obj._constructor(stacked_values, index=index, columns=columns) if not self.as_index: self._insert_inaxis_grouper_inplace(result) return self._reindex_output(result) def _cython_transform( self, how: str, numeric_only: bool = True, axis: int = 0, **kwargs ) -> DataFrame: assert axis == 0 # handled by caller # TODO: no tests with self.ndim == 1 for DataFrameGroupBy # With self.axis == 0, we have multi-block tests # e.g. test_rank_min_int, test_cython_transform_frame # test_transform_numeric_ret # With self.axis == 1, _get_data_to_aggregate does a transpose # so we always have a single block. mgr: Manager2D = self._get_data_to_aggregate() if numeric_only: mgr = mgr.get_numeric_data(copy=False) def arr_func(bvalues: ArrayLike) -> ArrayLike: return self.grouper._cython_operation( "transform", bvalues, how, 1, **kwargs ) # We could use `mgr.apply` here and not have to set_axis, but # we would have to do shape gymnastics for ArrayManager compat res_mgr = mgr.grouped_reduce(arr_func, ignore_failures=True) res_mgr.set_axis(1, mgr.axes[1]) if len(res_mgr) < len(mgr): warn_dropping_nuisance_columns_deprecated(type(self), how) res_df = self.obj._constructor(res_mgr) if self.axis == 1: res_df = res_df.T return res_df def _transform_general(self, func, *args, **kwargs): from pandas.core.reshape.concat import concat applied = [] obj = self._obj_with_exclusions gen = self.grouper.get_iterator(obj, axis=self.axis) fast_path, slow_path = self._define_paths(func, *args, **kwargs) # Determine whether to use slow or fast path by evaluating on the first group. # Need to handle the case of an empty generator and process the result so that # it does not need to be computed again. try: name, group = next(gen) except StopIteration: pass else: object.__setattr__(group, "name", name) try: path, res = self._choose_path(fast_path, slow_path, group) except TypeError: return self._transform_item_by_item(obj, fast_path) except ValueError as err: msg = "transform must return a scalar value for each group" raise ValueError(msg) from err if group.size > 0: res = _wrap_transform_general_frame(self.obj, group, res) applied.append(res) # Compute and process with the remaining groups for name, group in gen: if group.size == 0: continue object.__setattr__(group, "name", name) res = path(group) res = _wrap_transform_general_frame(self.obj, group, res) applied.append(res) concat_index = obj.columns if self.axis == 0 else obj.index other_axis = 1 if self.axis == 0 else 0 # switches between 0 & 1 concatenated = concat(applied, axis=self.axis, verify_integrity=False) concatenated = concatenated.reindex(concat_index, axis=other_axis, copy=False) return self._set_result_index_ordered(concatenated) @Substitution(klass="DataFrame") @Appender(_transform_template) def transform(self, func, *args, engine=None, engine_kwargs=None, **kwargs): return self._transform( func, *args, engine=engine, engine_kwargs=engine_kwargs, **kwargs ) def _define_paths(self, func, *args, **kwargs): if isinstance(func, str): fast_path = lambda group: getattr(group, func)(*args, **kwargs) slow_path = lambda group: group.apply( lambda x: getattr(x, func)(*args, **kwargs), axis=self.axis ) else: fast_path = lambda group: func(group, *args, **kwargs) slow_path = lambda group: group.apply( lambda x: func(x, *args, **kwargs), axis=self.axis ) return fast_path, slow_path def _choose_path(self, fast_path: Callable, slow_path: Callable, group: DataFrame): path = slow_path res = slow_path(group) if self.ngroups == 1: # no need to evaluate multiple paths when only # a single group exists return path, res # if we make it here, test if we can use the fast path try: res_fast = fast_path(group) except AssertionError: raise # pragma: no cover except Exception: # GH#29631 For user-defined function, we can't predict what may be # raised; see test_transform.test_transform_fastpath_raises return path, res # verify fast path returns either: # a DataFrame with columns equal to group.columns # OR a Series with index equal to group.columns if isinstance(res_fast, DataFrame): if not res_fast.columns.equals(group.columns): return path, res elif isinstance(res_fast, Series): if not res_fast.index.equals(group.columns): return path, res else: return path, res if res_fast.equals(res): path = fast_path return path, res def _transform_item_by_item(self, obj: DataFrame, wrapper) -> DataFrame: # iterate through columns, see test_transform_exclude_nuisance # gets here with non-unique columns output = {} inds = [] for i, (colname, sgb) in enumerate(self._iterate_column_groupbys(obj)): try: output[i] = sgb.transform(wrapper) except TypeError: # e.g. trying to call nanmean with string values warn_dropping_nuisance_columns_deprecated(type(self), "transform") else: inds.append(i) if not output: raise TypeError("Transform function invalid for data types") columns = obj.columns.take(inds) result = self.obj._constructor(output, index=obj.index) result.columns = columns return result def filter(self, func, dropna=True, *args, **kwargs): """ Return a copy of a DataFrame excluding filtered elements. Elements from groups are filtered if they do not satisfy the boolean criterion specified by func. Parameters ---------- func : function Function to apply to each subframe. Should return True or False. dropna : Drop groups that do not pass the filter. True by default; If False, groups that evaluate False are filled with NaNs. Returns ------- filtered : DataFrame Notes ----- Each subframe is endowed the attribute 'name' in case you need to know which group you are working on. Functions that mutate the passed object can produce unexpected behavior or errors and are not supported. See :ref:`gotchas.udf-mutation` for more details. Examples -------- >>> df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', ... 'foo', 'bar'], ... 'B' : [1, 2, 3, 4, 5, 6], ... 'C' : [2.0, 5., 8., 1., 2., 9.]}) >>> grouped = df.groupby('A') >>> grouped.filter(lambda x: x['B'].mean() > 3.) A B C 1 bar 2 5.0 3 bar 4 1.0 5 bar 6 9.0 """ indices = [] obj = self._selected_obj gen = self.grouper.get_iterator(obj, axis=self.axis) for name, group in gen: object.__setattr__(group, "name", name) res = func(group, *args, **kwargs) try: res = res.squeeze() except AttributeError: # allow e.g., scalars and frames to pass pass # interpret the result of the filter if is_bool(res) or (is_scalar(res) and isna(res)): if res and notna(res): indices.append(self._get_index(name)) else: # non scalars aren't allowed raise TypeError( f"filter function returned a {type(res).__name__}, " "but expected a scalar bool" ) return self._apply_filter(indices, dropna) def __getitem__(self, key) -> DataFrameGroupBy | SeriesGroupBy: if self.axis == 1: # GH 37725 raise ValueError("Cannot subset columns when using axis=1") # per GH 23566 if isinstance(key, tuple) and len(key) > 1: # if len == 1, then it becomes a SeriesGroupBy and this is actually # valid syntax, so don't raise warning warnings.warn( "Indexing with multiple keys (implicitly converted to a tuple " "of keys) will be deprecated, use a list instead.", FutureWarning, stacklevel=find_stack_level(), ) return super().__getitem__(key) def _gotitem(self, key, ndim: int, subset=None): """ sub-classes to define return a sliced object Parameters ---------- key : string / list of selections ndim : {1, 2} requested ndim of result subset : object, default None subset to act on """ if ndim == 2: if subset is None: subset = self.obj return DataFrameGroupBy( subset, self.grouper, axis=self.axis, level=self.level, grouper=self.grouper, exclusions=self.exclusions, selection=key, as_index=self.as_index, sort=self.sort, group_keys=self.group_keys, squeeze=self.squeeze, observed=self.observed, mutated=self.mutated, dropna=self.dropna, ) elif ndim == 1: if subset is None: subset = self.obj[key] return SeriesGroupBy( subset, level=self.level, grouper=self.grouper, selection=key, sort=self.sort, group_keys=self.group_keys, squeeze=self.squeeze, observed=self.observed, dropna=self.dropna, ) raise AssertionError("invalid ndim for _gotitem") def _get_data_to_aggregate(self) -> Manager2D: obj = self._obj_with_exclusions if self.axis == 1: return obj.T._mgr else: return obj._mgr def _insert_inaxis_grouper_inplace(self, result: DataFrame) -> None: # zip in reverse so we can always insert at loc 0 columns = result.columns for name, lev, in_axis in zip( reversed(self.grouper.names), reversed(self.grouper.get_group_levels()), reversed([grp.in_axis for grp in self.grouper.groupings]), ): # GH #28549 # When using .apply(-), name will be in columns already if in_axis and name not in columns: result.insert(0, name, lev) def _indexed_output_to_ndframe( self, output: Mapping[base.OutputKey, ArrayLike] ) -> DataFrame: """ Wrap the dict result of a GroupBy aggregation into a DataFrame. """ indexed_output = {key.position: val for key, val in output.items()} columns = Index([key.label for key in output]) columns._set_names(self._obj_with_exclusions._get_axis(1 - self.axis).names) result = self.obj._constructor(indexed_output) result.columns = columns return result def _wrap_agged_manager(self, mgr: Manager2D) -> DataFrame: if not self.as_index: # GH 41998 - empty mgr always gets index of length 0 rows = mgr.shape[1] if mgr.shape[0] > 0 else 0 index = Index(range(rows)) mgr.set_axis(1, index) result = self.obj._constructor(mgr) self._insert_inaxis_grouper_inplace(result) result = result._consolidate() else: index = self.grouper.result_index mgr.set_axis(1, index) result = self.obj._constructor(mgr) if self.axis == 1: result = result.T # Note: we only need to pass datetime=True in order to get numeric # values converted return self._reindex_output(result)._convert(datetime=True) def _iterate_column_groupbys(self, obj: DataFrame | Series): for i, colname in enumerate(obj.columns): yield colname, SeriesGroupBy( obj.iloc[:, i], selection=colname, grouper=self.grouper, exclusions=self.exclusions, observed=self.observed, ) def _apply_to_column_groupbys(self, func, obj: DataFrame | Series) -> DataFrame: from pandas.core.reshape.concat import concat columns = obj.columns results = [ func(col_groupby) for _, col_groupby in self._iterate_column_groupbys(obj) ] if not len(results): # concat would raise return DataFrame([], columns=columns, index=self.grouper.result_index) else: return concat(results, keys=columns, axis=1) def nunique(self, dropna: bool = True) -> DataFrame: """ Return DataFrame with counts of unique elements in each position. Parameters ---------- dropna : bool, default True Don't include NaN in the counts. Returns ------- nunique: DataFrame Examples -------- >>> df = pd.DataFrame({'id': ['spam', 'egg', 'egg', 'spam', ... 'ham', 'ham'], ... 'value1': [1, 5, 5, 2, 5, 5], ... 'value2': list('abbaxy')}) >>> df id value1 value2 0 spam 1 a 1 egg 5 b 2 egg 5 b 3 spam 2 a 4 ham 5 x 5 ham 5 y >>> df.groupby('id').nunique() value1 value2 id egg 1 1 ham 1 2 spam 2 1 Check for rows with the same id but conflicting values: >>> df.groupby('id').filter(lambda g: (g.nunique() > 1).any()) id value1 value2 0 spam 1 a 3 spam 2 a 4 ham 5 x 5 ham 5 y """ if self.axis != 0: # see test_groupby_crash_on_nunique return self._python_agg_general(lambda sgb: sgb.nunique(dropna)) obj = self._obj_with_exclusions results = self._apply_to_column_groupbys( lambda sgb: sgb.nunique(dropna), obj=obj ) if not self.as_index: results.index = Index(range(len(results))) self._insert_inaxis_grouper_inplace(results) return results @doc( _shared_docs["idxmax"], numeric_only_default="True for axis=0, False for axis=1", ) def idxmax(self, axis=0, skipna: bool = True, numeric_only: bool | None = None): axis = DataFrame._get_axis_number(axis) if numeric_only is None: numeric_only = None if axis == 0 else False def func(df): # NB: here we use numeric_only=None, in DataFrame it is False GH#38217 res = df._reduce( nanops.nanargmax, "argmax", axis=axis, skipna=skipna, numeric_only=numeric_only, ) indices = res._values index = df._get_axis(axis) result = [index[i] if i >= 0 else np.nan for i in indices] return df._constructor_sliced(result, index=res.index) func.__name__ = "idxmax" return self._python_apply_general(func, self._obj_with_exclusions) @doc( _shared_docs["idxmin"], numeric_only_default="True for axis=0, False for axis=1", ) def idxmin(self, axis=0, skipna: bool = True, numeric_only: bool | None = None): axis = DataFrame._get_axis_number(axis) if numeric_only is None: numeric_only = None if axis == 0 else False def func(df): # NB: here we use numeric_only=None, in DataFrame it is False GH#46560 res = df._reduce( nanops.nanargmin, "argmin", axis=axis, skipna=skipna, numeric_only=numeric_only, ) indices = res._values index = df._get_axis(axis) result = [index[i] if i >= 0 else np.nan for i in indices] return df._constructor_sliced(result, index=res.index) func.__name__ = "idxmin" return self._python_apply_general(func, self._obj_with_exclusions) boxplot = boxplot_frame_groupby def value_counts( self, subset: Sequence[Hashable] | None = None, normalize: bool = False, sort: bool = True, ascending: bool = False, dropna: bool = True, ) -> DataFrame | Series: """ Return a Series or DataFrame containing counts of unique rows. .. versionadded:: 1.4.0 Parameters ---------- subset : list-like, optional Columns to use when counting unique combinations. normalize : bool, default False Return proportions rather than frequencies. sort : bool, default True Sort by frequencies. ascending : bool, default False Sort in ascending order. dropna : bool, default True Don’t include counts of rows that contain NA values. Returns ------- Series or DataFrame Series if the groupby as_index is True, otherwise DataFrame. See Also -------- Series.value_counts: Equivalent method on Series. DataFrame.value_counts: Equivalent method on DataFrame. SeriesGroupBy.value_counts: Equivalent method on SeriesGroupBy. Notes ----- - If the groupby as_index is True then the returned Series will have a MultiIndex with one level per input column. - If the groupby as_index is False then the returned DataFrame will have an additional column with the value_counts. The column is labelled 'count' or 'proportion', depending on the ``normalize`` parameter. By default, rows that contain any NA values are omitted from the result. By default, the result will be in descending order so that the first element of each group is the most frequently-occurring row. Examples -------- >>> df = pd.DataFrame({ ... 'gender': ['male', 'male', 'female', 'male', 'female', 'male'], ... 'education': ['low', 'medium', 'high', 'low', 'high', 'low'], ... 'country': ['US', 'FR', 'US', 'FR', 'FR', 'FR'] ... }) >>> df gender education country 0 male low US 1 male medium FR 2 female high US 3 male low FR 4 female high FR 5 male low FR >>> df.groupby('gender').value_counts() gender education country female high FR 1 US 1 male low FR 2 US 1 medium FR 1 dtype: int64 >>> df.groupby('gender').value_counts(ascending=True) gender education country female high FR 1 US 1 male low US 1 medium FR 1 low FR 2 dtype: int64 >>> df.groupby('gender').value_counts(normalize=True) gender education country female high FR 0.50 US 0.50 male low FR 0.50 US 0.25 medium FR 0.25 dtype: float64 >>> df.groupby('gender', as_index=False).value_counts() gender education country count 0 female high FR 1 1 female high US 1 2 male low FR 2 3 male low US 1 4 male medium FR 1 >>> df.groupby('gender', as_index=False).value_counts(normalize=True) gender education country proportion 0 female high FR 0.50 1 female high US 0.50 2 male low FR 0.50 3 male low US 0.25 4 male medium FR 0.25 """ if self.axis == 1: raise NotImplementedError( "DataFrameGroupBy.value_counts only handles axis=0" ) with self._group_selection_context(): df = self.obj in_axis_names = { grouping.name for grouping in self.grouper.groupings if grouping.in_axis } if isinstance(self._selected_obj, Series): name = self._selected_obj.name keys = [] if name in in_axis_names else [self._selected_obj] else: keys = [ # Can't use .values because the column label needs to be preserved self._selected_obj.iloc[:, idx] for idx, name in enumerate(self._selected_obj.columns) if name not in in_axis_names ] if subset is not None: clashing = set(subset) & set(in_axis_names) if clashing: raise ValueError( f"Keys {clashing} in subset cannot be in " "the groupby column keys" ) groupings = list(self.grouper.groupings) for key in keys: grouper, _, _ = get_grouper( df, key=key, axis=self.axis, sort=self.sort, dropna=dropna, ) groupings += list(grouper.groupings) # Take the size of the overall columns gb = df.groupby( groupings, sort=self.sort, observed=self.observed, dropna=self.dropna, ) result_series = cast(Series, gb.size()) if normalize: # Normalize the results by dividing by the original group sizes. # We are guaranteed to have the first N levels be the # user-requested grouping. levels = list( range(len(self.grouper.groupings), result_series.index.nlevels) ) indexed_group_size = result_series.groupby( result_series.index.droplevel(levels), sort=self.sort, observed=self.observed, dropna=self.dropna, ).transform("sum") result_series /= indexed_group_size if sort: # Sort the values and then resort by the main grouping index_level = range(len(self.grouper.groupings)) result_series = result_series.sort_values( ascending=ascending ).sort_index(level=index_level, sort_remaining=False) result: Series | DataFrame if self.as_index: result = result_series else: # Convert to frame name = "proportion" if normalize else "count" index = result_series.index columns = com.fill_missing_names(index.names) if name in columns: raise ValueError( f"Column label '{name}' is duplicate of result column" ) result_series.name = name result_series.index = index.set_names(range(len(columns))) result_frame = result_series.reset_index() result_frame.columns = columns + [name] result = result_frame return result.__finalize__(self.obj, method="value_counts") def _wrap_transform_general_frame( obj: DataFrame, group: DataFrame, res: DataFrame | Series ) -> DataFrame: from pandas import concat if isinstance(res, Series): # we need to broadcast across the # other dimension; this will preserve dtypes # GH14457 if res.index.is_(obj.index): res_frame = concat([res] * len(group.columns), axis=1) res_frame.columns = group.columns res_frame.index = group.index else: res_frame = obj._constructor( np.tile(res.values, (len(group.index), 1)), columns=group.columns, index=group.index, ) assert isinstance(res_frame, DataFrame) return res_frame else: return res
34.204459
88
0.555833
from __future__ import annotations from collections import abc from functools import partial from textwrap import dedent from typing import ( Any, Callable, Hashable, Iterable, Mapping, NamedTuple, Sequence, TypeVar, Union, cast, ) import warnings import numpy as np from pandas._libs import ( Interval, reduction as libreduction, ) from pandas._typing import ( ArrayLike, Manager, Manager2D, SingleManager, ) from pandas.util._decorators import ( Appender, Substitution, doc, ) from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( ensure_int64, is_bool, is_categorical_dtype, is_dict_like, is_integer_dtype, is_interval_dtype, is_scalar, ) from pandas.core.dtypes.missing import ( isna, notna, ) from pandas.core import ( algorithms, nanops, ) from pandas.core.apply import ( GroupByApply, maybe_mangle_lambdas, reconstruct_func, validate_func_kwargs, ) from pandas.core.base import SpecificationError import pandas.core.common as com from pandas.core.construction import create_series_with_explicit_dtype from pandas.core.frame import DataFrame from pandas.core.generic import NDFrame from pandas.core.groupby import base from pandas.core.groupby.groupby import ( GroupBy, _agg_template, _apply_docs, _transform_template, warn_dropping_nuisance_columns_deprecated, ) from pandas.core.groupby.grouper import get_grouper from pandas.core.indexes.api import ( Index, MultiIndex, all_indexes_same, ) from pandas.core.series import Series from pandas.core.shared_docs import _shared_docs from pandas.core.util.numba_ import maybe_use_numba from pandas.plotting import boxplot_frame_groupby AggScalar = Union[str, Callable[..., Any]] ScalarResult = TypeVar("ScalarResult") class NamedAgg(NamedTuple): column: Hashable aggfunc: AggScalar def generate_property(name: str, klass: type[DataFrame | Series]): def prop(self): return self._make_wrapper(name) parent_method = getattr(klass, name) prop.__doc__ = parent_method.__doc__ or "" prop.__name__ = name return property(prop) def pin_allowlisted_properties( klass: type[DataFrame | Series], allowlist: frozenset[str] ): def pinner(cls): for name in allowlist: if hasattr(cls, name): # in the base class continue prop = generate_property(name, klass) setattr(cls, name, prop) return cls return pinner @pin_allowlisted_properties(Series, base.series_apply_allowlist) class SeriesGroupBy(GroupBy[Series]): _apply_allowlist = base.series_apply_allowlist def _wrap_agged_manager(self, mgr: Manager) -> Series: if mgr.ndim == 1: mgr = cast(SingleManager, mgr) single = mgr else: mgr = cast(Manager2D, mgr) single = mgr.iget(0) ser = self.obj._constructor(single, name=self.obj.name) # NB: caller is responsible for setting ser.index return ser def _get_data_to_aggregate(self) -> SingleManager: ser = self._obj_with_exclusions single = ser._mgr return single def _iterate_slices(self) -> Iterable[Series]: yield self._selected_obj _agg_examples_doc = dedent( """ Examples -------- >>> s = pd.Series([1, 2, 3, 4]) >>> s 0 1 1 2 2 3 3 4 dtype: int64 >>> s.groupby([1, 1, 2, 2]).min() 1 1 2 3 dtype: int64 >>> s.groupby([1, 1, 2, 2]).agg('min') 1 1 2 3 dtype: int64 >>> s.groupby([1, 1, 2, 2]).agg(['min', 'max']) min max 1 1 2 2 3 4 The output column names can be controlled by passing the desired column names and aggregations as keyword arguments. >>> s.groupby([1, 1, 2, 2]).agg( ... minimum='min', ... maximum='max', ... ) minimum maximum 1 1 2 2 3 4 .. versionchanged:: 1.3.0 The resulting dtype will reflect the return value of the aggregating function. >>> s.groupby([1, 1, 2, 2]).agg(lambda x: x.astype(float).min()) 1 1.0 2 3.0 dtype: float64 """ ) @Appender( _apply_docs["template"].format( input="series", examples=_apply_docs["series_examples"] ) ) def apply(self, func, *args, **kwargs) -> Series: return super().apply(func, *args, **kwargs) @doc(_agg_template, examples=_agg_examples_doc, klass="Series") def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs): if maybe_use_numba(engine): with self._group_selection_context(): data = self._selected_obj result = self._aggregate_with_numba( data.to_frame(), func, *args, engine_kwargs=engine_kwargs, **kwargs ) index = self.grouper.result_index return self.obj._constructor(result.ravel(), index=index, name=data.name) relabeling = func is None columns = None if relabeling: columns, func = validate_func_kwargs(kwargs) kwargs = {} if isinstance(func, str): return getattr(self, func)(*args, **kwargs) elif isinstance(func, abc.Iterable): # Catch instances of lists / tuples # but not the class list / tuple itself. func = maybe_mangle_lambdas(func) ret = self._aggregate_multiple_funcs(func) if relabeling: # error: Incompatible types in assignment (expression has type # "Optional[List[str]]", variable has type "Index") ret.columns = columns # type: ignore[assignment] return ret else: cyfunc = com.get_cython_func(func) if cyfunc and not args and not kwargs: return getattr(self, cyfunc)() if self.grouper.nkeys > 1: return self._python_agg_general(func, *args, **kwargs) try: return self._python_agg_general(func, *args, **kwargs) except KeyError: # TODO: KeyError is raised in _python_agg_general, # see test_groupby.test_basic result = self._aggregate_named(func, *args, **kwargs) # result is a dict whose keys are the elements of result_index index = self.grouper.result_index return create_series_with_explicit_dtype( result, index=index, dtype_if_empty=object ) agg = aggregate def _aggregate_multiple_funcs(self, arg) -> DataFrame: if isinstance(arg, dict): # show the deprecation, but only if we # have not shown a higher level one # GH 15931 raise SpecificationError("nested renamer is not supported") elif any(isinstance(x, (tuple, list)) for x in arg): arg = [(x, x) if not isinstance(x, (tuple, list)) else x for x in arg] # indicated column order columns = next(zip(*arg)) else: # list of functions / function names columns = [] for f in arg: columns.append(com.get_callable_name(f) or f) arg = zip(columns, arg) results: dict[base.OutputKey, DataFrame | Series] = {} for idx, (name, func) in enumerate(arg): key = base.OutputKey(label=name, position=idx) results[key] = self.aggregate(func) if any(isinstance(x, DataFrame) for x in results.values()): from pandas import concat res_df = concat( results.values(), axis=1, keys=[key.label for key in results.keys()] ) return res_df indexed_output = {key.position: val for key, val in results.items()} output = self.obj._constructor_expanddim(indexed_output, index=None) output.columns = Index(key.label for key in results) output = self._reindex_output(output) return output def _indexed_output_to_ndframe( self, output: Mapping[base.OutputKey, ArrayLike] ) -> Series: assert len(output) == 1 values = next(iter(output.values())) result = self.obj._constructor(values) result.name = self.obj.name return result def _wrap_applied_output( self, data: Series, values: list[Any], not_indexed_same: bool = False, override_group_keys: bool = False, ) -> DataFrame | Series: if len(values) == 0: # GH #6265 return self.obj._constructor( [], name=self.obj.name, index=self.grouper.result_index, dtype=data.dtype, ) assert values is not None if isinstance(values[0], dict): # GH #823 #24880 index = self.grouper.result_index res_df = self.obj._constructor_expanddim(values, index=index) res_df = self._reindex_output(res_df) # if self.observed is False, # keep all-NaN rows created while re-indexing res_ser = res_df.stack(dropna=self.observed) res_ser.name = self.obj.name return res_ser elif isinstance(values[0], (Series, DataFrame)): result = self._concat_objects( values, not_indexed_same=not_indexed_same, override_group_keys=override_group_keys, ) result.name = self.obj.name return result else: # GH #6265 #24880 result = self.obj._constructor( data=values, index=self.grouper.result_index, name=self.obj.name ) return self._reindex_output(result) def _aggregate_named(self, func, *args, **kwargs): # Note: this is very similar to _aggregate_series_pure_python, # but that does not pin group.name result = {} initialized = False for name, group in self: object.__setattr__(group, "name", name) output = func(group, *args, **kwargs) output = libreduction.extract_result(output) if not initialized: # We only do this validation on the first iteration libreduction.check_result_array(output, group.dtype) initialized = True result[name] = output return result @Substitution(klass="Series") @Appender(_transform_template) def transform(self, func, *args, engine=None, engine_kwargs=None, **kwargs): return self._transform( func, *args, engine=engine, engine_kwargs=engine_kwargs, **kwargs ) def _cython_transform( self, how: str, numeric_only: bool = True, axis: int = 0, **kwargs ): assert axis == 0 # handled by caller obj = self._selected_obj try: result = self.grouper._cython_operation( "transform", obj._values, how, axis, **kwargs ) except NotImplementedError as err: raise TypeError(f"{how} is not supported for {obj.dtype} dtype") from err return obj._constructor(result, index=self.obj.index, name=obj.name) def _transform_general(self, func: Callable, *args, **kwargs) -> Series: assert callable(func) klass = type(self.obj) results = [] for name, group in self: # this setattr is needed for test_transform_lambda_with_datetimetz object.__setattr__(group, "name", name) res = func(group, *args, **kwargs) results.append(klass(res, index=group.index)) # check for empty "results" to avoid concat ValueError if results: from pandas.core.reshape.concat import concat concatenated = concat(results) result = self._set_result_index_ordered(concatenated) else: result = self.obj._constructor(dtype=np.float64) result.name = self.obj.name return result def filter(self, func, dropna: bool = True, *args, **kwargs): if isinstance(func, str): wrapper = lambda x: getattr(x, func)(*args, **kwargs) else: wrapper = lambda x: func(x, *args, **kwargs) # Interpret np.nan as False. def true_and_notna(x) -> bool: b = wrapper(x) return b and notna(b) try: indices = [ self._get_index(name) for name, group in self if true_and_notna(group) ] except (ValueError, TypeError) as err: raise TypeError("the filter must return a boolean result") from err filtered = self._apply_filter(indices, dropna) return filtered def nunique(self, dropna: bool = True) -> Series: ids, _, _ = self.grouper.group_info val = self.obj._values codes, _ = algorithms.factorize(val, sort=False) sorter = np.lexsort((codes, ids)) codes = codes[sorter] ids = ids[sorter] # group boundaries are where group ids change # unique observations are where sorted values change idx = np.r_[0, 1 + np.nonzero(ids[1:] != ids[:-1])[0]] inc = np.r_[1, codes[1:] != codes[:-1]] # 1st item of each group is a new unique observation mask = codes == -1 if dropna: inc[idx] = 1 inc[mask] = 0 else: inc[mask & np.r_[False, mask[:-1]]] = 0 inc[idx] = 1 out = np.add.reduceat(inc, idx).astype("int64", copy=False) if len(ids): # NaN/NaT group exists if the head of ids is -1, # so remove it from res and exclude its index from idx if ids[0] == -1: res = out[1:] idx = idx[np.flatnonzero(idx)] else: res = out else: res = out[1:] ri = self.grouper.result_index # we might have duplications among the bins if len(res) != len(ri): res, out = np.zeros(len(ri), dtype=out.dtype), res res[ids[idx]] = out result = self.obj._constructor(res, index=ri, name=self.obj.name) return self._reindex_output(result, fill_value=0) @doc(Series.describe) def describe(self, **kwargs): return super().describe(**kwargs) def value_counts( self, normalize: bool = False, sort: bool = True, ascending: bool = False, bins=None, dropna: bool = True, ): from pandas.core.reshape.merge import get_join_indexers from pandas.core.reshape.tile import cut ids, _, _ = self.grouper.group_info val = self.obj._values names = self.grouper.names + [self.obj.name] if is_categorical_dtype(val.dtype) or ( bins is not None and not np.iterable(bins) ): # scalar bins cannot be done at top level # in a backward compatible way # GH38672 relates to categorical dtype ser = self.apply( Series.value_counts, normalize=normalize, sort=sort, ascending=ascending, bins=bins, ) ser.index.names = names return ser # groupby removes null keys from groupings mask = ids != -1 ids, val = ids[mask], val[mask] if bins is None: lab, lev = algorithms.factorize(val, sort=True) llab = lambda lab, inc: lab[inc] else: # lab is a Categorical with categories an IntervalIndex lab = cut(Series(val), bins, include_lowest=True) # error: "ndarray" has no attribute "cat" lev = lab.cat.categories # type: ignore[attr-defined] # error: No overload variant of "take" of "_ArrayOrScalarCommon" matches # argument types "Any", "bool", "Union[Any, float]" lab = lev.take( # type: ignore[call-overload] # error: "ndarray" has no attribute "cat" lab.cat.codes, # type: ignore[attr-defined] allow_fill=True, # error: Item "ndarray" of "Union[ndarray, Index]" has no attribute # "_na_value" fill_value=lev._na_value, # type: ignore[union-attr] ) llab = lambda lab, inc: lab[inc]._multiindex.codes[-1] if is_interval_dtype(lab.dtype): # TODO: should we do this inside II? lab_interval = cast(Interval, lab) sorter = np.lexsort((lab_interval.left, lab_interval.right, ids)) else: sorter = np.lexsort((lab, ids)) ids, lab = ids[sorter], lab[sorter] # group boundaries are where group ids change idchanges = 1 + np.nonzero(ids[1:] != ids[:-1])[0] idx = np.r_[0, idchanges] if not len(ids): idx = idchanges # new values are where sorted labels change lchanges = llab(lab, slice(1, None)) != llab(lab, slice(None, -1)) inc = np.r_[True, lchanges] if not len(val): inc = lchanges inc[idx] = True # group boundaries are also new values out = np.diff(np.nonzero(np.r_[inc, True])[0]) # value counts # num. of times each group should be repeated rep = partial(np.repeat, repeats=np.add.reduceat(inc, idx)) # multi-index components codes = self.grouper.reconstructed_codes codes = [rep(level_codes) for level_codes in codes] + [llab(lab, inc)] # error: List item 0 has incompatible type "Union[ndarray[Any, Any], Index]"; # expected "Index" levels = [ping.group_index for ping in self.grouper.groupings] + [ lev # type: ignore[list-item] ] if dropna: mask = codes[-1] != -1 if mask.all(): dropna = False else: out, codes = out[mask], [level_codes[mask] for level_codes in codes] if normalize: out = out.astype("float") d = np.diff(np.r_[idx, len(ids)]) if dropna: m = ids[lab == -1] np.add.at(d, m, -1) acc = rep(d)[mask] else: acc = rep(d) out /= acc if sort and bins is None: cat = ids[inc][mask] if dropna else ids[inc] sorter = np.lexsort((out if ascending else -out, cat)) out, codes[-1] = out[sorter], codes[-1][sorter] if bins is not None: # for compat. with libgroupby.value_counts need to ensure every # bin is present at every index level, null filled with zeros diff = np.zeros(len(out), dtype="bool") for level_codes in codes[:-1]: diff |= np.r_[True, level_codes[1:] != level_codes[:-1]] ncat, nbin = diff.sum(), len(levels[-1]) left = [np.repeat(np.arange(ncat), nbin), np.tile(np.arange(nbin), ncat)] right = [diff.cumsum() - 1, codes[-1]] _, idx = get_join_indexers(left, right, sort=False, how="left") out = np.where(idx != -1, out[idx], 0) if sort: sorter = np.lexsort((out if ascending else -out, left[0])) out, left[-1] = out[sorter], left[-1][sorter] # build the multi-index w/ full levels def build_codes(lev_codes: np.ndarray) -> np.ndarray: return np.repeat(lev_codes[diff], nbin) codes = [build_codes(lev_codes) for lev_codes in codes[:-1]] codes.append(left[-1]) mi = MultiIndex(levels=levels, codes=codes, names=names, verify_integrity=False) if is_integer_dtype(out.dtype): out = ensure_int64(out) return self.obj._constructor(out, index=mi, name=self.obj.name) @doc(Series.nlargest) def nlargest(self, n: int = 5, keep: str = "first"): f = partial(Series.nlargest, n=n, keep=keep) data = self._obj_with_exclusions # Don't change behavior if result index happens to be the same, i.e. result = self._python_apply_general(f, data, not_indexed_same=True) return result @doc(Series.nsmallest) def nsmallest(self, n: int = 5, keep: str = "first"): f = partial(Series.nsmallest, n=n, keep=keep) data = self._obj_with_exclusions # already ordered and n >= all group sizes. result = self._python_apply_general(f, data, not_indexed_same=True) return result @pin_allowlisted_properties(DataFrame, base.dataframe_apply_allowlist) class DataFrameGroupBy(GroupBy[DataFrame]): _apply_allowlist = base.dataframe_apply_allowlist _agg_examples_doc = dedent( """ Examples -------- >>> df = pd.DataFrame( ... { ... "A": [1, 1, 2, 2], ... "B": [1, 2, 3, 4], ... "C": [0.362838, 0.227877, 1.267767, -0.562860], ... } ... ) >>> df A B C 0 1 1 0.362838 1 1 2 0.227877 2 2 3 1.267767 3 2 4 -0.562860 The aggregation is for each column. >>> df.groupby('A').agg('min') B C A 1 1 0.227877 2 3 -0.562860 Multiple aggregations >>> df.groupby('A').agg(['min', 'max']) B C min max min max A 1 1 2 0.227877 0.362838 2 3 4 -0.562860 1.267767 Select a column for aggregation >>> df.groupby('A').B.agg(['min', 'max']) min max A 1 1 2 2 3 4 Different aggregations per column >>> df.groupby('A').agg({'B': ['min', 'max'], 'C': 'sum'}) B C min max sum A 1 1 2 0.590715 2 3 4 0.704907 To control the output names with different aggregations per column, pandas supports "named aggregation" >>> df.groupby("A").agg( ... b_min=pd.NamedAgg(column="B", aggfunc="min"), ... c_sum=pd.NamedAgg(column="C", aggfunc="sum")) b_min c_sum A 1 1 0.590715 2 3 0.704907 - The keywords are the *output* column names - The values are tuples whose first element is the column to select and the second element is the aggregation to apply to that column. Pandas provides the ``pandas.NamedAgg`` namedtuple with the fields ``['column', 'aggfunc']`` to make it clearer what the arguments are. As usual, the aggregation can be a callable or a string alias. See :ref:`groupby.aggregate.named` for more. .. versionchanged:: 1.3.0 The resulting dtype will reflect the return value of the aggregating function. >>> df.groupby("A")[["B"]].agg(lambda x: x.astype(float).min()) B A 1 1.0 2 3.0 """ ) @doc(_agg_template, examples=_agg_examples_doc, klass="DataFrame") def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs): if maybe_use_numba(engine): with self._group_selection_context(): data = self._selected_obj result = self._aggregate_with_numba( data, func, *args, engine_kwargs=engine_kwargs, **kwargs ) index = self.grouper.result_index return self.obj._constructor(result, index=index, columns=data.columns) relabeling, func, columns, order = reconstruct_func(func, **kwargs) func = maybe_mangle_lambdas(func) op = GroupByApply(self, func, args, kwargs) result = op.agg() if not is_dict_like(func) and result is not None: return result elif relabeling and result is not None: # this should be the only (non-raising) case with relabeling # used reordered index of columns result = result.iloc[:, order] result.columns = columns if result is None: # grouper specific aggregations if self.grouper.nkeys > 1: # test_groupby_as_index_series_scalar gets here with 'not self.as_index' return self._python_agg_general(func, *args, **kwargs) elif args or kwargs: # test_pass_args_kwargs gets here (with and without as_index) # can't return early result = self._aggregate_frame(func, *args, **kwargs) elif self.axis == 1: result = self._aggregate_frame(func) return result else: gba = GroupByApply(self, [func], args=(), kwargs={}) try: result = gba.agg() except ValueError as err: if "no results" not in str(err): raise result = self._aggregate_frame(func) else: sobj = self._selected_obj if isinstance(sobj, Series): h_exclusions.columns.copy() else: result.columns._set_names( sobj.columns.names, level=list(range(sobj.columns.nlevels)) ) result.columns = result.columns.droplevel(-1) if not self.as_index: self._insert_inaxis_grouper_inplace(result) result.index = Index(range(len(result))) return result agg = aggregate def _iterate_slices(self) -> Iterable[Series]: obj = self._selected_obj if self.axis == 1: obj = obj.T if isinstance(obj, Series) and obj.name not in self.exclusions: yield obj else: for label, values in obj.items(): if label in self.exclusions: continue yield values def _aggregate_frame(self, func, *args, **kwargs) -> DataFrame: if self.grouper.nkeys != 1: raise AssertionError("Number of keys must be 1") obj = self._obj_with_exclusions result: dict[Hashable, NDFrame | np.ndarray] = {} if self.axis == 0: for name, data in self: fres = func(data, *args, **kwargs) result[name] = fres else: for name in self.indices: grp_df = self.get_group(name, obj=obj) fres = func(grp_df, *args, **kwargs) result[name] = fres result_index = self.grouper.result_index other_ax = obj.axes[1 - self.axis] out = self.obj._constructor(result, index=other_ax, columns=result_index) if self.axis == 0: out = out.T return out def _aggregate_item_by_item(self, func, *args, **kwargs) -> DataFrame: obj = self._obj_with_exclusions result: dict[int, NDFrame] = {} for i, (item, sgb) in enumerate(self._iterate_column_groupbys(obj)): result[i] = sgb.aggregate(func, *args, **kwargs) res_df = self.obj._constructor(result) res_df.columns = obj.columns return res_df def _wrap_applied_output( self, data: DataFrame, values: list, not_indexed_same: bool = False, override_group_keys: bool = False, ): if len(values) == 0: result = self.obj._constructor( index=self.grouper.result_index, columns=data.columns ) result = result.astype(data.dtypes, copy=False) return result first_not_none = next(com.not_none(*values), None) if first_not_none is None: return self.obj._constructor() elif isinstance(first_not_none, DataFrame): return self._concat_objects( values, not_indexed_same=not_indexed_same, override_group_keys=override_group_keys, ) key_index = self.grouper.result_index if self.as_index else None if isinstance(first_not_none, (np.ndarray, Index)): return self.obj._constructor_sliced( values, index=key_index, name=self._selection ) elif not isinstance(first_not_none, Series): if self.as_index: return self.obj._constructor_sliced(values, index=key_index) else: result = self.obj._constructor(values, columns=[self._selection]) self._insert_inaxis_grouper_inplace(result) return result else: return self._wrap_applied_output_series( values, not_indexed_same, first_not_none, key_index, override_group_keys, ) def _wrap_applied_output_series( self, values: list[Series], not_indexed_same: bool, first_not_none, key_index, override_group_keys: bool, ) -> DataFrame | Series: kwargs = first_not_none._construct_axes_dict() backup = create_series_with_explicit_dtype(dtype_if_empty=object, **kwargs) values = [x if (x is not None) else backup for x in values] all_indexed_same = all_indexes_same(x.index for x in values) if self.squeeze: applied_index = self._selected_obj._get_axis(self.axis) singular_series = len(values) == 1 and applied_index.nlevels == 1 if singular_series: # single values return self._concat_objects( values, not_indexed_same=not_indexed_same, override_group_keys=override_group_keys, ) # still a series # path added as of GH 5545 elif all_indexed_same: from pandas.core.reshape.concat import concat return concat(values) if not all_indexed_same: # GH 8467 return self._concat_objects( values, not_indexed_same=True, override_group_keys=override_group_keys, ) # Combine values # vstack+constructor is faster than concat and handles MI-columns stacked_values = np.vstack([np.asarray(v) for v in values]) if self.axis == 0: index = key_index columns = first_not_none.index.copy() if columns.name is None: # GH6124 - propagate name of Series when it's consistent names = {v.name for v in values} if len(names) == 1: columns.name = list(names)[0] else: index = first_not_none.index columns = key_index stacked_values = stacked_values.T if stacked_values.dtype == object: stacked_values = stacked_values.tolist() result = self.obj._constructor(stacked_values, index=index, columns=columns) if not self.as_index: self._insert_inaxis_grouper_inplace(result) return self._reindex_output(result) def _cython_transform( self, how: str, numeric_only: bool = True, axis: int = 0, **kwargs ) -> DataFrame: assert axis == 0 # handled by caller # TODO: no tests with self.ndim == 1 for DataFrameGroupBy # With self.axis == 0, we have multi-block tests # e.g. test_rank_min_int, test_cython_transform_frame # test_transform_numeric_ret # With self.axis == 1, _get_data_to_aggregate does a transpose # so we always have a single block. mgr: Manager2D = self._get_data_to_aggregate() if numeric_only: mgr = mgr.get_numeric_data(copy=False) def arr_func(bvalues: ArrayLike) -> ArrayLike: return self.grouper._cython_operation( "transform", bvalues, how, 1, **kwargs ) # We could use `mgr.apply` here and not have to set_axis, but # we would have to do shape gymnastics for ArrayManager compat res_mgr = mgr.grouped_reduce(arr_func, ignore_failures=True) res_mgr.set_axis(1, mgr.axes[1]) if len(res_mgr) < len(mgr): warn_dropping_nuisance_columns_deprecated(type(self), how) res_df = self.obj._constructor(res_mgr) if self.axis == 1: res_df = res_df.T return res_df def _transform_general(self, func, *args, **kwargs): from pandas.core.reshape.concat import concat applied = [] obj = self._obj_with_exclusions gen = self.grouper.get_iterator(obj, axis=self.axis) fast_path, slow_path = self._define_paths(func, *args, **kwargs) # Determine whether to use slow or fast path by evaluating on the first group. # Need to handle the case of an empty generator and process the result so that # it does not need to be computed again. try: name, group = next(gen) except StopIteration: pass else: object.__setattr__(group, "name", name) try: path, res = self._choose_path(fast_path, slow_path, group) except TypeError: return self._transform_item_by_item(obj, fast_path) except ValueError as err: msg = "transform must return a scalar value for each group" raise ValueError(msg) from err if group.size > 0: res = _wrap_transform_general_frame(self.obj, group, res) applied.append(res) # Compute and process with the remaining groups for name, group in gen: if group.size == 0: continue object.__setattr__(group, "name", name) res = path(group) res = _wrap_transform_general_frame(self.obj, group, res) applied.append(res) concat_index = obj.columns if self.axis == 0 else obj.index other_axis = 1 if self.axis == 0 else 0 # switches between 0 & 1 concatenated = concat(applied, axis=self.axis, verify_integrity=False) concatenated = concatenated.reindex(concat_index, axis=other_axis, copy=False) return self._set_result_index_ordered(concatenated) @Substitution(klass="DataFrame") @Appender(_transform_template) def transform(self, func, *args, engine=None, engine_kwargs=None, **kwargs): return self._transform( func, *args, engine=engine, engine_kwargs=engine_kwargs, **kwargs ) def _define_paths(self, func, *args, **kwargs): if isinstance(func, str): fast_path = lambda group: getattr(group, func)(*args, **kwargs) slow_path = lambda group: group.apply( lambda x: getattr(x, func)(*args, **kwargs), axis=self.axis ) else: fast_path = lambda group: func(group, *args, **kwargs) slow_path = lambda group: group.apply( lambda x: func(x, *args, **kwargs), axis=self.axis ) return fast_path, slow_path def _choose_path(self, fast_path: Callable, slow_path: Callable, group: DataFrame): path = slow_path res = slow_path(group) if self.ngroups == 1: # no need to evaluate multiple paths when only # a single group exists return path, res # if we make it here, test if we can use the fast path try: res_fast = fast_path(group) except AssertionError: raise # pragma: no cover except Exception: # GH#29631 For user-defined function, we can't predict what may be return path, res if isinstance(res_fast, DataFrame): if not res_fast.columns.equals(group.columns): return path, res elif isinstance(res_fast, Series): if not res_fast.index.equals(group.columns): return path, res else: return path, res if res_fast.equals(res): path = fast_path return path, res def _transform_item_by_item(self, obj: DataFrame, wrapper) -> DataFrame: output = {} inds = [] for i, (colname, sgb) in enumerate(self._iterate_column_groupbys(obj)): try: output[i] = sgb.transform(wrapper) except TypeError: warn_dropping_nuisance_columns_deprecated(type(self), "transform") else: inds.append(i) if not output: raise TypeError("Transform function invalid for data types") columns = obj.columns.take(inds) result = self.obj._constructor(output, index=obj.index) result.columns = columns return result def filter(self, func, dropna=True, *args, **kwargs): indices = [] obj = self._selected_obj gen = self.grouper.get_iterator(obj, axis=self.axis) for name, group in gen: object.__setattr__(group, "name", name) res = func(group, *args, **kwargs) try: res = res.squeeze() except AttributeError: pass if is_bool(res) or (is_scalar(res) and isna(res)): if res and notna(res): indices.append(self._get_index(name)) else: raise TypeError( f"filter function returned a {type(res).__name__}, " "but expected a scalar bool" ) return self._apply_filter(indices, dropna) def __getitem__(self, key) -> DataFrameGroupBy | SeriesGroupBy: if self.axis == 1: # GH 37725 raise ValueError("Cannot subset columns when using axis=1") # per GH 23566 if isinstance(key, tuple) and len(key) > 1: # if len == 1, then it becomes a SeriesGroupBy and this is actually # valid syntax, so don't raise warning warnings.warn( "Indexing with multiple keys (implicitly converted to a tuple " "of keys) will be deprecated, use a list instead.", FutureWarning, stacklevel=find_stack_level(), ) return super().__getitem__(key) def _gotitem(self, key, ndim: int, subset=None): if ndim == 2: if subset is None: subset = self.obj return DataFrameGroupBy( subset, self.grouper, axis=self.axis, level=self.level, grouper=self.grouper, exclusions=self.exclusions, selection=key, as_index=self.as_index, sort=self.sort, group_keys=self.group_keys, squeeze=self.squeeze, observed=self.observed, mutated=self.mutated, dropna=self.dropna, ) elif ndim == 1: if subset is None: subset = self.obj[key] return SeriesGroupBy( subset, level=self.level, grouper=self.grouper, selection=key, sort=self.sort, group_keys=self.group_keys, squeeze=self.squeeze, observed=self.observed, dropna=self.dropna, ) raise AssertionError("invalid ndim for _gotitem") def _get_data_to_aggregate(self) -> Manager2D: obj = self._obj_with_exclusions if self.axis == 1: return obj.T._mgr else: return obj._mgr def _insert_inaxis_grouper_inplace(self, result: DataFrame) -> None: columns = result.columns for name, lev, in_axis in zip( reversed(self.grouper.names), reversed(self.grouper.get_group_levels()), reversed([grp.in_axis for grp in self.grouper.groupings]), ): if in_axis and name not in columns: result.insert(0, name, lev) def _indexed_output_to_ndframe( self, output: Mapping[base.OutputKey, ArrayLike] ) -> DataFrame: indexed_output = {key.position: val for key, val in output.items()} columns = Index([key.label for key in output]) columns._set_names(self._obj_with_exclusions._get_axis(1 - self.axis).names) result = self.obj._constructor(indexed_output) result.columns = columns return result def _wrap_agged_manager(self, mgr: Manager2D) -> DataFrame: if not self.as_index: rows = mgr.shape[1] if mgr.shape[0] > 0 else 0 index = Index(range(rows)) mgr.set_axis(1, index) result = self.obj._constructor(mgr) self._insert_inaxis_grouper_inplace(result) result = result._consolidate() else: index = self.grouper.result_index mgr.set_axis(1, index) result = self.obj._constructor(mgr) if self.axis == 1: result = result.T return self._reindex_output(result)._convert(datetime=True) def _iterate_column_groupbys(self, obj: DataFrame | Series): for i, colname in enumerate(obj.columns): yield colname, SeriesGroupBy( obj.iloc[:, i], selection=colname, grouper=self.grouper, exclusions=self.exclusions, observed=self.observed, ) def _apply_to_column_groupbys(self, func, obj: DataFrame | Series) -> DataFrame: from pandas.core.reshape.concat import concat columns = obj.columns results = [ func(col_groupby) for _, col_groupby in self._iterate_column_groupbys(obj) ] if not len(results): return DataFrame([], columns=columns, index=self.grouper.result_index) else: return concat(results, keys=columns, axis=1) def nunique(self, dropna: bool = True) -> DataFrame: if self.axis != 0: return self._python_agg_general(lambda sgb: sgb.nunique(dropna)) obj = self._obj_with_exclusions results = self._apply_to_column_groupbys( lambda sgb: sgb.nunique(dropna), obj=obj ) if not self.as_index: results.index = Index(range(len(results))) self._insert_inaxis_grouper_inplace(results) return results @doc( _shared_docs["idxmax"], numeric_only_default="True for axis=0, False for axis=1", ) def idxmax(self, axis=0, skipna: bool = True, numeric_only: bool | None = None): axis = DataFrame._get_axis_number(axis) if numeric_only is None: numeric_only = None if axis == 0 else False def func(df): res = df._reduce( nanops.nanargmax, "argmax", axis=axis, skipna=skipna, numeric_only=numeric_only, ) indices = res._values index = df._get_axis(axis) result = [index[i] if i >= 0 else np.nan for i in indices] return df._constructor_sliced(result, index=res.index) func.__name__ = "idxmax" return self._python_apply_general(func, self._obj_with_exclusions) @doc( _shared_docs["idxmin"], numeric_only_default="True for axis=0, False for axis=1", ) def idxmin(self, axis=0, skipna: bool = True, numeric_only: bool | None = None): axis = DataFrame._get_axis_number(axis) if numeric_only is None: numeric_only = None if axis == 0 else False def func(df): res = df._reduce( nanops.nanargmin, "argmin", axis=axis, skipna=skipna, numeric_only=numeric_only, ) indices = res._values index = df._get_axis(axis) result = [index[i] if i >= 0 else np.nan for i in indices] return df._constructor_sliced(result, index=res.index) func.__name__ = "idxmin" return self._python_apply_general(func, self._obj_with_exclusions) boxplot = boxplot_frame_groupby def value_counts( self, subset: Sequence[Hashable] | None = None, normalize: bool = False, sort: bool = True, ascending: bool = False, dropna: bool = True, ) -> DataFrame | Series: if self.axis == 1: raise NotImplementedError( "DataFrameGroupBy.value_counts only handles axis=0" ) with self._group_selection_context(): df = self.obj in_axis_names = { grouping.name for grouping in self.grouper.groupings if grouping.in_axis } if isinstance(self._selected_obj, Series): name = self._selected_obj.name keys = [] if name in in_axis_names else [self._selected_obj] else: keys = [ self._selected_obj.iloc[:, idx] for idx, name in enumerate(self._selected_obj.columns) if name not in in_axis_names ] if subset is not None: clashing = set(subset) & set(in_axis_names) if clashing: raise ValueError( f"Keys {clashing} in subset cannot be in " "the groupby column keys" ) groupings = list(self.grouper.groupings) for key in keys: grouper, _, _ = get_grouper( df, key=key, axis=self.axis, sort=self.sort, dropna=dropna, ) groupings += list(grouper.groupings) # Take the size of the overall columns gb = df.groupby( groupings, sort=self.sort, observed=self.observed, dropna=self.dropna, ) result_series = cast(Series, gb.size()) if normalize: # Normalize the results by dividing by the original group sizes. # We are guaranteed to have the first N levels be the # user-requested grouping. levels = list( range(len(self.grouper.groupings), result_series.index.nlevels) ) indexed_group_size = result_series.groupby( result_series.index.droplevel(levels), sort=self.sort, observed=self.observed, dropna=self.dropna, ).transform("sum") result_series /= indexed_group_size if sort: # Sort the values and then resort by the main grouping index_level = range(len(self.grouper.groupings)) result_series = result_series.sort_values( ascending=ascending ).sort_index(level=index_level, sort_remaining=False) result: Series | DataFrame if self.as_index: result = result_series else: # Convert to frame name = "proportion" if normalize else "count" index = result_series.index columns = com.fill_missing_names(index.names) if name in columns: raise ValueError( f"Column label '{name}' is duplicate of result column" ) result_series.name = name result_series.index = index.set_names(range(len(columns))) result_frame = result_series.reset_index() result_frame.columns = columns + [name] result = result_frame return result.__finalize__(self.obj, method="value_counts") def _wrap_transform_general_frame( obj: DataFrame, group: DataFrame, res: DataFrame | Series ) -> DataFrame: from pandas import concat if isinstance(res, Series): # we need to broadcast across the # other dimension; this will preserve dtypes # GH14457 if res.index.is_(obj.index): res_frame = concat([res] * len(group.columns), axis=1) res_frame.columns = group.columns res_frame.index = group.index else: res_frame = obj._constructor( np.tile(res.values, (len(group.index), 1)), columns=group.columns, index=group.index, ) assert isinstance(res_frame, DataFrame) return res_frame else: return res
true
true
f725aeade897e373631ced4d97f1f6a440b377d9
1,600
py
Python
utils/runner/optimizer/builder.py
UESTC-Liuxin/CVMI_Sementic_Segmentation
dc5bf6e940cf6961ef65abb6e7ec372f29d55249
[ "Apache-2.0" ]
null
null
null
utils/runner/optimizer/builder.py
UESTC-Liuxin/CVMI_Sementic_Segmentation
dc5bf6e940cf6961ef65abb6e7ec372f29d55249
[ "Apache-2.0" ]
null
null
null
utils/runner/optimizer/builder.py
UESTC-Liuxin/CVMI_Sementic_Segmentation
dc5bf6e940cf6961ef65abb6e7ec372f29d55249
[ "Apache-2.0" ]
null
null
null
''' Author: Liu Xin Date: 2021-11-21 18:10:58 LastEditors: Liu Xin LastEditTime: 2021-11-21 21:38:30 Description: file content FilePath: /CVMI_Sementic_Segmentation/utils/runner/optimizer/builder.py ''' import copy import inspect import torch from utils.registry import Registry, build OPTIMIZERS = Registry('optimizer') OPTIMIZER_BUILDERS = Registry('optimizer builder') def register_torch_optimizers(): """ @description : 通过扫描torvh.optim文件,获取torch实现的优化器对象 @param : @Returns : """ torch_optimizers = [] for module_name in dir(torch.optim): if module_name.startswith('__'): continue _optim = getattr(torch.optim, module_name) if inspect.isclass(_optim) and issubclass(_optim, torch.optim.Optimizer): OPTIMIZERS.register_module(_optim.__name__)(_optim) torch_optimizers.append(module_name) return torch_optimizers TORCH_OPTIMIZERS = register_torch_optimizers() def build_optimizer_constructor(cfg): return build(cfg, OPTIMIZER_BUILDERS) def build_optimizer(model, cfg): optimizer_cfg = copy.deepcopy(cfg) constructor_type = optimizer_cfg.pop('constructor', 'DefaultOptimizerConstructor') paramwise_cfg = optimizer_cfg.pop('paramwise_cfg', None) optim_constructor = build_optimizer_constructor( dict( name=constructor_type, optimizer_cfg=optimizer_cfg, paramwise_cfg=paramwise_cfg)) optimizer = optim_constructor(model) return optimizer
30.188679
73
0.683125
import copy import inspect import torch from utils.registry import Registry, build OPTIMIZERS = Registry('optimizer') OPTIMIZER_BUILDERS = Registry('optimizer builder') def register_torch_optimizers(): torch_optimizers = [] for module_name in dir(torch.optim): if module_name.startswith('__'): continue _optim = getattr(torch.optim, module_name) if inspect.isclass(_optim) and issubclass(_optim, torch.optim.Optimizer): OPTIMIZERS.register_module(_optim.__name__)(_optim) torch_optimizers.append(module_name) return torch_optimizers TORCH_OPTIMIZERS = register_torch_optimizers() def build_optimizer_constructor(cfg): return build(cfg, OPTIMIZER_BUILDERS) def build_optimizer(model, cfg): optimizer_cfg = copy.deepcopy(cfg) constructor_type = optimizer_cfg.pop('constructor', 'DefaultOptimizerConstructor') paramwise_cfg = optimizer_cfg.pop('paramwise_cfg', None) optim_constructor = build_optimizer_constructor( dict( name=constructor_type, optimizer_cfg=optimizer_cfg, paramwise_cfg=paramwise_cfg)) optimizer = optim_constructor(model) return optimizer
true
true
f725afde370dd3d08133a4a847cf11682d4bc65e
30
py
Python
py_yahoo/__init__.py
satheshrgs/py_yahoo
c18d680a9c75bb28364b95ada8b4dead0302d6ed
[ "MIT" ]
null
null
null
py_yahoo/__init__.py
satheshrgs/py_yahoo
c18d680a9c75bb28364b95ada8b4dead0302d6ed
[ "MIT" ]
null
null
null
py_yahoo/__init__.py
satheshrgs/py_yahoo
c18d680a9c75bb28364b95ada8b4dead0302d6ed
[ "MIT" ]
null
null
null
from .py_yahoo import YWeather
30
30
0.866667
from .py_yahoo import YWeather
true
true
f725b02ef1848fb30f10583d1d0ba4ed093eebfa
878
py
Python
examples/demo1/main.py
Layto888/laylib-1.0.1
c7317c29659a476adf6e90eb729b09ce4c49e219
[ "MIT" ]
1
2018-08-04T14:44:42.000Z
2018-08-04T14:44:42.000Z
examples/demo1/main.py
Layto888/laylib-1.0
c7317c29659a476adf6e90eb729b09ce4c49e219
[ "MIT" ]
null
null
null
examples/demo1/main.py
Layto888/laylib-1.0
c7317c29659a476adf6e90eb729b09ce4c49e219
[ "MIT" ]
null
null
null
""" Demo 01 Made with python and pygame to test and improve the laylib-pygame framework for fast game prototyping. ---- Author: Amardjia Amine Date: 20/10/18 Github: --- - This demo shows how the Resources manager loads and separates the different data and their associated variables. All resources are showed in the terminal after running your program. """ from laylib import Environment from engine import Engine import sys def main(): # init global environment demo = Environment( 800, # width 600, # height False, # full screen '2D Demo' # window title ) # load resources, set the game demo.load_complete(Engine(), '../data') # play demo.gInstance.main_loop() # quit the game demo.destroy() if __name__ == "__main__": sys.exit(main())
22.512821
75
0.632118
from laylib import Environment from engine import Engine import sys def main(): demo = Environment( 800, 600, False, '2D Demo' ) demo.load_complete(Engine(), '../data') demo.gInstance.main_loop() demo.destroy() if __name__ == "__main__": sys.exit(main())
true
true
f725b0a65f050af516439f7b25d526190cc56ff4
15,585
py
Python
mpunet/callbacks/callbacks.py
sandeepsinghsengar/MPUNet2Plus
fd97800cd349ee47d2c9cce1851a332dcbcb047c
[ "MIT" ]
156
2018-12-19T19:21:30.000Z
2022-03-10T13:14:52.000Z
mpunet/callbacks/callbacks.py
sandeepsinghsengar/MPUNet2Plus
fd97800cd349ee47d2c9cce1851a332dcbcb047c
[ "MIT" ]
25
2019-07-30T07:45:26.000Z
2022-02-10T00:38:31.000Z
mpunet/callbacks/callbacks.py
sandeepsinghsengar/MPUNet2Plus
fd97800cd349ee47d2c9cce1851a332dcbcb047c
[ "MIT" ]
33
2019-01-26T16:34:50.000Z
2022-02-20T13:48:44.000Z
import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt import tensorflow as tf import psutil import numpy as np import os from tensorflow.keras.callbacks import Callback from datetime import datetime from mpunet.logging import ScreenLogger from mpunet.utils.plotting import (imshow_with_label_overlay, imshow, plot_all_training_curves) class DividerLine(Callback): """ Simply prints a line to screen after each epoch """ def __init__(self, logger=None): """ Args: logger: An instance of a MultiPlanar Logger that prints to screen and/or file """ super().__init__() self.logger = logger or ScreenLogger() def on_epoch_end(self, epoch, logs=None): self.logger("-"*45 + "\n") class LearningCurve(Callback): """ On epoch end this callback looks for all csv files matching the 'csv_regex' regex within the dir 'out_dir' and attempts to create a learning curve for each file that will be saved to 'out_dir'. Note: Failure to plot a learning curve based on a given csv file will is handled in the plot_all_training_curves function and will not cause the LearningCurve callback to raise an exception. """ def __init__(self, log_dir="logs", out_dir="logs", fname="curve.png", csv_regex="*training.csv", logger=None, **plot_kwargs): """ Args: log_dir: Relative path from the out_dir: fname: csv_regex: logger: """ super().__init__() out_dir = os.path.abspath(out_dir) if not os.path.exists(out_dir): os.makedirs(out_dir) self.csv_regex = os.path.join(os.path.abspath(log_dir), csv_regex) self.save_path = os.path.join(out_dir, fname) self.logger = logger or ScreenLogger() self.plot_kwargs = plot_kwargs def on_epoch_end(self, epoch, logs={}): plot_all_training_curves(self.csv_regex, self.save_path, logy=True, raise_error=False, logger=self.logger, **self.plot_kwargs) class MemoryConsumption(Callback): def __init__(self, max_gib=None, round_=2, logger=None): self.max_gib = max_gib self.logger = logger self.round_ = round_ def on_epoch_end(self, epoch, logs={}): process = psutil.Process(os.getpid()) mem_bytes = process.memory_info().rss mem_gib = round(mem_bytes / (1024**3), self.round_) logs['memory_usage_gib'] = mem_gib if self.max_gib and mem_gib >= self.max_gib: self.warn("Stopping training from callback 'MemoryConsumption'! " "Total memory consumption of {} GiB exceeds limitation" " (self.max_gib = {}) ".format(mem_gib, self.max_gib)) self.model.stop_training = True class DelayedCallback(object): """ Callback wrapper that delays the functionality of another callback by N number of epochs. """ def __init__(self, callback, start_from=0, logger=None): """ Args: callback: A tf.keras callback start_from: Delay the activity of 'callback' until this epoch 'start_from' logger: An instance of a MultiPlanar Logger that prints to screen and/or file """ self.logger = logger or ScreenLogger() self.callback = callback self.start_from = start_from def __getattr__(self, item): return getattr(self.callback, item) def on_epoch_end(self, epoch, logs=None): if epoch >= self.start_from-1: self.callback.on_epoch_end(epoch, logs=logs) else: self.logger("[%s] Not active at epoch %i - will be at %i" % (self.callback.__class__.__name__, epoch+1, self.start_from)) class TrainTimer(Callback): """ Appends train timing information to the log. If called prior to tf.keras.callbacks.CSVLogger this information will be written to disk. """ def __init__(self, logger=None, max_minutes=None, verbose=1): super().__init__() self.logger = logger or ScreenLogger() self.max_minutes = int(max_minutes) if max_minutes else None self.verbose = bool(verbose) # Timing attributes self.train_begin_time = None self.prev_epoch_time = None def on_train_begin(self, logs=None): self.train_begin_time = datetime.now() def on_epoch_begin(self, epoch, logs=None): self.prev_epoch_time = datetime.now() def on_epoch_end(self, epoch, logs=None): # Compute epoch execution time end_time = datetime.now() epoch_time = end_time - self.prev_epoch_time train_time = end_time - self.train_begin_time # Update attributes self.prev_epoch_time = end_time # Add to logs train_hours = round(train_time.total_seconds() / 3600, 4) epoch_minutes = round(epoch_time.total_seconds() / 60, 4) logs["epoch_minutes"] = epoch_minutes logs["train_hours"] = train_hours if self.verbose: self.logger("[TrainTimer] Epoch time: %.2f minutes " "- Total train time: %.2f hours" % (epoch_minutes, train_hours)) if self.max_minutes and train_hours*60 > self.max_minutes: self.logger("Stopping training. Training ran for {} minutes, " "max_minutes of {} was specified on the TrainTimer " "callback.".format(train_hours*60, self.max_minutes)) self.model.stop_training = True class FGBatchBalancer(Callback): """ mpunet callback. Sets the forced FG fraction in a batch at each epoch to 1-recall over the validation data at the previous epoch """ def __init__(self, train_data, val_data=None, logger=None): """ Args: train_data: A mpunet.sequence object representing the training data val_data: A mpunet.sequence object representing the validation data logger: An instance of a MultiPlanar Logger that prints to screen and/or file """ super().__init__() self.data = (("train", train_data), ("val", val_data)) self.logger = logger or ScreenLogger() self.active = True def on_epoch_end(self, epoch, logs=None): if not self.active: return None recall = logs.get("val_recall") if recall is None: self.logger("[FGBatchBalancer] No val_recall in logs. " "Disabling callback. " "Did you put this callback before the validation " "callback?") self.active = False else: # Always at least 1 image slice fraction = max(0.01, 1 - recall) for name, data in self.data: if data is not None: data.fg_batch_fraction = fraction self.logger("[FGBatchBalancer] Setting FG fraction for %s " "to: %.4f - Now %s/%s" % (name, fraction, data.n_fg_slices, data.batch_size)) class MeanReduceLogArrays(Callback): """ On epoch end, goes through the log and replaces any array entries with their mean value. """ def __init__(self): super().__init__() def on_epoch_end(self, epoch, logs={}): for key, value in logs.items(): if isinstance(value, (np.ndarray, list)): logs[key] = np.mean(value) class PrintLayerWeights(Callback): """ Print the weights of a specified layer every some epoch or batch. """ def __init__(self, layer, every=10, first=10, per_epoch=False, logger=None): """ Args: layer: A tf.keras layer every: Print the weights every 'every' batch or epoch if per_epoch=True first: Print the first 'first' elements of each weight matrix per_epoch: Print after 'every' epoch instead of batch logger: An instance of a MultiPlanar Logger that prints to screen and/or file """ super().__init__() if isinstance(layer, int): self.layer = self.model.layers[layer] else: self.layer = layer self.first = first self.every = every self.logger = logger or ScreenLogger() self.per_epoch = per_epoch if per_epoch: # Apply on every epoch instead of per batches self.on_epoch_begin = self.on_batch_begin self.on_batch_begin = lambda *args, **kwargs: None self.log() def log(self): self.logger("PrintLayerWeights Callback") self.logger("Layer: ", self.layer) self.logger("Every: ", self.every) self.logger("First: ", self.first) self.logger("Per epoch: ", self.per_epoch) def on_batch_begin(self, batch, logs=None): if batch % self.every: return weights = self.layer.get_weights() self.logger("Weights for layer '%s'" % self.layer) self.logger("Weights:\n%s" % weights[0].ravel()[:self.first]) try: self.logger("Baises:\n%s" % weights[1].ravel()[:self.first]) except IndexError: pass class SaveOutputAs2DImage(Callback): """ Save random 2D slices from the output of a given layer during training. """ def __init__(self, layer, sequence, model, out_dir, every=10, logger=None): """ Args: layer: A tf.keras layer sequence: A MultiPlanar.sequence object from which batches are sampled and pushed through the graph to output of layer model: A tf.keras model object out_dir: Path to directory (existing or non-existing) in which images will be stored every: Perform this operation every 'every' batches """ super().__init__() self.every = every self.seq = sequence self.layer = layer self.epoch = None self.model = model self.logger = logger or ScreenLogger() self.out_dir = out_dir if not os.path.exists(out_dir): os.makedirs(self.out_dir) self.log() def log(self): self.logger("Save Output as 2D Image Callback") self.logger("Layer: ", self.layer) self.logger("Every: ", self.every) def on_epoch_begin(self, epoch, logs=None): self.epoch = epoch def on_batch_end(self, batch, logs=None): if batch % self.every: return # Get output of layer self.model.predict_on_batch() sess = tf.keras.backend.get_session() X, _, _ = self.seq[0] outs = sess.run([self.layer.output], feed_dict={self.model.input: X})[0] if isinstance(outs, list): outs = outs[0] for i, (model_in, layer_out) in enumerate(zip(X, outs)): fig = plt.figure(figsize=(12, 6)) ax1 = fig.add_subplot(121) ax2 = fig.add_subplot(122) # Plot model input and layer outputs on each ax chl1, axis, slice = imshow(ax1, model_in) chl2, _, _ = imshow(ax2, layer_out, axis=axis, slice=slice) # Set labels and save figure ax1.set_title("Model input - Channel %i - Axis %i - Slice %i" % (chl1, axis,slice), size=22) ax2.set_title("Layer output - Channel %i - Axis %i - Slice %i" % (chl2, axis, slice), size=22) fig.tight_layout() fig.savefig(os.path.join(self.out_dir, "epoch_%i_batch_%i_im_%i" % (self.epoch, batch, i))) plt.close(fig) class SavePredictionImages(Callback): """ Save images after each epoch of training of the model on a batch of training and a batch of validation data sampled from sequence objects. Saves the input image with ground truth overlay as well as the predicted label masks. """ def __init__(self, train_data, val_data, outdir='images'): """ Args: train_data: A mpunet.sequence object from which training data can be sampled via the __getitem__ method. val_data: A mpunet.sequence object from which validation data can be sampled via the __getitem__ method. outdir: Path to directory (existing or non-existing) in which images will be stored. """ super().__init__() self.train_data = train_data self.val_data = val_data self.save_path = os.path.abspath(os.path.join(outdir, "pred_images_at_epoch")) if not os.path.exists(self.save_path): os.makedirs(self.save_path) def pred_and_save(self, data, subdir): # Get a random batch X, y, _ = data[np.random.randint(len(data), dtype=np.int64)] # Predict on the batch pred = self.model.predict(X) subdir = os.path.join(self.save_path, subdir) if not os.path.exists(subdir): os.mkdir(subdir) # Plot each sample in the batch for i, (im, lab, p) in enumerate(zip(X, y, pred)): fig, (ax1, ax2, ax3) = plt.subplots(ncols=3, figsize=(12, 6)) lab = lab.reshape(im.shape[:-1] + (lab.shape[-1],)) p = p.reshape(im.shape[:-1] + (p.shape[-1],)) # Imshow ground truth on ax2 # This function will determine which channel, axis and slice to # show and return so that we can use them for the other 2 axes chnl, axis, slice = imshow_with_label_overlay(ax2, im, lab, lab_alpha=1.0) # Imshow pred on ax3 imshow_with_label_overlay(ax3, im, p, lab_alpha=1.0, channel=chnl, axis=axis, slice=slice) # Imshow raw image on ax1 # Chose the same slice, channel and axis as above im = im[..., chnl] im = np.moveaxis(im, axis, 0) if slice is not None: # Only for 3D imges im = im[slice] ax1.imshow(im, cmap="gray") # Set labels ax1.set_title("Image", size=18) ax2.set_title("True labels", size=18) ax3.set_title("Prediction", size=18) fig.tight_layout() with np.testing.suppress_warnings() as sup: sup.filter(UserWarning) fig.savefig(os.path.join(subdir, str(i) + ".png")) plt.close(fig.number) def on_epoch_end(self, epoch, logs={}): self.pred_and_save(self.train_data, "train_%s" % epoch) if self.val_data is not None: self.pred_and_save(self.val_data, "val_%s" % epoch)
37.019002
86
0.569714
import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt import tensorflow as tf import psutil import numpy as np import os from tensorflow.keras.callbacks import Callback from datetime import datetime from mpunet.logging import ScreenLogger from mpunet.utils.plotting import (imshow_with_label_overlay, imshow, plot_all_training_curves) class DividerLine(Callback): def __init__(self, logger=None): super().__init__() self.logger = logger or ScreenLogger() def on_epoch_end(self, epoch, logs=None): self.logger("-"*45 + "\n") class LearningCurve(Callback): def __init__(self, log_dir="logs", out_dir="logs", fname="curve.png", csv_regex="*training.csv", logger=None, **plot_kwargs): super().__init__() out_dir = os.path.abspath(out_dir) if not os.path.exists(out_dir): os.makedirs(out_dir) self.csv_regex = os.path.join(os.path.abspath(log_dir), csv_regex) self.save_path = os.path.join(out_dir, fname) self.logger = logger or ScreenLogger() self.plot_kwargs = plot_kwargs def on_epoch_end(self, epoch, logs={}): plot_all_training_curves(self.csv_regex, self.save_path, logy=True, raise_error=False, logger=self.logger, **self.plot_kwargs) class MemoryConsumption(Callback): def __init__(self, max_gib=None, round_=2, logger=None): self.max_gib = max_gib self.logger = logger self.round_ = round_ def on_epoch_end(self, epoch, logs={}): process = psutil.Process(os.getpid()) mem_bytes = process.memory_info().rss mem_gib = round(mem_bytes / (1024**3), self.round_) logs['memory_usage_gib'] = mem_gib if self.max_gib and mem_gib >= self.max_gib: self.warn("Stopping training from callback 'MemoryConsumption'! " "Total memory consumption of {} GiB exceeds limitation" " (self.max_gib = {}) ".format(mem_gib, self.max_gib)) self.model.stop_training = True class DelayedCallback(object): def __init__(self, callback, start_from=0, logger=None): self.logger = logger or ScreenLogger() self.callback = callback self.start_from = start_from def __getattr__(self, item): return getattr(self.callback, item) def on_epoch_end(self, epoch, logs=None): if epoch >= self.start_from-1: self.callback.on_epoch_end(epoch, logs=logs) else: self.logger("[%s] Not active at epoch %i - will be at %i" % (self.callback.__class__.__name__, epoch+1, self.start_from)) class TrainTimer(Callback): def __init__(self, logger=None, max_minutes=None, verbose=1): super().__init__() self.logger = logger or ScreenLogger() self.max_minutes = int(max_minutes) if max_minutes else None self.verbose = bool(verbose) self.train_begin_time = None self.prev_epoch_time = None def on_train_begin(self, logs=None): self.train_begin_time = datetime.now() def on_epoch_begin(self, epoch, logs=None): self.prev_epoch_time = datetime.now() def on_epoch_end(self, epoch, logs=None): end_time = datetime.now() epoch_time = end_time - self.prev_epoch_time train_time = end_time - self.train_begin_time self.prev_epoch_time = end_time train_hours = round(train_time.total_seconds() / 3600, 4) epoch_minutes = round(epoch_time.total_seconds() / 60, 4) logs["epoch_minutes"] = epoch_minutes logs["train_hours"] = train_hours if self.verbose: self.logger("[TrainTimer] Epoch time: %.2f minutes " "- Total train time: %.2f hours" % (epoch_minutes, train_hours)) if self.max_minutes and train_hours*60 > self.max_minutes: self.logger("Stopping training. Training ran for {} minutes, " "max_minutes of {} was specified on the TrainTimer " "callback.".format(train_hours*60, self.max_minutes)) self.model.stop_training = True class FGBatchBalancer(Callback): def __init__(self, train_data, val_data=None, logger=None): super().__init__() self.data = (("train", train_data), ("val", val_data)) self.logger = logger or ScreenLogger() self.active = True def on_epoch_end(self, epoch, logs=None): if not self.active: return None recall = logs.get("val_recall") if recall is None: self.logger("[FGBatchBalancer] No val_recall in logs. " "Disabling callback. " "Did you put this callback before the validation " "callback?") self.active = False else: fraction = max(0.01, 1 - recall) for name, data in self.data: if data is not None: data.fg_batch_fraction = fraction self.logger("[FGBatchBalancer] Setting FG fraction for %s " "to: %.4f - Now %s/%s" % (name, fraction, data.n_fg_slices, data.batch_size)) class MeanReduceLogArrays(Callback): def __init__(self): super().__init__() def on_epoch_end(self, epoch, logs={}): for key, value in logs.items(): if isinstance(value, (np.ndarray, list)): logs[key] = np.mean(value) class PrintLayerWeights(Callback): def __init__(self, layer, every=10, first=10, per_epoch=False, logger=None): super().__init__() if isinstance(layer, int): self.layer = self.model.layers[layer] else: self.layer = layer self.first = first self.every = every self.logger = logger or ScreenLogger() self.per_epoch = per_epoch if per_epoch: self.on_epoch_begin = self.on_batch_begin self.on_batch_begin = lambda *args, **kwargs: None self.log() def log(self): self.logger("PrintLayerWeights Callback") self.logger("Layer: ", self.layer) self.logger("Every: ", self.every) self.logger("First: ", self.first) self.logger("Per epoch: ", self.per_epoch) def on_batch_begin(self, batch, logs=None): if batch % self.every: return weights = self.layer.get_weights() self.logger("Weights for layer '%s'" % self.layer) self.logger("Weights:\n%s" % weights[0].ravel()[:self.first]) try: self.logger("Baises:\n%s" % weights[1].ravel()[:self.first]) except IndexError: pass class SaveOutputAs2DImage(Callback): def __init__(self, layer, sequence, model, out_dir, every=10, logger=None): super().__init__() self.every = every self.seq = sequence self.layer = layer self.epoch = None self.model = model self.logger = logger or ScreenLogger() self.out_dir = out_dir if not os.path.exists(out_dir): os.makedirs(self.out_dir) self.log() def log(self): self.logger("Save Output as 2D Image Callback") self.logger("Layer: ", self.layer) self.logger("Every: ", self.every) def on_epoch_begin(self, epoch, logs=None): self.epoch = epoch def on_batch_end(self, batch, logs=None): if batch % self.every: return self.model.predict_on_batch() sess = tf.keras.backend.get_session() X, _, _ = self.seq[0] outs = sess.run([self.layer.output], feed_dict={self.model.input: X})[0] if isinstance(outs, list): outs = outs[0] for i, (model_in, layer_out) in enumerate(zip(X, outs)): fig = plt.figure(figsize=(12, 6)) ax1 = fig.add_subplot(121) ax2 = fig.add_subplot(122) chl1, axis, slice = imshow(ax1, model_in) chl2, _, _ = imshow(ax2, layer_out, axis=axis, slice=slice) ax1.set_title("Model input - Channel %i - Axis %i - Slice %i" % (chl1, axis,slice), size=22) ax2.set_title("Layer output - Channel %i - Axis %i - Slice %i" % (chl2, axis, slice), size=22) fig.tight_layout() fig.savefig(os.path.join(self.out_dir, "epoch_%i_batch_%i_im_%i" % (self.epoch, batch, i))) plt.close(fig) class SavePredictionImages(Callback): def __init__(self, train_data, val_data, outdir='images'): super().__init__() self.train_data = train_data self.val_data = val_data self.save_path = os.path.abspath(os.path.join(outdir, "pred_images_at_epoch")) if not os.path.exists(self.save_path): os.makedirs(self.save_path) def pred_and_save(self, data, subdir): X, y, _ = data[np.random.randint(len(data), dtype=np.int64)] pred = self.model.predict(X) subdir = os.path.join(self.save_path, subdir) if not os.path.exists(subdir): os.mkdir(subdir) for i, (im, lab, p) in enumerate(zip(X, y, pred)): fig, (ax1, ax2, ax3) = plt.subplots(ncols=3, figsize=(12, 6)) lab = lab.reshape(im.shape[:-1] + (lab.shape[-1],)) p = p.reshape(im.shape[:-1] + (p.shape[-1],)) chnl, axis, slice = imshow_with_label_overlay(ax2, im, lab, lab_alpha=1.0) imshow_with_label_overlay(ax3, im, p, lab_alpha=1.0, channel=chnl, axis=axis, slice=slice) im = im[..., chnl] im = np.moveaxis(im, axis, 0) if slice is not None: im = im[slice] ax1.imshow(im, cmap="gray") ax1.set_title("Image", size=18) ax2.set_title("True labels", size=18) ax3.set_title("Prediction", size=18) fig.tight_layout() with np.testing.suppress_warnings() as sup: sup.filter(UserWarning) fig.savefig(os.path.join(subdir, str(i) + ".png")) plt.close(fig.number) def on_epoch_end(self, epoch, logs={}): self.pred_and_save(self.train_data, "train_%s" % epoch) if self.val_data is not None: self.pred_and_save(self.val_data, "val_%s" % epoch)
true
true
f725b10ac41ecee5ca5b5e982437b8bbd0484e3c
273
py
Python
src/password_generator.py
thiamsantos/python-labs
91262d64b3772526d91db96976f2df77011a2343
[ "MIT" ]
null
null
null
src/password_generator.py
thiamsantos/python-labs
91262d64b3772526d91db96976f2df77011a2343
[ "MIT" ]
null
null
null
src/password_generator.py
thiamsantos/python-labs
91262d64b3772526d91db96976f2df77011a2343
[ "MIT" ]
null
null
null
import string import random def generate_password(): chars = string.ascii_letters + string.digits + string.punctuation return ''.join([random.choice(chars) for i in range(0, 15)]) def main(): print(generate_password()) if __name__ == '__main__': main()
19.5
69
0.692308
import string import random def generate_password(): chars = string.ascii_letters + string.digits + string.punctuation return ''.join([random.choice(chars) for i in range(0, 15)]) def main(): print(generate_password()) if __name__ == '__main__': main()
true
true
f725b1ae42f7b8692600bca55736971aa629fa7d
4,921
py
Python
lib/jnpr/healthbot/swagger/models/rule_schema_formula_min.py
Juniper/healthbot-py-client
49f0884b5d01ac8430aa7ed4c9acb4e7a2b717a6
[ "Apache-2.0" ]
10
2019-10-23T12:54:37.000Z
2022-02-07T19:24:30.000Z
lib/jnpr/healthbot/swagger/models/rule_schema_formula_min.py
Juniper/healthbot-py-client
49f0884b5d01ac8430aa7ed4c9acb4e7a2b717a6
[ "Apache-2.0" ]
5
2019-09-30T04:29:25.000Z
2022-02-16T12:21:06.000Z
lib/jnpr/healthbot/swagger/models/rule_schema_formula_min.py
Juniper/healthbot-py-client
49f0884b5d01ac8430aa7ed4c9acb4e7a2b717a6
[ "Apache-2.0" ]
4
2019-09-30T01:17:48.000Z
2020-08-25T07:27:54.000Z
# coding: utf-8 """ Paragon Insights APIs API interface for PI application # noqa: E501 OpenAPI spec version: 4.0.0 Contact: healthbot-feedback@juniper.net Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class RuleSchemaFormulaMin(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'field_name': 'str', 'time_range': 'str' } attribute_map = { 'field_name': 'field-name', 'time_range': 'time-range' } def __init__(self, field_name=None, time_range=None): # noqa: E501 """RuleSchemaFormulaMin - a model defined in Swagger""" # noqa: E501 self._field_name = None self._time_range = None self.discriminator = None self.field_name = field_name self.time_range = time_range @property def field_name(self): """Gets the field_name of this RuleSchemaFormulaMin. # noqa: E501 Field name on which min operation needs to be performed # noqa: E501 :return: The field_name of this RuleSchemaFormulaMin. # noqa: E501 :rtype: str """ return self._field_name @field_name.setter def field_name(self, field_name): """Sets the field_name of this RuleSchemaFormulaMin. Field name on which min operation needs to be performed # noqa: E501 :param field_name: The field_name of this RuleSchemaFormulaMin. # noqa: E501 :type: str """ if field_name is None: raise ValueError("Invalid value for `field_name`, must not be `None`") # noqa: E501 self._field_name = field_name @property def time_range(self): """Gets the time_range of this RuleSchemaFormulaMin. # noqa: E501 How much back in time should we look for data. Specify positive integer followed by s/m/h/d/w/y/o representing seconds/minutes/hours/days/weeks/years/offset. Eg: 2s # noqa: E501 :return: The time_range of this RuleSchemaFormulaMin. # noqa: E501 :rtype: str """ return self._time_range @time_range.setter def time_range(self, time_range): """Sets the time_range of this RuleSchemaFormulaMin. How much back in time should we look for data. Specify positive integer followed by s/m/h/d/w/y/o representing seconds/minutes/hours/days/weeks/years/offset. Eg: 2s # noqa: E501 :param time_range: The time_range of this RuleSchemaFormulaMin. # noqa: E501 :type: str """ if time_range is None: raise ValueError("Invalid value for `time_range`, must not be `None`") # noqa: E501 if time_range is not None and not re.search(r'^[1-9][0-9]*(\\.[0-9]+)?(o|s|m|h|d|w|y|offset)$', time_range): # noqa: E501 raise ValueError(r"Invalid value for `time_range`, must be a follow pattern or equal to `/^[1-9][0-9]*(\\.[0-9]+)?(o|s|m|h|d|w|y|offset)$/`") # noqa: E501 self._time_range = time_range def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(RuleSchemaFormulaMin, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, RuleSchemaFormulaMin): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
32.806667
186
0.59622
import pprint import re import six class RuleSchemaFormulaMin(object): swagger_types = { 'field_name': 'str', 'time_range': 'str' } attribute_map = { 'field_name': 'field-name', 'time_range': 'time-range' } def __init__(self, field_name=None, time_range=None): self._field_name = None self._time_range = None self.discriminator = None self.field_name = field_name self.time_range = time_range @property def field_name(self): return self._field_name @field_name.setter def field_name(self, field_name): if field_name is None: raise ValueError("Invalid value for `field_name`, must not be `None`") self._field_name = field_name @property def time_range(self): return self._time_range @time_range.setter def time_range(self, time_range): if time_range is None: raise ValueError("Invalid value for `time_range`, must not be `None`") if time_range is not None and not re.search(r'^[1-9][0-9]*(\\.[0-9]+)?(o|s|m|h|d|w|y|offset)$', time_range): raise ValueError(r"Invalid value for `time_range`, must be a follow pattern or equal to `/^[1-9][0-9]*(\\.[0-9]+)?(o|s|m|h|d|w|y|offset)$/`") self._time_range = time_range def to_dict(self): result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(RuleSchemaFormulaMin, dict): for key, value in self.items(): result[key] = value return result def to_str(self): return pprint.pformat(self.to_dict()) def __repr__(self): return self.to_str() def __eq__(self, other): if not isinstance(other, RuleSchemaFormulaMin): return False return self.__dict__ == other.__dict__ def __ne__(self, other): return not self == other
true
true
f725b253adc761c90bb78171d6e459fcd4106d11
5,638
py
Python
tests/integration/climsoft/controller/test_regkey_controller.py
opencdms/opencdms-api
f1ed6e1d883025a8658746fe457e0c975718c7be
[ "MIT" ]
3
2020-12-01T09:25:18.000Z
2022-02-14T23:57:34.000Z
tests/integration/climsoft/controller/test_regkey_controller.py
opencdms/opencdms-api
f1ed6e1d883025a8658746fe457e0c975718c7be
[ "MIT" ]
11
2021-12-05T10:09:00.000Z
2022-02-17T08:11:22.000Z
tests/integration/climsoft/controller/test_regkey_controller.py
opencdms/opencdms-api
f1ed6e1d883025a8658746fe457e0c975718c7be
[ "MIT" ]
2
2021-03-10T19:03:05.000Z
2021-12-11T08:36:04.000Z
import json import pytest from sqlalchemy.sql import text as sa_text from sqlalchemy.orm.session import sessionmaker from opencdms.models.climsoft import v4_1_1_core as climsoft_models from apps.climsoft.db.engine import db_engine from apps.climsoft.schemas import regkey_schema from datagen.climsoft import regkey as climsoft_regkey from faker import Faker from fastapi.testclient import TestClient from apps.auth.db.engine import db_engine as auth_db_engine from apps.auth.db.models import user_model from passlib.hash import django_pbkdf2_sha256 as handler fake = Faker() def setup_module(module): with auth_db_engine.connect().execution_options(autocommit=True) as connection: with connection.begin(): auth_db_engine.execute(sa_text(f''' TRUNCATE TABLE {user_model.AuthUser.__tablename__} RESTART IDENTITY CASCADE ''').execution_options(autocommit=True)) with db_engine.connect().execution_options(autocommit=True) as connection: with connection.begin(): db_engine.execute(sa_text(f""" SET FOREIGN_KEY_CHECKS = 0; TRUNCATE TABLE {climsoft_models.Regkey.__tablename__}; SET FOREIGN_KEY_CHECKS = 1; """)) Session = sessionmaker(bind=db_engine) db_session = Session() for i in range(1, 11): db_session.add(climsoft_models.Regkey( **climsoft_regkey.get_valid_reg_key_input().dict() )) db_session.commit() db_session.close() AuthSession = sessionmaker(bind=auth_db_engine) auth_session = AuthSession() user = user_model.AuthUser( username="testuser", password=handler.hash("password"), first_name=fake.first_name(), last_name=fake.last_name(), email=fake.email() ) auth_session.add(user) auth_session.commit() auth_session.close() def teardown_module(module): with auth_db_engine.connect().execution_options(autocommit=True) as connection: with connection.begin(): auth_db_engine.execute(sa_text(f''' TRUNCATE TABLE {user_model.AuthUser.__tablename__} RESTART IDENTITY CASCADE ''').execution_options(autocommit=True)) with db_engine.connect().execution_options(autocommit=True) as connection: with connection.begin(): db_engine.execute(sa_text(f""" SET FOREIGN_KEY_CHECKS = 0; TRUNCATE TABLE {climsoft_models.Regkey.__tablename__}; SET FOREIGN_KEY_CHECKS = 1; """)) @pytest.fixture def get_access_token(user_access_token: str) -> str: return user_access_token @pytest.fixture def get_reg_key(): Session = sessionmaker(bind=db_engine) session = Session() reg_key = climsoft_models.Regkey(**climsoft_regkey.get_valid_reg_key_input().dict()) session.add(reg_key) session.commit() yield reg_key session.close() def test_should_return_first_five_reg_keys(client: TestClient, get_access_token: str): response = client.get("/climsoft/v1/reg-keys", params={"limit": 5}, headers={ "Authorization": f"Bearer {get_access_token}" }) assert response.status_code == 200 response_data = response.json() assert len(response_data["result"]) == 5 def test_should_return_single_reg_key(client: TestClient, get_reg_key: climsoft_models.Regkey, get_access_token: str): response = client.get(f"/climsoft/v1/reg-keys/{get_reg_key.keyName}", headers={ "Authorization": f"Bearer {get_access_token}" }) assert response.status_code == 200 response_data = response.json() assert len(response_data["result"]) == 1 def test_should_create_a_reg_key(client: TestClient, get_access_token: str): reg_key_data = climsoft_regkey.get_valid_reg_key_input().dict(by_alias=True) response = client.post("/climsoft/v1/reg-keys", data=json.dumps(reg_key_data, default=str), headers={ "Authorization": f"Bearer {get_access_token}" }) assert response.status_code == 200 response_data = response.json() assert len(response_data["result"]) == 1 def test_should_raise_validation_error(client: TestClient, get_access_token: str): reg_key_data = {"aaa": "bbbbbbb"} response = client.post("/climsoft/v1/reg-keys", data=json.dumps(reg_key_data, default=str), headers={ "Authorization": f"Bearer {get_access_token}" }) assert response.status_code == 422 def test_should_update_reg_key(client: TestClient, get_reg_key, get_access_token: str): reg_key_data = regkey_schema.RegKey.from_orm(get_reg_key).dict(by_alias=True) key_name = reg_key_data.pop("key_name") updates = {**reg_key_data, "key_description": "updated name"} response = client.put(f"/climsoft/v1/reg-keys/{key_name}", data=json.dumps(updates, default=str), headers={ "Authorization": f"Bearer {get_access_token}" }) response_data = response.json() assert response.status_code == 200 assert response_data["result"][0]["key_description"] == updates["key_description"] def test_should_delete_reg_key(client: TestClient, get_reg_key, get_access_token: str): reg_key_data = regkey_schema.RegKey.from_orm(get_reg_key).dict(by_alias=True) key_name = reg_key_data.pop("key_name") response = client.delete(f"/climsoft/v1/reg-keys/{key_name}", headers={ "Authorization": f"Bearer {get_access_token}" }) assert response.status_code == 200 response = client.get(f"/climsoft/v1/reg-keys/{key_name}", headers={ "Authorization": f"Bearer {get_access_token}" }) assert response.status_code == 404
37.586667
118
0.707166
import json import pytest from sqlalchemy.sql import text as sa_text from sqlalchemy.orm.session import sessionmaker from opencdms.models.climsoft import v4_1_1_core as climsoft_models from apps.climsoft.db.engine import db_engine from apps.climsoft.schemas import regkey_schema from datagen.climsoft import regkey as climsoft_regkey from faker import Faker from fastapi.testclient import TestClient from apps.auth.db.engine import db_engine as auth_db_engine from apps.auth.db.models import user_model from passlib.hash import django_pbkdf2_sha256 as handler fake = Faker() def setup_module(module): with auth_db_engine.connect().execution_options(autocommit=True) as connection: with connection.begin(): auth_db_engine.execute(sa_text(f''' TRUNCATE TABLE {user_model.AuthUser.__tablename__} RESTART IDENTITY CASCADE ''').execution_options(autocommit=True)) with db_engine.connect().execution_options(autocommit=True) as connection: with connection.begin(): db_engine.execute(sa_text(f""" SET FOREIGN_KEY_CHECKS = 0; TRUNCATE TABLE {climsoft_models.Regkey.__tablename__}; SET FOREIGN_KEY_CHECKS = 1; """)) Session = sessionmaker(bind=db_engine) db_session = Session() for i in range(1, 11): db_session.add(climsoft_models.Regkey( **climsoft_regkey.get_valid_reg_key_input().dict() )) db_session.commit() db_session.close() AuthSession = sessionmaker(bind=auth_db_engine) auth_session = AuthSession() user = user_model.AuthUser( username="testuser", password=handler.hash("password"), first_name=fake.first_name(), last_name=fake.last_name(), email=fake.email() ) auth_session.add(user) auth_session.commit() auth_session.close() def teardown_module(module): with auth_db_engine.connect().execution_options(autocommit=True) as connection: with connection.begin(): auth_db_engine.execute(sa_text(f''' TRUNCATE TABLE {user_model.AuthUser.__tablename__} RESTART IDENTITY CASCADE ''').execution_options(autocommit=True)) with db_engine.connect().execution_options(autocommit=True) as connection: with connection.begin(): db_engine.execute(sa_text(f""" SET FOREIGN_KEY_CHECKS = 0; TRUNCATE TABLE {climsoft_models.Regkey.__tablename__}; SET FOREIGN_KEY_CHECKS = 1; """)) @pytest.fixture def get_access_token(user_access_token: str) -> str: return user_access_token @pytest.fixture def get_reg_key(): Session = sessionmaker(bind=db_engine) session = Session() reg_key = climsoft_models.Regkey(**climsoft_regkey.get_valid_reg_key_input().dict()) session.add(reg_key) session.commit() yield reg_key session.close() def test_should_return_first_five_reg_keys(client: TestClient, get_access_token: str): response = client.get("/climsoft/v1/reg-keys", params={"limit": 5}, headers={ "Authorization": f"Bearer {get_access_token}" }) assert response.status_code == 200 response_data = response.json() assert len(response_data["result"]) == 5 def test_should_return_single_reg_key(client: TestClient, get_reg_key: climsoft_models.Regkey, get_access_token: str): response = client.get(f"/climsoft/v1/reg-keys/{get_reg_key.keyName}", headers={ "Authorization": f"Bearer {get_access_token}" }) assert response.status_code == 200 response_data = response.json() assert len(response_data["result"]) == 1 def test_should_create_a_reg_key(client: TestClient, get_access_token: str): reg_key_data = climsoft_regkey.get_valid_reg_key_input().dict(by_alias=True) response = client.post("/climsoft/v1/reg-keys", data=json.dumps(reg_key_data, default=str), headers={ "Authorization": f"Bearer {get_access_token}" }) assert response.status_code == 200 response_data = response.json() assert len(response_data["result"]) == 1 def test_should_raise_validation_error(client: TestClient, get_access_token: str): reg_key_data = {"aaa": "bbbbbbb"} response = client.post("/climsoft/v1/reg-keys", data=json.dumps(reg_key_data, default=str), headers={ "Authorization": f"Bearer {get_access_token}" }) assert response.status_code == 422 def test_should_update_reg_key(client: TestClient, get_reg_key, get_access_token: str): reg_key_data = regkey_schema.RegKey.from_orm(get_reg_key).dict(by_alias=True) key_name = reg_key_data.pop("key_name") updates = {**reg_key_data, "key_description": "updated name"} response = client.put(f"/climsoft/v1/reg-keys/{key_name}", data=json.dumps(updates, default=str), headers={ "Authorization": f"Bearer {get_access_token}" }) response_data = response.json() assert response.status_code == 200 assert response_data["result"][0]["key_description"] == updates["key_description"] def test_should_delete_reg_key(client: TestClient, get_reg_key, get_access_token: str): reg_key_data = regkey_schema.RegKey.from_orm(get_reg_key).dict(by_alias=True) key_name = reg_key_data.pop("key_name") response = client.delete(f"/climsoft/v1/reg-keys/{key_name}", headers={ "Authorization": f"Bearer {get_access_token}" }) assert response.status_code == 200 response = client.get(f"/climsoft/v1/reg-keys/{key_name}", headers={ "Authorization": f"Bearer {get_access_token}" }) assert response.status_code == 404
true
true
f725b3453489b66fbfc7b49799e450b8abfbfc00
11,264
py
Python
deployer/src/config_creator.py
yugabyte/docsearch-scraper
8b58d364c7721cbce892843e946834a3ccc5fcd7
[ "MIT" ]
null
null
null
deployer/src/config_creator.py
yugabyte/docsearch-scraper
8b58d364c7721cbce892843e946834a3ccc5fcd7
[ "MIT" ]
null
null
null
deployer/src/config_creator.py
yugabyte/docsearch-scraper
8b58d364c7721cbce892843e946834a3ccc5fcd7
[ "MIT" ]
1
2020-04-01T22:01:17.000Z
2020-04-01T22:01:17.000Z
from collections import OrderedDict import tldextract import re from . import helpers from . import helpdesk_helper from urllib.parse import urlparse def extract_root_from_input(input_string): # We cant parse the url since user might have not enter a proper link # We assume that the string is already the proper root if input_string.endswith('/'): return input_string # extracting substring before the first isolated / (not //) domain = re.match(".+?([^/]/(?!/))", input_string) try: url_parsed = urlparse(input_string) # Removing unused parameters url_parsed._replace(params='', query='', fragment='') path_splited = url_parsed.path.split('/') # Path is redirecting to a page if ('html' in path_splited[-1]): url_parsed = url_parsed._replace(path='/'.join(path_splited[: -1])) # We are fine else: pass return url_parsed.geturl() + '/' except ValueError: return domain.group() if domain else input_string def to_docusaurus_config(config, urls=None): if urls: config["sitemap_urls"] = [ extract_root_from_input(urls[0]) + "sitemap.xml"] config["sitemap_alternate_links"] = True config["custom_settings"] = {"attributesForFaceting": ["language", "version"] } config["selectors"]["lvl0"] = OrderedDict(( ("selector", "//*[contains(@class,'navGroups')]//*[contains(@class,'navListItemActive')]/preceding::h3[1]"), ("type", "xpath"), ("global", True), ("default_value", "Documentation") )) config["selectors"]["lvl1"] = ".post h1" config["selectors"]["lvl2"] = ".post h2" config["selectors"]["lvl3"] = ".post h3" config["selectors"]["lvl4"] = ".post h4" config["selectors"]["lvl5"] = ".post h5" config["selectors"]["text"] = ".post article p, .post article li" config["selectors_exclude"] = [".hash-link"] return config def to_gitbook_config(config): config["selectors"]["lvl0"] = ".markdown-section h1" config["selectors"]["lvl1"] = ".markdown-section h2" config["selectors"]["lvl2"] = ".markdown-section h3" config["selectors"]["lvl3"] = ".markdown-section h4" config["selectors"]["lvl4"] = ".markdown-section h4" config["selectors"]["lvl5"] = ".markdown-section h5" config["selectors"]["text"] = ".markdown-section p, .markdown-section li" return config def to_pkgdown_config(config, urls=None): if urls: root = extract_root_from_input(urls[0]) config["start_urls"] = [{ "url": root + "index.html", "selectors_key": "homepage", "tags": [ "homepage" ] }, { "url": root + "reference", "selectors_key": "reference", "tags": [ "reference" ] }, { "url": root + "articles", "selectors_key": "articles", "tags": [ "articles" ] }] config["sitemap_urls"] = [ root + "sitemap.xml"] config["selectors"] = OrderedDict(( ("homepage", OrderedDict(( ("lvl0", OrderedDict(( ("selector", ".contents h1"), ("default_value", "pkgdown Home page") ))), ("lvl1", ".contents h2"), ("lvl2", OrderedDict(( ("selector", ".contents h3"), ("default_value", "Context") ))), ("lvl3", ".ref-arguments td, .ref-description"), ("text", ".contents p, .contents li, .contents .pre") ))), ("reference", OrderedDict(( ("lvl0", ".contents h1"), ("lvl1", OrderedDict(( ("selector", ".contents .name"), ("default_value", "Argument") ))), ("lvl2", OrderedDict(( ("selector", ".ref-arguments th"), ("default_value", "Description") ))), ("lvl3", ".ref-arguments td, .ref-description"), ("text", ".contents p, .contents li") ))), ("articles", OrderedDict(( ("lvl0", ".contents h1"), ("lvl1", ".contents .name"), ("lvl2", OrderedDict(( ("selector", ".contents h2, .contents h3"), ("default_value", "Context") ))), ("text", ".contents p, .contents li") ))), ("default", OrderedDict(( ("lvl1", ".contents h2"), ("lvl2", ".contents h3, .contents th"), ("lvl3", ".contents h4"), ("lvl4", ".contents h5"), ("text", ".contents p, .contents li, .usage, .template-article .contents .pre") ))) )) config["selectors_exclude"] = [".dont-index"] config["stop_urls"] = ["/reference/$", "/reference/index.html", "/articles/$", "/articles/index.html"] config["custom_settings"] = { "separatorsToIndex": "_", "attributesToRetrieve": ["hierarchy", "content", "anchor", "url", "url_without_anchor"] } config["min_indexed_level"] = 2 return config def to_vuepress_config(config): config["selectors"]["lvl0"] = OrderedDict(( ("selector", "p.sidebar-heading.open"), ("global", True), ("default_value", "Documentation") )) config["custom_settings"] = {"attributesForFaceting": ["lang"] } config["selectors"]["lvl1"] = ".content h1" config["selectors"]["lvl2"] = ".content h2" config["selectors"]["lvl3"] = ".content h3" config["selectors"]["lvl4"] = ".content h4" config["selectors"]["lvl5"] = ".content h5" config["selectors"]["text"] = ".content p, .content li" config["selectors"]["lang"] = OrderedDict(( ("selector", "/html/@lang"), ("type", "xpath"), ("global", True), ("default_value", "en-US") )) config["scrap_start_urls"] = False config["strip_chars"] = " .,;:#" return config def to_larecipe_config(config, urls=None): if urls: config["sitemap_urls"] = [ extract_root_from_input(urls[0]) + "sitemap.xml"] config["selectors"]["lvl0"] = OrderedDict(( ("selector", "//div[contains(@class, 'sidebar')]//li/a[text()=//div[contains(@class, 'article')]//h1[1]/text()]"), ("global", True), ("type", "xpath"), ("default_value", "Documentation") )) config["selectors"]["lvl1"] = "div.article h1" config["selectors"]["lvl2"] = "div.article h2" config["selectors"]["lvl3"] = "div.article h3" config["selectors"]["lvl4"] = "div.article h4" config["selectors"]["lvl5"] = "div.article h5" config["selectors"]["text"] = "div.article p, div.article li" return config def to_publii_config(config, urls=None): if urls: config["sitemap_urls"] = [ extract_root_from_input(urls[0]) + "sitemap.xml"] config["selectors"]["lvl0"] = OrderedDict(( ("selector", ".active-parent > span"), ("global", True), ("default_value", "Documentation") )) config["selectors"]["lvl1"] = ".content h1" config["selectors"]["lvl2"] = ".content h2" config["selectors"]["lvl3"] = ".content h3" config["selectors"]["lvl4"] = ".content h4" config["selectors"]["lvl5"] = ".content h5" config["selectors"]["text"] = ".content p, .content li" config["only_content_level"] = True return config def to_jsdoc_config(config, urls=None): config["stop_urls"] = ["\\.js\\.html", "/index\\.html$"] config["selectors"]["lvl0"] = OrderedDict(( ("selector", "#main .page-title"), ("global", True), ("default_value", "Documentation") )) config["selectors"]["lvl1"] = "#main h3" config["selectors"]["lvl2"] = "#main h4" config["selectors"]["lvl3"] = "#main h5" config["selectors"]["lvl4"] = "#main h6, #main td.name" del config["selectors"]["lvl5"] config["selectors"]["text"] = "#main p, #main li" config["selectors_exclude"] = [".signature", ".type-signature", ".details"] return config def create_config(u=None): config = OrderedDict(( ("index_name", ""), ("start_urls", []), ("stop_urls", []), ("selectors", OrderedDict(( ("lvl0", "FIXME h1"), ("lvl1", "FIXME h2"), ("lvl2", "FIXME h3"), ("lvl3", "FIXME h4"), ("lvl4", "FIXME h5"), ("lvl5", "FIXME h6"), ("text", "FIXME p, FIXME li") ))) )) if u is None: u = helpers.get_user_value("start url: ") urls = [u] if helpdesk_helper.is_helpdesk_url(u): cuid = helpdesk_helper.get_conversation_ID_from_url(u) conversation = helpdesk_helper.get_conversation(cuid) url_from_conversation = helpdesk_helper.get_start_url_from_conversation( conversation) urls = [url_from_conversation] u = url_from_conversation if helpdesk_helper.is_docusaurus_conversation(conversation): config = to_docusaurus_config(config, urls) elif helpdesk_helper.is_gitbook_conversation(conversation): config = to_gitbook_config(config) elif helpdesk_helper.is_pkgdown_conversation(conversation): config = to_pkgdown_config(config, urls) elif helpdesk_helper.is_vuepress_conversation(conversation): config = to_vuepress_config(config) elif helpdesk_helper.is_larecipe_conversation(conversation): config = to_larecipe_config(config, urls) elif helpdesk_helper.is_publii_conversation(conversation): config = to_publii_config(config, urls) elif helpdesk_helper.is_jsdoc_conversation(conversation): config = to_jsdoc_config(config, urls) config["conversation_id"] = [cuid] if '.html' in u: urls.append(u.rsplit('/', 1)[0]) # Use subdomain for github website https://<subdomain>.github.io/ config['index_name'] = tldextract.extract( u).subdomain if tldextract.extract( u).domain == 'github' else tldextract.extract(u).domain if len(config['start_urls']) == 0: config['start_urls'] = urls user_index_name = helpers.get_user_value( 'index_name is \033[1;33m{}\033[0m [enter to confirm]: '.format(config[ "index_name"])) if user_index_name != "": config['index_name'] = user_index_name print('index_name is now \033[1;33m{}\033[0m'.format(config[ "index_name"])) return config
34.552147
110
0.532404
from collections import OrderedDict import tldextract import re from . import helpers from . import helpdesk_helper from urllib.parse import urlparse def extract_root_from_input(input_string): if input_string.endswith('/'): return input_string domain = re.match(".+?([^/]/(?!/))", input_string) try: url_parsed = urlparse(input_string) url_parsed._replace(params='', query='', fragment='') path_splited = url_parsed.path.split('/') if ('html' in path_splited[-1]): url_parsed = url_parsed._replace(path='/'.join(path_splited[: -1])) else: pass return url_parsed.geturl() + '/' except ValueError: return domain.group() if domain else input_string def to_docusaurus_config(config, urls=None): if urls: config["sitemap_urls"] = [ extract_root_from_input(urls[0]) + "sitemap.xml"] config["sitemap_alternate_links"] = True config["custom_settings"] = {"attributesForFaceting": ["language", "version"] } config["selectors"]["lvl0"] = OrderedDict(( ("selector", "//*[contains(@class,'navGroups')]//*[contains(@class,'navListItemActive')]/preceding::h3[1]"), ("type", "xpath"), ("global", True), ("default_value", "Documentation") )) config["selectors"]["lvl1"] = ".post h1" config["selectors"]["lvl2"] = ".post h2" config["selectors"]["lvl3"] = ".post h3" config["selectors"]["lvl4"] = ".post h4" config["selectors"]["lvl5"] = ".post h5" config["selectors"]["text"] = ".post article p, .post article li" config["selectors_exclude"] = [".hash-link"] return config def to_gitbook_config(config): config["selectors"]["lvl0"] = ".markdown-section h1" config["selectors"]["lvl1"] = ".markdown-section h2" config["selectors"]["lvl2"] = ".markdown-section h3" config["selectors"]["lvl3"] = ".markdown-section h4" config["selectors"]["lvl4"] = ".markdown-section h4" config["selectors"]["lvl5"] = ".markdown-section h5" config["selectors"]["text"] = ".markdown-section p, .markdown-section li" return config def to_pkgdown_config(config, urls=None): if urls: root = extract_root_from_input(urls[0]) config["start_urls"] = [{ "url": root + "index.html", "selectors_key": "homepage", "tags": [ "homepage" ] }, { "url": root + "reference", "selectors_key": "reference", "tags": [ "reference" ] }, { "url": root + "articles", "selectors_key": "articles", "tags": [ "articles" ] }] config["sitemap_urls"] = [ root + "sitemap.xml"] config["selectors"] = OrderedDict(( ("homepage", OrderedDict(( ("lvl0", OrderedDict(( ("selector", ".contents h1"), ("default_value", "pkgdown Home page") ))), ("lvl1", ".contents h2"), ("lvl2", OrderedDict(( ("selector", ".contents h3"), ("default_value", "Context") ))), ("lvl3", ".ref-arguments td, .ref-description"), ("text", ".contents p, .contents li, .contents .pre") ))), ("reference", OrderedDict(( ("lvl0", ".contents h1"), ("lvl1", OrderedDict(( ("selector", ".contents .name"), ("default_value", "Argument") ))), ("lvl2", OrderedDict(( ("selector", ".ref-arguments th"), ("default_value", "Description") ))), ("lvl3", ".ref-arguments td, .ref-description"), ("text", ".contents p, .contents li") ))), ("articles", OrderedDict(( ("lvl0", ".contents h1"), ("lvl1", ".contents .name"), ("lvl2", OrderedDict(( ("selector", ".contents h2, .contents h3"), ("default_value", "Context") ))), ("text", ".contents p, .contents li") ))), ("default", OrderedDict(( ("lvl1", ".contents h2"), ("lvl2", ".contents h3, .contents th"), ("lvl3", ".contents h4"), ("lvl4", ".contents h5"), ("text", ".contents p, .contents li, .usage, .template-article .contents .pre") ))) )) config["selectors_exclude"] = [".dont-index"] config["stop_urls"] = ["/reference/$", "/reference/index.html", "/articles/$", "/articles/index.html"] config["custom_settings"] = { "separatorsToIndex": "_", "attributesToRetrieve": ["hierarchy", "content", "anchor", "url", "url_without_anchor"] } config["min_indexed_level"] = 2 return config def to_vuepress_config(config): config["selectors"]["lvl0"] = OrderedDict(( ("selector", "p.sidebar-heading.open"), ("global", True), ("default_value", "Documentation") )) config["custom_settings"] = {"attributesForFaceting": ["lang"] } config["selectors"]["lvl1"] = ".content h1" config["selectors"]["lvl2"] = ".content h2" config["selectors"]["lvl3"] = ".content h3" config["selectors"]["lvl4"] = ".content h4" config["selectors"]["lvl5"] = ".content h5" config["selectors"]["text"] = ".content p, .content li" config["selectors"]["lang"] = OrderedDict(( ("selector", "/html/@lang"), ("type", "xpath"), ("global", True), ("default_value", "en-US") )) config["scrap_start_urls"] = False config["strip_chars"] = " .,;:#" return config def to_larecipe_config(config, urls=None): if urls: config["sitemap_urls"] = [ extract_root_from_input(urls[0]) + "sitemap.xml"] config["selectors"]["lvl0"] = OrderedDict(( ("selector", "//div[contains(@class, 'sidebar')]//li/a[text()=//div[contains(@class, 'article')]//h1[1]/text()]"), ("global", True), ("type", "xpath"), ("default_value", "Documentation") )) config["selectors"]["lvl1"] = "div.article h1" config["selectors"]["lvl2"] = "div.article h2" config["selectors"]["lvl3"] = "div.article h3" config["selectors"]["lvl4"] = "div.article h4" config["selectors"]["lvl5"] = "div.article h5" config["selectors"]["text"] = "div.article p, div.article li" return config def to_publii_config(config, urls=None): if urls: config["sitemap_urls"] = [ extract_root_from_input(urls[0]) + "sitemap.xml"] config["selectors"]["lvl0"] = OrderedDict(( ("selector", ".active-parent > span"), ("global", True), ("default_value", "Documentation") )) config["selectors"]["lvl1"] = ".content h1" config["selectors"]["lvl2"] = ".content h2" config["selectors"]["lvl3"] = ".content h3" config["selectors"]["lvl4"] = ".content h4" config["selectors"]["lvl5"] = ".content h5" config["selectors"]["text"] = ".content p, .content li" config["only_content_level"] = True return config def to_jsdoc_config(config, urls=None): config["stop_urls"] = ["\\.js\\.html", "/index\\.html$"] config["selectors"]["lvl0"] = OrderedDict(( ("selector", "#main .page-title"), ("global", True), ("default_value", "Documentation") )) config["selectors"]["lvl1"] = "#main h3" config["selectors"]["lvl2"] = "#main h4" config["selectors"]["lvl3"] = "#main h5" config["selectors"]["lvl4"] = "#main h6, #main td.name" del config["selectors"]["lvl5"] config["selectors"]["text"] = "#main p, #main li" config["selectors_exclude"] = [".signature", ".type-signature", ".details"] return config def create_config(u=None): config = OrderedDict(( ("index_name", ""), ("start_urls", []), ("stop_urls", []), ("selectors", OrderedDict(( ("lvl0", "FIXME h1"), ("lvl1", "FIXME h2"), ("lvl2", "FIXME h3"), ("lvl3", "FIXME h4"), ("lvl4", "FIXME h5"), ("lvl5", "FIXME h6"), ("text", "FIXME p, FIXME li") ))) )) if u is None: u = helpers.get_user_value("start url: ") urls = [u] if helpdesk_helper.is_helpdesk_url(u): cuid = helpdesk_helper.get_conversation_ID_from_url(u) conversation = helpdesk_helper.get_conversation(cuid) url_from_conversation = helpdesk_helper.get_start_url_from_conversation( conversation) urls = [url_from_conversation] u = url_from_conversation if helpdesk_helper.is_docusaurus_conversation(conversation): config = to_docusaurus_config(config, urls) elif helpdesk_helper.is_gitbook_conversation(conversation): config = to_gitbook_config(config) elif helpdesk_helper.is_pkgdown_conversation(conversation): config = to_pkgdown_config(config, urls) elif helpdesk_helper.is_vuepress_conversation(conversation): config = to_vuepress_config(config) elif helpdesk_helper.is_larecipe_conversation(conversation): config = to_larecipe_config(config, urls) elif helpdesk_helper.is_publii_conversation(conversation): config = to_publii_config(config, urls) elif helpdesk_helper.is_jsdoc_conversation(conversation): config = to_jsdoc_config(config, urls) config["conversation_id"] = [cuid] if '.html' in u: urls.append(u.rsplit('/', 1)[0]) config['index_name'] = tldextract.extract( u).subdomain if tldextract.extract( u).domain == 'github' else tldextract.extract(u).domain if len(config['start_urls']) == 0: config['start_urls'] = urls user_index_name = helpers.get_user_value( 'index_name is \033[1;33m{}\033[0m [enter to confirm]: '.format(config[ "index_name"])) if user_index_name != "": config['index_name'] = user_index_name print('index_name is now \033[1;33m{}\033[0m'.format(config[ "index_name"])) return config
true
true
f725b3e77a5288c1d9314ff987b54ca1c859daff
46,076
py
Python
tests/plugins/test_reactor_config.py
MartinBasti/atomic-reactor
4431225c5a474c7f88c63ec1f25216d4b84a0f1d
[ "BSD-3-Clause" ]
null
null
null
tests/plugins/test_reactor_config.py
MartinBasti/atomic-reactor
4431225c5a474c7f88c63ec1f25216d4b84a0f1d
[ "BSD-3-Clause" ]
null
null
null
tests/plugins/test_reactor_config.py
MartinBasti/atomic-reactor
4431225c5a474c7f88c63ec1f25216d4b84a0f1d
[ "BSD-3-Clause" ]
null
null
null
""" Copyright (c) 2017 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. """ from __future__ import unicode_literals from jsonschema import ValidationError import io import logging import os import pkg_resources import pytest from textwrap import dedent import re import yaml import smtplib from copy import deepcopy import atomic_reactor import koji from atomic_reactor.core import DockerTasker from atomic_reactor.inner import DockerBuildWorkflow from atomic_reactor.util import read_yaml import atomic_reactor.koji_util import atomic_reactor.pulp_util import atomic_reactor.odcs_util import osbs.conf import osbs.api from osbs.utils import RegistryURI from atomic_reactor.plugins.pre_reactor_config import (ReactorConfig, ReactorConfigPlugin, get_config, WORKSPACE_CONF_KEY, get_koji_session, get_koji_path_info, get_pulp_session, get_odcs_session, get_smtp_session, get_openshift_session, get_clusters_client_config_path, get_docker_registry, get_platform_to_goarch_mapping, get_goarch_to_platform_mapping, get_default_image_build_method, get_flatpak_base_image, CONTAINER_DEFAULT_BUILD_METHOD, get_build_image_override, NO_FALLBACK) from tests.constants import TEST_IMAGE, REACTOR_CONFIG_MAP from tests.docker_mock import mock_docker from tests.fixtures import reactor_config_map # noqa from flexmock import flexmock class TestReactorConfigPlugin(object): def prepare(self): mock_docker() tasker = DockerTasker() workflow = DockerBuildWorkflow({'provider': 'git', 'uri': 'asd'}, TEST_IMAGE) return tasker, workflow @pytest.mark.parametrize(('fallback'), [ False, True ]) @pytest.mark.parametrize(('config', 'valid'), [ ("""\ version: 1 registries: - url: https://container-registry.example.com/v2 auth: cfg_path: /var/run/secrets/atomic-reactor/v2-registry-dockercfg """, True), ("""\ version: 1 registries: - url: https://old-container-registry.example.com/v1 auth: cfg_path: /var/run/secrets/atomic-reactor/v1-registry-dockercfg - url: https://container-registry.example.com/v2 auth: cfg_path: /var/run/secrets/atomic-reactor/v2-registry-dockercfg """, True), ("""\ version: 1 registries: - url: https://old-container-registry.example.com/v1 auth: cfg_path: /var/run/secrets/atomic-reactor/v1-registry-dockercfg """, False), ]) def test_get_docker_registry(self, config, fallback, valid): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} config_json = read_yaml(config, 'schemas/config.json') docker_reg = { 'version': 'v2', 'insecure': False, 'secret': '/var/run/secrets/atomic-reactor/v2-registry-dockercfg', 'url': 'https://container-registry.example.com/v2', } if fallback: if valid: docker_fallback = docker_reg expected = docker_reg else: docker_fallback = NO_FALLBACK else: docker_fallback = {} expected = { 'url': 'https://container-registry.example.com', 'insecure': False, 'secret': '/var/run/secrets/atomic-reactor/v2-registry-dockercfg' } workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\ ReactorConfig(config_json) if valid: docker_registry = get_docker_registry(workflow, docker_fallback) assert docker_registry == expected else: if fallback: with pytest.raises(KeyError): get_docker_registry(workflow, docker_fallback) else: with pytest.raises(RuntimeError): get_docker_registry(workflow, docker_fallback) def test_no_config(self): tasker, workflow = self.prepare() conf = get_config(workflow) assert isinstance(conf, ReactorConfig) same_conf = get_config(workflow) assert conf is same_conf @pytest.mark.parametrize('basename', ['reactor-config.yaml', None]) def test_filename(self, tmpdir, basename): filename = os.path.join(str(tmpdir), basename or 'config.yaml') with open(filename, 'w'): pass tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path=str(tmpdir), basename=filename) assert plugin.run() is None def test_filename_not_found(self): tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path='/not-found') with pytest.raises(Exception): plugin.run() def test_no_schema_resource(self, tmpdir, caplog): class FakeProvider(object): def get_resource_stream(self, pkg, rsc): raise IOError # pkg_resources.resource_stream() cannot be mocked directly # Instead mock the module-level function it calls. (flexmock(pkg_resources) .should_receive('get_provider') .and_return(FakeProvider())) filename = os.path.join(str(tmpdir), 'config.yaml') with open(filename, 'w'): pass tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path=str(tmpdir)) with caplog.atLevel(logging.ERROR), pytest.raises(Exception): plugin.run() captured_errs = [x.message for x in caplog.records()] assert "unable to extract JSON schema, cannot validate" in captured_errs @pytest.mark.parametrize('schema', [ # Invalid JSON '{', # Invalid schema '{"properties": {"any": null}}', ]) def test_invalid_schema_resource(self, tmpdir, caplog, schema): class FakeProvider(object): def get_resource_stream(self, pkg, rsc): return io.BufferedReader(io.BytesIO(schema)) # pkg_resources.resource_stream() cannot be mocked directly # Instead mock the module-level function it calls. (flexmock(pkg_resources) .should_receive('get_provider') .and_return(FakeProvider())) filename = os.path.join(str(tmpdir), 'config.yaml') with open(filename, 'w'): pass tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path=str(tmpdir)) with caplog.atLevel(logging.ERROR), pytest.raises(Exception): plugin.run() captured_errs = [x.message for x in caplog.records()] assert any("cannot validate" in x for x in captured_errs) @pytest.mark.parametrize(('config', 'errors'), [ # noqa:F811 ("""\ clusters: foo: - name: bar max_concurrent_builds: 1 """, [ "validation error (at top level): " "%r is a required property" % u'version', ]), ("""\ version: 1 clusters: foo: bar: 1 plat/form: - name: foo max_concurrent_builds: 1 """, [ "validation error (clusters.foo): None is not of type %r" % u'array', "validation error (clusters.bar): 1 is not of type %r" % u'array', re.compile(r"validation error \(clusters\): .*'plat/form'"), ]), ("""\ version: 1 clusters: foo: - name: 1 max_concurrent_builds: 1 - name: blah max_concurrent_builds: one - name: "2" # quoting prevents error max_concurrent_builds: 2 - name: negative max_concurrent_builds: -1 """, [ "validation error (clusters.foo[0].name): " "1 is not of type %r" % u'string', "validation error (clusters.foo[1].max_concurrent_builds): " "'one' is not of type %r" % u'integer', re.compile(r"validation error \(clusters\.foo\[3\]\.max_concurrent_builds\): -1(\.0)?" r" is less than the minimum of 0"), ]), ("""\ version: 1 clusters: foo: - name: blah max_concurrent_builds: 1 enabled: never """, [ "validation error (clusters.foo[0].enabled): " "'never' is not of type %r" % u'boolean', ]), ("""\ version: 1 clusters: foo: # missing name - nam: bar max_concurrent_builds: 1 # missing max_concurrent_builds - name: baz max_concurrrent_builds: 2 - name: bar max_concurrent_builds: 4 extra: false """, [ "validation error (clusters.foo[0]): " "%r is a required property" % u'name', "validation error (clusters.foo[1]): " "%r is a required property" % u'max_concurrent_builds', "validation error (clusters.foo[2]): " "Additional properties are not allowed ('extra' was unexpected)", ]) ]) def test_bad_cluster_config(self, tmpdir, caplog, reactor_config_map, config, errors): if reactor_config_map: os.environ['REACTOR_CONFIG'] = dedent(config) else: filename = os.path.join(str(tmpdir), 'config.yaml') with open(filename, 'w') as fp: fp.write(dedent(config)) tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path=str(tmpdir)) with caplog.atLevel(logging.ERROR), pytest.raises(ValidationError): plugin.run() os.environ.pop('REACTOR_CONFIG', None) captured_errs = [x.message for x in caplog.records()] for error in errors: try: # Match regexp assert any(filter(error.match, captured_errs)) except AttributeError: # String comparison assert error in captured_errs def test_bad_version(self, tmpdir): filename = os.path.join(str(tmpdir), 'config.yaml') with open(filename, 'w') as fp: fp.write("version: 2") tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path=str(tmpdir)) with pytest.raises(ValueError): plugin.run() @pytest.mark.parametrize(('config', 'clusters'), [ # noqa:F811 # Empty config ("", []), # Built-in default config (yaml.dump(ReactorConfig.DEFAULT_CONFIG), []), # Unknown key ("""\ version: 1 special: foo """, []), ("""\ version: 1 clusters: ignored: - name: foo max_concurrent_builds: 2 platform: - name: one max_concurrent_builds: 4 - name: two max_concurrent_builds: 8 enabled: true - name: three max_concurrent_builds: 16 enabled: false """, [ ('one', 4), ('two', 8), ]), ]) def test_good_cluster_config(self, tmpdir, reactor_config_map, config, clusters): if reactor_config_map and config: os.environ['REACTOR_CONFIG'] = dedent(config) else: filename = os.path.join(str(tmpdir), 'config.yaml') with open(filename, 'w') as fp: fp.write(dedent(config)) tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path=str(tmpdir)) assert plugin.run() is None os.environ.pop('REACTOR_CONFIG', None) conf = get_config(workflow) enabled = conf.get_enabled_clusters_for_platform('platform') assert set([(x.name, x.max_concurrent_builds) for x in enabled]) == set(clusters) @pytest.mark.parametrize(('extra_config', 'fallback', 'error'), [ # noqa:F811 ('clusters_client_config_dir: /the/path', None, None), ('clusters_client_config_dir: /the/path', '/unused/path', None), (None, '/the/path', None), (None, NO_FALLBACK, KeyError), ]) def test_cluster_client_config_path(self, tmpdir, reactor_config_map, extra_config, fallback, error): config = 'version: 1' if extra_config: config += '\n' + extra_config if reactor_config_map and config: os.environ['REACTOR_CONFIG'] = config else: filename = os.path.join(str(tmpdir), 'config.yaml') with open(filename, 'w') as fp: fp.write(config) tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path=str(tmpdir)) assert plugin.run() is None os.environ.pop('REACTOR_CONFIG', None) if error: with pytest.raises(error): get_clusters_client_config_path(workflow, fallback) else: path = get_clusters_client_config_path(workflow, fallback) assert path == '/the/path/osbs.conf' @pytest.mark.parametrize('default', ( 'release', 'beta', 'unsigned', )) def test_odcs_config(self, tmpdir, default): filename = str(tmpdir.join('config.yaml')) with open(filename, 'w') as fp: fp.write(dedent("""\ version: 1 odcs: signing_intents: - name: release keys: [R123, R234] - name: beta keys: [R123, B456, B457] - name: unsigned keys: [] default_signing_intent: {default} api_url: http://odcs.example.com auth: ssl_certs_dir: /var/run/secrets/atomic-reactor/odcssecret """.format(default=default))) tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path=str(tmpdir)) assert plugin.run() is None odcs_config = get_config(workflow).get_odcs_config() assert odcs_config.default_signing_intent == default unsigned_intent = {'name': 'unsigned', 'keys': [], 'restrictiveness': 0} beta_intent = {'name': 'beta', 'keys': ['R123', 'B456', 'B457'], 'restrictiveness': 1} release_intent = {'name': 'release', 'keys': ['R123', 'R234'], 'restrictiveness': 2} assert odcs_config.signing_intents == [ unsigned_intent, beta_intent, release_intent ] assert odcs_config.get_signing_intent_by_name('release') == release_intent assert odcs_config.get_signing_intent_by_name('beta') == beta_intent assert odcs_config.get_signing_intent_by_name('unsigned') == unsigned_intent with pytest.raises(ValueError): odcs_config.get_signing_intent_by_name('missing') assert odcs_config.get_signing_intent_by_keys(['R123', 'R234'])['name'] == 'release' assert odcs_config.get_signing_intent_by_keys('R123 R234')['name'] == 'release' assert odcs_config.get_signing_intent_by_keys(['R123'])['name'] == 'release' assert odcs_config.get_signing_intent_by_keys('R123')['name'] == 'release' assert odcs_config.get_signing_intent_by_keys(['R123', 'B456'])['name'] == 'beta' assert odcs_config.get_signing_intent_by_keys(['B456', 'R123'])['name'] == 'beta' assert odcs_config.get_signing_intent_by_keys('B456 R123')['name'] == 'beta' assert odcs_config.get_signing_intent_by_keys('R123 B456 ')['name'] == 'beta' assert odcs_config.get_signing_intent_by_keys(['B456'])['name'] == 'beta' assert odcs_config.get_signing_intent_by_keys('B456')['name'] == 'beta' assert odcs_config.get_signing_intent_by_keys([])['name'] == 'unsigned' assert odcs_config.get_signing_intent_by_keys('')['name'] == 'unsigned' with pytest.raises(ValueError): assert odcs_config.get_signing_intent_by_keys(['missing']) with pytest.raises(ValueError): assert odcs_config.get_signing_intent_by_keys(['R123', 'R234', 'B457']) def test_odcs_config_invalid_default_signing_intent(self, tmpdir): filename = str(tmpdir.join('config.yaml')) with open(filename, 'w') as fp: fp.write(dedent("""\ version: 1 odcs: signing_intents: - name: release keys: [R123] - name: beta keys: [R123, B456] - name: unsigned keys: [] default_signing_intent: spam api_url: http://odcs.example.com auth: ssl_certs_dir: /var/run/secrets/atomic-reactor/odcssecret """)) tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path=str(tmpdir)) assert plugin.run() is None with pytest.raises(ValueError) as exc_info: get_config(workflow).get_odcs_config() message = str(exc_info.value) assert message == dedent("""\ unknown signing intent name "spam", valid names: unsigned, beta, release """.rstrip()) @pytest.mark.parametrize('fallback', (True, False, None)) @pytest.mark.parametrize('method', [ 'koji', 'pulp', 'odcs', 'smtp', 'arrangement_version', 'artifacts_allowed_domains', 'image_labels', 'image_label_info_url_format', 'image_equal_labels', 'openshift', 'group_manifests', 'platform_descriptors', 'prefer_schema1_digest', 'content_versions', 'registries', 'yum_proxy', 'source_registry', 'sources_command', 'required_secrets', 'worker_token_secrets', 'clusters', ]) def test_get_methods(self, fallback, method): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} if fallback is False: workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] = \ ReactorConfig(yaml.safe_load(REACTOR_CONFIG_MAP)) else: if fallback: fall_source = ReactorConfig(yaml.safe_load(REACTOR_CONFIG_MAP)) else: fall_source = ReactorConfig(yaml.safe_load("version: 1")) method_name = 'get_' + method real_method = getattr(atomic_reactor.plugins.pre_reactor_config, method_name) if fallback is True: output = real_method(workflow, fall_source.conf[method]) else: if fallback is False: output = real_method(workflow) else: with pytest.raises(KeyError): real_method(workflow) return expected = yaml.safe_load(REACTOR_CONFIG_MAP)[method] if method == 'registries': registries_cm = {} for registry in expected: reguri = RegistryURI(registry.get('url')) regdict = {} regdict['version'] = reguri.version if registry.get('auth'): regdict['secret'] = registry['auth']['cfg_path'] regdict['insecure'] = registry.get('insecure', False) regdict['expected_media_types'] = registry.get('expected_media_types', []) registries_cm[reguri.docker_uri] = regdict if fallback: output = real_method(workflow, registries_cm) assert output == registries_cm return if method == 'source_registry': expect = { 'uri': RegistryURI(expected['url']), 'insecure': expected.get('insecure', False) } if fallback: output = real_method(workflow, expect) assert output['insecure'] == expect['insecure'] assert output['uri'].uri == expect['uri'].uri return assert output == expected @pytest.mark.parametrize('fallback', (True, False)) @pytest.mark.parametrize(('config', 'expect'), [ ("""\ version: 1 platform_descriptors: - platform: x86_64 architecture: amd64 """, {'x86_64': 'amd64', 'ppc64le': 'ppc64le'}), ]) def test_get_platform_to_goarch_mapping(self, fallback, config, expect): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} config_json = read_yaml(config, 'schemas/config.json') workspace = workflow.plugin_workspace[ReactorConfigPlugin.key] workspace[WORKSPACE_CONF_KEY] = ReactorConfig(config_json) kwargs = {} if fallback: kwargs['descriptors_fallback'] = {'x86_64': 'amd64'} platform_to_goarch = get_platform_to_goarch_mapping(workflow, **kwargs) goarch_to_platform = get_goarch_to_platform_mapping(workflow, **kwargs) for plat, goarch in expect.items(): assert platform_to_goarch[plat] == goarch assert goarch_to_platform[goarch] == plat @pytest.mark.parametrize(('config', 'expect'), [ ("""\ version: 1 default_image_build_method: imagebuilder """, "imagebuilder"), ("""\ version: 1 """, CONTAINER_DEFAULT_BUILD_METHOD), ]) def test_get_default_image_build_method(self, config, expect): config_json = read_yaml(config, 'schemas/config.json') _, workflow = self.prepare() workspace = workflow.plugin_workspace.setdefault(ReactorConfigPlugin.key, {}) workspace[WORKSPACE_CONF_KEY] = ReactorConfig(config_json) method = get_default_image_build_method(workflow) assert method == expect @pytest.mark.parametrize('fallback', (True, False)) @pytest.mark.parametrize(('config', 'expect'), [ ("""\ version: 1 build_image_override: ppc64le: registry.example.com/buildroot-ppc64le:latest arm: registry.example.com/buildroot-arm:latest """, {'ppc64le': 'registry.example.com/buildroot-ppc64le:latest', 'arm': 'registry.example.com/buildroot-arm:latest'}), ]) def test_get_build_image_override(self, fallback, config, expect): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} config_json = read_yaml(config, 'schemas/config.json') workspace = workflow.plugin_workspace[ReactorConfigPlugin.key] workspace[WORKSPACE_CONF_KEY] = ReactorConfig(config_json) kwargs = {} if fallback: kwargs['fallback'] = expect build_image_override = get_build_image_override(workflow, **kwargs) assert build_image_override == expect @pytest.mark.parametrize(('config', 'fallback', 'expect'), [ ("""\ version: 1 flatpak: base_image: fedora:latest """, "x", "fedora:latest"), ("""\ version: 1 flatpak: {} """, "x", "x"), ("""\ version: 1 """, "x", "x"), ("""\ version: 1 """, None, None), ("""\ version: 1 flatpak: {} """, None, None), ]) def test_get_flatpak_base_image(self, config, fallback, expect): config_json = read_yaml(config, 'schemas/config.json') _, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = { WORKSPACE_CONF_KEY: ReactorConfig(config_json) } kwargs = {} if fallback: kwargs['fallback'] = fallback if expect: base_image = get_flatpak_base_image(workflow, **kwargs) assert base_image == expect else: with pytest.raises(KeyError): get_flatpak_base_image(workflow, **kwargs) @pytest.mark.parametrize('fallback', (True, False)) @pytest.mark.parametrize(('config', 'raise_error'), [ ("""\ version: 1 koji: hub_url: https://koji.example.com/hub root_url: https://koji.example.com/root auth: proxyuser: proxyuser krb_principal: krb_principal krb_keytab_path: /tmp/krb_keytab """, False), ("""\ version: 1 koji: hub_url: https://koji.example.com/hub root_url: https://koji.example.com/root auth: proxyuser: proxyuser ssl_certs_dir: /var/certs """, False), ("""\ version: 1 koji: hub_url: https://koji.example.com/hub root_url: https://koji.example.com/root auth: proxyuser: proxyuser """, False), ("""\ version: 1 koji: hub_url: https://koji.example.com/hub root_url: https://koji.example.com/root auth: """, True), ("""\ version: 1 koji: hub_url: https://koji.example.com/hub root_url: https://koji.example.com/root auth: proxyuser: proxyuser krb_principal: krb_principal krb_keytab_path: /tmp/krb_keytab ssl_certs_dir: /var/certs """, True), ("""\ version: 1 koji: hub_url: https://koji.example.com/hub root_url: https://koji.example.com/root auth: proxyuser: proxyuser krb_keytab_path: /tmp/krb_keytab """, True), ("""\ version: 1 koji: hub_url: https://koji.example.com/hub root_url: https://koji.example.com/root auth: proxyuser: proxyuser krb_principal: krb_principal """, True), ("""\ version: 1 koji: hub_url: https://koji.example.com/hub root_url: https://koji.example.com/root auth: proxyuser: proxyuser krb_principal: krb_principal ssl_certs_dir: /var/certs """, True), ("""\ version: 1 koji: hub_url: https://koji.example.com/hub root_url: https://koji.example.com/root auth: proxyuser: proxyuser krb_keytab_path: /tmp/krb_keytab ssl_certs_dir: /var/certs """, True), ]) def test_get_koji_session(self, fallback, config, raise_error): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} if raise_error: with pytest.raises(Exception): read_yaml(config, 'schemas/config.json') return config_json = read_yaml(config, 'schemas/config.json') auth_info = { "proxyuser": config_json['koji']['auth'].get('proxyuser'), "ssl_certs_dir": config_json['koji']['auth'].get('ssl_certs_dir'), "krb_principal": config_json['koji']['auth'].get('krb_principal'), "krb_keytab": config_json['koji']['auth'].get('krb_keytab_path') } fallback_map = {} if fallback: fallback_map = {'auth': deepcopy(auth_info), 'hub_url': config_json['koji']['hub_url']} fallback_map['auth']['krb_keytab_path'] = fallback_map['auth'].pop('krb_keytab') else: workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] = \ ReactorConfig(config_json) (flexmock(atomic_reactor.koji_util) .should_receive('create_koji_session') .with_args(config_json['koji']['hub_url'], auth_info) .once() .and_return(True)) get_koji_session(workflow, fallback_map) @pytest.mark.parametrize('fallback', (True, False)) @pytest.mark.parametrize('root_url', ( 'https://koji.example.com/root', 'https://koji.example.com/root/', None )) def test_get_koji_path_info(self, fallback, root_url): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} config = { 'version': 1, 'koji': { 'hub_url': 'https://koji.example.com/hub', 'auth': { 'ssl_certs_dir': '/var/certs' } } } expected_root_url = 'https://koji.example.com/root' if root_url: config['koji']['root_url'] = root_url config_yaml = yaml.safe_dump(config) expect_error = not root_url if expect_error: with pytest.raises(Exception): read_yaml(config_yaml, 'schemas/config.json') return parsed_config = read_yaml(config_yaml, 'schemas/config.json') fallback_map = {} if fallback: fallback_map = deepcopy(config['koji']) else: workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] = \ ReactorConfig(parsed_config) (flexmock(koji.PathInfo) .should_receive('__init__') .with_args(topdir=expected_root_url) .once()) get_koji_path_info(workflow, fallback_map) @pytest.mark.parametrize('fallback', (True, False)) @pytest.mark.parametrize(('config', 'raise_error'), [ ("""\ version: 1 pulp: name: my-pulp auth: password: testpasswd username: testuser """, False), ("""\ version: 1 pulp: name: my-pulp auth: ssl_certs_dir: /var/certs """, False), ("""\ version: 1 pulp: name: my-pulp auth: ssl_certs_dir: /var/certs password: testpasswd username: testuser """, True), ("""\ version: 1 pulp: name: my-pulp auth: ssl_certs_dir: /var/certs password: testpasswd """, True), ("""\ version: 1 pulp: name: my-pulp auth: ssl_certs_dir: /var/certs username: testuser """, True), ("""\ version: 1 pulp: name: my-pulp auth: username: testuser """, True), ("""\ version: 1 pulp: name: my-pulp auth: password: testpasswd """, True), ]) def test_get_pulp_session(self, fallback, config, raise_error): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} if raise_error: with pytest.raises(Exception): read_yaml(config, 'schemas/config.json') return config_json = read_yaml(config, 'schemas/config.json') auth_info = { "pulp_secret_path": config_json['pulp']['auth'].get('ssl_certs_dir'), "username": config_json['pulp']['auth'].get('username'), "password": config_json['pulp']['auth'].get('password'), "dockpulp_loglevel": None } fallback_map = {} if fallback: fallback_map = {'auth': deepcopy(auth_info), 'name': config_json['pulp']['name']} fallback_map['auth']['ssl_certs_dir'] = fallback_map['auth'].pop('pulp_secret_path') else: workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\ ReactorConfig(config_json) (flexmock(atomic_reactor.pulp_util.PulpHandler) .should_receive('__init__') .with_args(workflow, config_json['pulp']['name'], 'logger', **auth_info) .once() .and_return(None)) get_pulp_session(workflow, 'logger', fallback_map) @pytest.mark.parametrize('fallback', (True, False)) @pytest.mark.parametrize(('config', 'raise_error'), [ ("""\ version: 1 odcs: api_url: https://odcs.example.com/api/1 auth: ssl_certs_dir: /var/run/secrets/atomic-reactor/odcssecret signing_intents: - name: release keys: [R123] default_signing_intent: default """, False), ("""\ version: 1 odcs: api_url: https://odcs.example.com/api/1 auth: ssl_certs_dir: nonexistent signing_intents: - name: release keys: [R123] default_signing_intent: default """, False), ("""\ version: 1 odcs: api_url: https://odcs.example.com/api/1 auth: openidc_dir: /var/run/open_idc signing_intents: - name: release keys: [R123] default_signing_intent: default """, False), ("""\ version: 1 odcs: api_url: https://odcs.example.com/api/1 auth: openidc_dir: /var/run/open_idc ssl_certs_dir: /var/run/secrets/atomic-reactor/odcssecret signing_intents: - name: release keys: [R123] default_signing_intent: default """, True), ("""\ version: 1 odcs: api_url: https://odcs.example.com/api/1 auth: openidc_dir: /var/run/open_idc signing_intents: - name: release keys: [R123] """, True), ("""\ version: 1 odcs: api_url: https://odcs.example.com/api/1 auth: openidc_dir: /var/run/open_idc default_signing_intent: default """, True), ("""\ version: 1 odcs: auth: openidc_dir: /var/run/open_idc signing_intents: - name: release keys: [R123] default_signing_intent: default """, True), ]) def test_get_odcs_session(self, tmpdir, fallback, config, raise_error): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} if raise_error: with pytest.raises(Exception): read_yaml(config, 'schemas/config.json') return config_json = read_yaml(config, 'schemas/config.json') auth_info = {'insecure': config_json['odcs'].get('insecure', False)} if 'openidc_dir' in config_json['odcs']['auth']: config_json['odcs']['auth']['openidc_dir'] = str(tmpdir) filename = str(tmpdir.join('token')) with open(filename, 'w') as fp: fp.write("my_token") auth_info['token'] = "my_token" ssl_dir_raise = False if 'ssl_certs_dir' in config_json['odcs']['auth']: if config_json['odcs']['auth']['ssl_certs_dir'] != "nonexistent": config_json['odcs']['auth']['ssl_certs_dir'] = str(tmpdir) filename = str(tmpdir.join('cert')) with open(filename, 'w') as fp: fp.write("my_cert") auth_info['cert'] = filename else: ssl_dir_raise = True fallback_map = {} if fallback: fallback_map = {'auth': deepcopy(auth_info), 'api_url': config_json['odcs']['api_url']} fallback_map['auth']['ssl_certs_dir'] = config_json['odcs']['auth'].get('ssl_certs_dir') fallback_map['auth']['openidc_dir'] = config_json['odcs']['auth'].get('openidc_dir') else: workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\ ReactorConfig(config_json) if not ssl_dir_raise: (flexmock(atomic_reactor.odcs_util.ODCSClient) .should_receive('__init__') .with_args(config_json['odcs']['api_url'], **auth_info) .once() .and_return(None)) get_odcs_session(workflow, fallback_map) else: with pytest.raises(KeyError): get_odcs_session(workflow, fallback_map) @pytest.mark.parametrize('fallback', (True, False)) @pytest.mark.parametrize(('config', 'raise_error'), [ ("""\ version: 1 smtp: host: smtp.example.com from_address: osbs@example.com """, False), ("""\ version: 1 smtp: from_address: osbs@example.com """, True), ("""\ version: 1 smtp: host: smtp.example.com """, True), ("""\ version: 1 smtp: """, True), ]) def test_get_smtp_session(self, fallback, config, raise_error): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} if raise_error: with pytest.raises(Exception): read_yaml(config, 'schemas/config.json') return config_json = read_yaml(config, 'schemas/config.json') fallback_map = {} if fallback: fallback_map['host'] = config_json['smtp']['host'] else: workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\ ReactorConfig(config_json) (flexmock(smtplib.SMTP) .should_receive('__init__') .with_args(config_json['smtp']['host']) .once() .and_return(None)) get_smtp_session(workflow, fallback_map) @pytest.mark.parametrize('fallback', (True, False)) @pytest.mark.parametrize('build_json_dir', [ None, "/tmp/build_json_dir", ]) @pytest.mark.parametrize(('config', 'raise_error'), [ ("""\ version: 1 openshift: url: https://openshift.example.com auth: ssl_certs_dir: /var/run/secrets/atomic-reactor/odcssecret """, False), ("""\ version: 1 openshift: url: https://openshift.example.com """, False), ("""\ version: 1 openshift: url: https://openshift.example.com auth: krb_principal: principal krb_keytab_path: /var/keytab """, False), ("""\ version: 1 openshift: url: https://openshift.example.com auth: krb_principal: principal krb_keytab_path: /var/keytab krb_cache_path: /var/krb/cache """, False), ("""\ version: 1 openshift: url: https://openshift.example.com auth: enable: True """, False), ("""\ version: 1 openshift: url: https://openshift.example.com auth: krb_keytab_path: /var/keytab """, True), ("""\ version: 1 openshift: url: https://openshift.example.com auth: krb_principal: principal """, True), ("""\ version: 1 openshift: auth: ssl_certs_dir: /var/run/secrets/atomic-reactor/odcssecret """, True), ("""\ version: 1 openshift: auth: krb_principal: principal krb_keytab_path: /var/keytab """, True), ("""\ version: 1 openshift: url: https://openshift.example.com auth: """, True), ("""\ version: 1 openshift: auth: ssl_certs_dir: /var/run/secrets/atomic-reactor/odcssecret """, True), ]) def test_get_openshift_session(self, fallback, build_json_dir, config, raise_error): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} if build_json_dir: config += " build_json_dir: " + build_json_dir if raise_error: with pytest.raises(Exception): read_yaml(config, 'schemas/config.json') return config_json = read_yaml(config, 'schemas/config.json') auth_info = { 'openshift_url': config_json['openshift']['url'], 'verify_ssl': not config_json['openshift'].get('insecure', False), 'use_auth': False, 'conf_file': None, 'namespace': 'namespace', 'build_json_dir': build_json_dir } if config_json['openshift'].get('auth'): if config_json['openshift']['auth'].get('krb_keytab_path'): auth_info['kerberos_keytab'] =\ config_json['openshift']['auth'].get('krb_keytab_path') if config_json['openshift']['auth'].get('krb_principal'): auth_info['kerberos_principal'] =\ config_json['openshift']['auth'].get('krb_principal') if config_json['openshift']['auth'].get('krb_cache_path'): auth_info['kerberos_ccache'] =\ config_json['openshift']['auth'].get('krb_cache_path') if config_json['openshift']['auth'].get('ssl_certs_dir'): auth_info['client_cert'] =\ os.path.join(config_json['openshift']['auth'].get('ssl_certs_dir'), 'cert') auth_info['client_key'] =\ os.path.join(config_json['openshift']['auth'].get('ssl_certs_dir'), 'key') auth_info['use_auth'] = config_json['openshift']['auth'].get('enable', False) fallback_map = {} if fallback: fallback_map = {'url': config_json['openshift']['url'], 'insecure': config_json['openshift'].get('insecure', False), 'build_json_dir': build_json_dir} if config_json['openshift'].get('auth'): fallback_map['auth'] = {} fallback_map['auth']['krb_keytab_path'] =\ config_json['openshift']['auth'].get('krb_keytab_path') fallback_map['auth']['krb_principal'] =\ config_json['openshift']['auth'].get('krb_principal') fallback_map['auth']['enable'] =\ config_json['openshift']['auth'].get('enable', False) fallback_map['auth']['krb_cache_path'] =\ config_json['openshift']['auth'].get('krb_cache_path') fallback_map['auth']['ssl_certs_dir'] =\ config_json['openshift']['auth'].get('ssl_certs_dir') else: workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\ ReactorConfig(config_json) (flexmock(osbs.conf.Configuration) .should_call('__init__') .with_args(**auth_info) .once()) (flexmock(osbs.api.OSBS) .should_call('__init__') .once()) flexmock(os, environ={'BUILD': '{"metadata": {"namespace": "namespace"}}'}) get_openshift_session(workflow, fallback_map)
35.092155
100
0.532924
from __future__ import unicode_literals from jsonschema import ValidationError import io import logging import os import pkg_resources import pytest from textwrap import dedent import re import yaml import smtplib from copy import deepcopy import atomic_reactor import koji from atomic_reactor.core import DockerTasker from atomic_reactor.inner import DockerBuildWorkflow from atomic_reactor.util import read_yaml import atomic_reactor.koji_util import atomic_reactor.pulp_util import atomic_reactor.odcs_util import osbs.conf import osbs.api from osbs.utils import RegistryURI from atomic_reactor.plugins.pre_reactor_config import (ReactorConfig, ReactorConfigPlugin, get_config, WORKSPACE_CONF_KEY, get_koji_session, get_koji_path_info, get_pulp_session, get_odcs_session, get_smtp_session, get_openshift_session, get_clusters_client_config_path, get_docker_registry, get_platform_to_goarch_mapping, get_goarch_to_platform_mapping, get_default_image_build_method, get_flatpak_base_image, CONTAINER_DEFAULT_BUILD_METHOD, get_build_image_override, NO_FALLBACK) from tests.constants import TEST_IMAGE, REACTOR_CONFIG_MAP from tests.docker_mock import mock_docker from tests.fixtures import reactor_config_map from flexmock import flexmock class TestReactorConfigPlugin(object): def prepare(self): mock_docker() tasker = DockerTasker() workflow = DockerBuildWorkflow({'provider': 'git', 'uri': 'asd'}, TEST_IMAGE) return tasker, workflow @pytest.mark.parametrize(('fallback'), [ False, True ]) @pytest.mark.parametrize(('config', 'valid'), [ ("""\ version: 1 registries: - url: https://container-registry.example.com/v2 auth: cfg_path: /var/run/secrets/atomic-reactor/v2-registry-dockercfg """, True), ("""\ version: 1 registries: - url: https://old-container-registry.example.com/v1 auth: cfg_path: /var/run/secrets/atomic-reactor/v1-registry-dockercfg - url: https://container-registry.example.com/v2 auth: cfg_path: /var/run/secrets/atomic-reactor/v2-registry-dockercfg """, True), ("""\ version: 1 registries: - url: https://old-container-registry.example.com/v1 auth: cfg_path: /var/run/secrets/atomic-reactor/v1-registry-dockercfg """, False), ]) def test_get_docker_registry(self, config, fallback, valid): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} config_json = read_yaml(config, 'schemas/config.json') docker_reg = { 'version': 'v2', 'insecure': False, 'secret': '/var/run/secrets/atomic-reactor/v2-registry-dockercfg', 'url': 'https://container-registry.example.com/v2', } if fallback: if valid: docker_fallback = docker_reg expected = docker_reg else: docker_fallback = NO_FALLBACK else: docker_fallback = {} expected = { 'url': 'https://container-registry.example.com', 'insecure': False, 'secret': '/var/run/secrets/atomic-reactor/v2-registry-dockercfg' } workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\ ReactorConfig(config_json) if valid: docker_registry = get_docker_registry(workflow, docker_fallback) assert docker_registry == expected else: if fallback: with pytest.raises(KeyError): get_docker_registry(workflow, docker_fallback) else: with pytest.raises(RuntimeError): get_docker_registry(workflow, docker_fallback) def test_no_config(self): tasker, workflow = self.prepare() conf = get_config(workflow) assert isinstance(conf, ReactorConfig) same_conf = get_config(workflow) assert conf is same_conf @pytest.mark.parametrize('basename', ['reactor-config.yaml', None]) def test_filename(self, tmpdir, basename): filename = os.path.join(str(tmpdir), basename or 'config.yaml') with open(filename, 'w'): pass tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path=str(tmpdir), basename=filename) assert plugin.run() is None def test_filename_not_found(self): tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path='/not-found') with pytest.raises(Exception): plugin.run() def test_no_schema_resource(self, tmpdir, caplog): class FakeProvider(object): def get_resource_stream(self, pkg, rsc): raise IOError (flexmock(pkg_resources) .should_receive('get_provider') .and_return(FakeProvider())) filename = os.path.join(str(tmpdir), 'config.yaml') with open(filename, 'w'): pass tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path=str(tmpdir)) with caplog.atLevel(logging.ERROR), pytest.raises(Exception): plugin.run() captured_errs = [x.message for x in caplog.records()] assert "unable to extract JSON schema, cannot validate" in captured_errs @pytest.mark.parametrize('schema', [ '{', '{"properties": {"any": null}}', ]) def test_invalid_schema_resource(self, tmpdir, caplog, schema): class FakeProvider(object): def get_resource_stream(self, pkg, rsc): return io.BufferedReader(io.BytesIO(schema)) (flexmock(pkg_resources) .should_receive('get_provider') .and_return(FakeProvider())) filename = os.path.join(str(tmpdir), 'config.yaml') with open(filename, 'w'): pass tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path=str(tmpdir)) with caplog.atLevel(logging.ERROR), pytest.raises(Exception): plugin.run() captured_errs = [x.message for x in caplog.records()] assert any("cannot validate" in x for x in captured_errs) @pytest.mark.parametrize(('config', 'errors'), [ ("""\ clusters: foo: - name: bar max_concurrent_builds: 1 """, [ "validation error (at top level): " "%r is a required property" % u'version', ]), ("""\ version: 1 clusters: foo: bar: 1 plat/form: - name: foo max_concurrent_builds: 1 """, [ "validation error (clusters.foo): None is not of type %r" % u'array', "validation error (clusters.bar): 1 is not of type %r" % u'array', re.compile(r"validation error \(clusters\): .*'plat/form'"), ]), ("""\ version: 1 clusters: foo: - name: 1 max_concurrent_builds: 1 - name: blah max_concurrent_builds: one - name: "2" # quoting prevents error max_concurrent_builds: 2 - name: negative max_concurrent_builds: -1 """, [ "validation error (clusters.foo[0].name): " "1 is not of type %r" % u'string', "validation error (clusters.foo[1].max_concurrent_builds): " "'one' is not of type %r" % u'integer', re.compile(r"validation error \(clusters\.foo\[3\]\.max_concurrent_builds\): -1(\.0)?" r" is less than the minimum of 0"), ]), ("""\ version: 1 clusters: foo: - name: blah max_concurrent_builds: 1 enabled: never """, [ "validation error (clusters.foo[0].enabled): " "'never' is not of type %r" % u'boolean', ]), ("""\ version: 1 clusters: foo: # missing name - nam: bar max_concurrent_builds: 1 # missing max_concurrent_builds - name: baz max_concurrrent_builds: 2 - name: bar max_concurrent_builds: 4 extra: false """, [ "validation error (clusters.foo[0]): " "%r is a required property" % u'name', "validation error (clusters.foo[1]): " "%r is a required property" % u'max_concurrent_builds', "validation error (clusters.foo[2]): " "Additional properties are not allowed ('extra' was unexpected)", ]) ]) def test_bad_cluster_config(self, tmpdir, caplog, reactor_config_map, config, errors): if reactor_config_map: os.environ['REACTOR_CONFIG'] = dedent(config) else: filename = os.path.join(str(tmpdir), 'config.yaml') with open(filename, 'w') as fp: fp.write(dedent(config)) tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path=str(tmpdir)) with caplog.atLevel(logging.ERROR), pytest.raises(ValidationError): plugin.run() os.environ.pop('REACTOR_CONFIG', None) captured_errs = [x.message for x in caplog.records()] for error in errors: try: assert any(filter(error.match, captured_errs)) except AttributeError: assert error in captured_errs def test_bad_version(self, tmpdir): filename = os.path.join(str(tmpdir), 'config.yaml') with open(filename, 'w') as fp: fp.write("version: 2") tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path=str(tmpdir)) with pytest.raises(ValueError): plugin.run() @pytest.mark.parametrize(('config', 'clusters'), [ ("", []), (yaml.dump(ReactorConfig.DEFAULT_CONFIG), []), ("""\ version: 1 special: foo """, []), ("""\ version: 1 clusters: ignored: - name: foo max_concurrent_builds: 2 platform: - name: one max_concurrent_builds: 4 - name: two max_concurrent_builds: 8 enabled: true - name: three max_concurrent_builds: 16 enabled: false """, [ ('one', 4), ('two', 8), ]), ]) def test_good_cluster_config(self, tmpdir, reactor_config_map, config, clusters): if reactor_config_map and config: os.environ['REACTOR_CONFIG'] = dedent(config) else: filename = os.path.join(str(tmpdir), 'config.yaml') with open(filename, 'w') as fp: fp.write(dedent(config)) tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path=str(tmpdir)) assert plugin.run() is None os.environ.pop('REACTOR_CONFIG', None) conf = get_config(workflow) enabled = conf.get_enabled_clusters_for_platform('platform') assert set([(x.name, x.max_concurrent_builds) for x in enabled]) == set(clusters) @pytest.mark.parametrize(('extra_config', 'fallback', 'error'), [ ('clusters_client_config_dir: /the/path', None, None), ('clusters_client_config_dir: /the/path', '/unused/path', None), (None, '/the/path', None), (None, NO_FALLBACK, KeyError), ]) def test_cluster_client_config_path(self, tmpdir, reactor_config_map, extra_config, fallback, error): config = 'version: 1' if extra_config: config += '\n' + extra_config if reactor_config_map and config: os.environ['REACTOR_CONFIG'] = config else: filename = os.path.join(str(tmpdir), 'config.yaml') with open(filename, 'w') as fp: fp.write(config) tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path=str(tmpdir)) assert plugin.run() is None os.environ.pop('REACTOR_CONFIG', None) if error: with pytest.raises(error): get_clusters_client_config_path(workflow, fallback) else: path = get_clusters_client_config_path(workflow, fallback) assert path == '/the/path/osbs.conf' @pytest.mark.parametrize('default', ( 'release', 'beta', 'unsigned', )) def test_odcs_config(self, tmpdir, default): filename = str(tmpdir.join('config.yaml')) with open(filename, 'w') as fp: fp.write(dedent("""\ version: 1 odcs: signing_intents: - name: release keys: [R123, R234] - name: beta keys: [R123, B456, B457] - name: unsigned keys: [] default_signing_intent: {default} api_url: http://odcs.example.com auth: ssl_certs_dir: /var/run/secrets/atomic-reactor/odcssecret """.format(default=default))) tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path=str(tmpdir)) assert plugin.run() is None odcs_config = get_config(workflow).get_odcs_config() assert odcs_config.default_signing_intent == default unsigned_intent = {'name': 'unsigned', 'keys': [], 'restrictiveness': 0} beta_intent = {'name': 'beta', 'keys': ['R123', 'B456', 'B457'], 'restrictiveness': 1} release_intent = {'name': 'release', 'keys': ['R123', 'R234'], 'restrictiveness': 2} assert odcs_config.signing_intents == [ unsigned_intent, beta_intent, release_intent ] assert odcs_config.get_signing_intent_by_name('release') == release_intent assert odcs_config.get_signing_intent_by_name('beta') == beta_intent assert odcs_config.get_signing_intent_by_name('unsigned') == unsigned_intent with pytest.raises(ValueError): odcs_config.get_signing_intent_by_name('missing') assert odcs_config.get_signing_intent_by_keys(['R123', 'R234'])['name'] == 'release' assert odcs_config.get_signing_intent_by_keys('R123 R234')['name'] == 'release' assert odcs_config.get_signing_intent_by_keys(['R123'])['name'] == 'release' assert odcs_config.get_signing_intent_by_keys('R123')['name'] == 'release' assert odcs_config.get_signing_intent_by_keys(['R123', 'B456'])['name'] == 'beta' assert odcs_config.get_signing_intent_by_keys(['B456', 'R123'])['name'] == 'beta' assert odcs_config.get_signing_intent_by_keys('B456 R123')['name'] == 'beta' assert odcs_config.get_signing_intent_by_keys('R123 B456 ')['name'] == 'beta' assert odcs_config.get_signing_intent_by_keys(['B456'])['name'] == 'beta' assert odcs_config.get_signing_intent_by_keys('B456')['name'] == 'beta' assert odcs_config.get_signing_intent_by_keys([])['name'] == 'unsigned' assert odcs_config.get_signing_intent_by_keys('')['name'] == 'unsigned' with pytest.raises(ValueError): assert odcs_config.get_signing_intent_by_keys(['missing']) with pytest.raises(ValueError): assert odcs_config.get_signing_intent_by_keys(['R123', 'R234', 'B457']) def test_odcs_config_invalid_default_signing_intent(self, tmpdir): filename = str(tmpdir.join('config.yaml')) with open(filename, 'w') as fp: fp.write(dedent("""\ version: 1 odcs: signing_intents: - name: release keys: [R123] - name: beta keys: [R123, B456] - name: unsigned keys: [] default_signing_intent: spam api_url: http://odcs.example.com auth: ssl_certs_dir: /var/run/secrets/atomic-reactor/odcssecret """)) tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path=str(tmpdir)) assert plugin.run() is None with pytest.raises(ValueError) as exc_info: get_config(workflow).get_odcs_config() message = str(exc_info.value) assert message == dedent("""\ unknown signing intent name "spam", valid names: unsigned, beta, release """.rstrip()) @pytest.mark.parametrize('fallback', (True, False, None)) @pytest.mark.parametrize('method', [ 'koji', 'pulp', 'odcs', 'smtp', 'arrangement_version', 'artifacts_allowed_domains', 'image_labels', 'image_label_info_url_format', 'image_equal_labels', 'openshift', 'group_manifests', 'platform_descriptors', 'prefer_schema1_digest', 'content_versions', 'registries', 'yum_proxy', 'source_registry', 'sources_command', 'required_secrets', 'worker_token_secrets', 'clusters', ]) def test_get_methods(self, fallback, method): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} if fallback is False: workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] = \ ReactorConfig(yaml.safe_load(REACTOR_CONFIG_MAP)) else: if fallback: fall_source = ReactorConfig(yaml.safe_load(REACTOR_CONFIG_MAP)) else: fall_source = ReactorConfig(yaml.safe_load("version: 1")) method_name = 'get_' + method real_method = getattr(atomic_reactor.plugins.pre_reactor_config, method_name) if fallback is True: output = real_method(workflow, fall_source.conf[method]) else: if fallback is False: output = real_method(workflow) else: with pytest.raises(KeyError): real_method(workflow) return expected = yaml.safe_load(REACTOR_CONFIG_MAP)[method] if method == 'registries': registries_cm = {} for registry in expected: reguri = RegistryURI(registry.get('url')) regdict = {} regdict['version'] = reguri.version if registry.get('auth'): regdict['secret'] = registry['auth']['cfg_path'] regdict['insecure'] = registry.get('insecure', False) regdict['expected_media_types'] = registry.get('expected_media_types', []) registries_cm[reguri.docker_uri] = regdict if fallback: output = real_method(workflow, registries_cm) assert output == registries_cm return if method == 'source_registry': expect = { 'uri': RegistryURI(expected['url']), 'insecure': expected.get('insecure', False) } if fallback: output = real_method(workflow, expect) assert output['insecure'] == expect['insecure'] assert output['uri'].uri == expect['uri'].uri return assert output == expected @pytest.mark.parametrize('fallback', (True, False)) @pytest.mark.parametrize(('config', 'expect'), [ ("""\ version: 1 platform_descriptors: - platform: x86_64 architecture: amd64 """, {'x86_64': 'amd64', 'ppc64le': 'ppc64le'}), ]) def test_get_platform_to_goarch_mapping(self, fallback, config, expect): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} config_json = read_yaml(config, 'schemas/config.json') workspace = workflow.plugin_workspace[ReactorConfigPlugin.key] workspace[WORKSPACE_CONF_KEY] = ReactorConfig(config_json) kwargs = {} if fallback: kwargs['descriptors_fallback'] = {'x86_64': 'amd64'} platform_to_goarch = get_platform_to_goarch_mapping(workflow, **kwargs) goarch_to_platform = get_goarch_to_platform_mapping(workflow, **kwargs) for plat, goarch in expect.items(): assert platform_to_goarch[plat] == goarch assert goarch_to_platform[goarch] == plat @pytest.mark.parametrize(('config', 'expect'), [ ("""\ version: 1 default_image_build_method: imagebuilder """, "imagebuilder"), ("""\ version: 1 """, CONTAINER_DEFAULT_BUILD_METHOD), ]) def test_get_default_image_build_method(self, config, expect): config_json = read_yaml(config, 'schemas/config.json') _, workflow = self.prepare() workspace = workflow.plugin_workspace.setdefault(ReactorConfigPlugin.key, {}) workspace[WORKSPACE_CONF_KEY] = ReactorConfig(config_json) method = get_default_image_build_method(workflow) assert method == expect @pytest.mark.parametrize('fallback', (True, False)) @pytest.mark.parametrize(('config', 'expect'), [ ("""\ version: 1 build_image_override: ppc64le: registry.example.com/buildroot-ppc64le:latest arm: registry.example.com/buildroot-arm:latest """, {'ppc64le': 'registry.example.com/buildroot-ppc64le:latest', 'arm': 'registry.example.com/buildroot-arm:latest'}), ]) def test_get_build_image_override(self, fallback, config, expect): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} config_json = read_yaml(config, 'schemas/config.json') workspace = workflow.plugin_workspace[ReactorConfigPlugin.key] workspace[WORKSPACE_CONF_KEY] = ReactorConfig(config_json) kwargs = {} if fallback: kwargs['fallback'] = expect build_image_override = get_build_image_override(workflow, **kwargs) assert build_image_override == expect @pytest.mark.parametrize(('config', 'fallback', 'expect'), [ ("""\ version: 1 flatpak: base_image: fedora:latest """, "x", "fedora:latest"), ("""\ version: 1 flatpak: {} """, "x", "x"), ("""\ version: 1 """, "x", "x"), ("""\ version: 1 """, None, None), ("""\ version: 1 flatpak: {} """, None, None), ]) def test_get_flatpak_base_image(self, config, fallback, expect): config_json = read_yaml(config, 'schemas/config.json') _, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = { WORKSPACE_CONF_KEY: ReactorConfig(config_json) } kwargs = {} if fallback: kwargs['fallback'] = fallback if expect: base_image = get_flatpak_base_image(workflow, **kwargs) assert base_image == expect else: with pytest.raises(KeyError): get_flatpak_base_image(workflow, **kwargs) @pytest.mark.parametrize('fallback', (True, False)) @pytest.mark.parametrize(('config', 'raise_error'), [ ("""\ version: 1 koji: hub_url: https://koji.example.com/hub root_url: https://koji.example.com/root auth: proxyuser: proxyuser krb_principal: krb_principal krb_keytab_path: /tmp/krb_keytab """, False), ("""\ version: 1 koji: hub_url: https://koji.example.com/hub root_url: https://koji.example.com/root auth: proxyuser: proxyuser ssl_certs_dir: /var/certs """, False), ("""\ version: 1 koji: hub_url: https://koji.example.com/hub root_url: https://koji.example.com/root auth: proxyuser: proxyuser """, False), ("""\ version: 1 koji: hub_url: https://koji.example.com/hub root_url: https://koji.example.com/root auth: """, True), ("""\ version: 1 koji: hub_url: https://koji.example.com/hub root_url: https://koji.example.com/root auth: proxyuser: proxyuser krb_principal: krb_principal krb_keytab_path: /tmp/krb_keytab ssl_certs_dir: /var/certs """, True), ("""\ version: 1 koji: hub_url: https://koji.example.com/hub root_url: https://koji.example.com/root auth: proxyuser: proxyuser krb_keytab_path: /tmp/krb_keytab """, True), ("""\ version: 1 koji: hub_url: https://koji.example.com/hub root_url: https://koji.example.com/root auth: proxyuser: proxyuser krb_principal: krb_principal """, True), ("""\ version: 1 koji: hub_url: https://koji.example.com/hub root_url: https://koji.example.com/root auth: proxyuser: proxyuser krb_principal: krb_principal ssl_certs_dir: /var/certs """, True), ("""\ version: 1 koji: hub_url: https://koji.example.com/hub root_url: https://koji.example.com/root auth: proxyuser: proxyuser krb_keytab_path: /tmp/krb_keytab ssl_certs_dir: /var/certs """, True), ]) def test_get_koji_session(self, fallback, config, raise_error): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} if raise_error: with pytest.raises(Exception): read_yaml(config, 'schemas/config.json') return config_json = read_yaml(config, 'schemas/config.json') auth_info = { "proxyuser": config_json['koji']['auth'].get('proxyuser'), "ssl_certs_dir": config_json['koji']['auth'].get('ssl_certs_dir'), "krb_principal": config_json['koji']['auth'].get('krb_principal'), "krb_keytab": config_json['koji']['auth'].get('krb_keytab_path') } fallback_map = {} if fallback: fallback_map = {'auth': deepcopy(auth_info), 'hub_url': config_json['koji']['hub_url']} fallback_map['auth']['krb_keytab_path'] = fallback_map['auth'].pop('krb_keytab') else: workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] = \ ReactorConfig(config_json) (flexmock(atomic_reactor.koji_util) .should_receive('create_koji_session') .with_args(config_json['koji']['hub_url'], auth_info) .once() .and_return(True)) get_koji_session(workflow, fallback_map) @pytest.mark.parametrize('fallback', (True, False)) @pytest.mark.parametrize('root_url', ( 'https://koji.example.com/root', 'https://koji.example.com/root/', None )) def test_get_koji_path_info(self, fallback, root_url): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} config = { 'version': 1, 'koji': { 'hub_url': 'https://koji.example.com/hub', 'auth': { 'ssl_certs_dir': '/var/certs' } } } expected_root_url = 'https://koji.example.com/root' if root_url: config['koji']['root_url'] = root_url config_yaml = yaml.safe_dump(config) expect_error = not root_url if expect_error: with pytest.raises(Exception): read_yaml(config_yaml, 'schemas/config.json') return parsed_config = read_yaml(config_yaml, 'schemas/config.json') fallback_map = {} if fallback: fallback_map = deepcopy(config['koji']) else: workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] = \ ReactorConfig(parsed_config) (flexmock(koji.PathInfo) .should_receive('__init__') .with_args(topdir=expected_root_url) .once()) get_koji_path_info(workflow, fallback_map) @pytest.mark.parametrize('fallback', (True, False)) @pytest.mark.parametrize(('config', 'raise_error'), [ ("""\ version: 1 pulp: name: my-pulp auth: password: testpasswd username: testuser """, False), ("""\ version: 1 pulp: name: my-pulp auth: ssl_certs_dir: /var/certs """, False), ("""\ version: 1 pulp: name: my-pulp auth: ssl_certs_dir: /var/certs password: testpasswd username: testuser """, True), ("""\ version: 1 pulp: name: my-pulp auth: ssl_certs_dir: /var/certs password: testpasswd """, True), ("""\ version: 1 pulp: name: my-pulp auth: ssl_certs_dir: /var/certs username: testuser """, True), ("""\ version: 1 pulp: name: my-pulp auth: username: testuser """, True), ("""\ version: 1 pulp: name: my-pulp auth: password: testpasswd """, True), ]) def test_get_pulp_session(self, fallback, config, raise_error): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} if raise_error: with pytest.raises(Exception): read_yaml(config, 'schemas/config.json') return config_json = read_yaml(config, 'schemas/config.json') auth_info = { "pulp_secret_path": config_json['pulp']['auth'].get('ssl_certs_dir'), "username": config_json['pulp']['auth'].get('username'), "password": config_json['pulp']['auth'].get('password'), "dockpulp_loglevel": None } fallback_map = {} if fallback: fallback_map = {'auth': deepcopy(auth_info), 'name': config_json['pulp']['name']} fallback_map['auth']['ssl_certs_dir'] = fallback_map['auth'].pop('pulp_secret_path') else: workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\ ReactorConfig(config_json) (flexmock(atomic_reactor.pulp_util.PulpHandler) .should_receive('__init__') .with_args(workflow, config_json['pulp']['name'], 'logger', **auth_info) .once() .and_return(None)) get_pulp_session(workflow, 'logger', fallback_map) @pytest.mark.parametrize('fallback', (True, False)) @pytest.mark.parametrize(('config', 'raise_error'), [ ("""\ version: 1 odcs: api_url: https://odcs.example.com/api/1 auth: ssl_certs_dir: /var/run/secrets/atomic-reactor/odcssecret signing_intents: - name: release keys: [R123] default_signing_intent: default """, False), ("""\ version: 1 odcs: api_url: https://odcs.example.com/api/1 auth: ssl_certs_dir: nonexistent signing_intents: - name: release keys: [R123] default_signing_intent: default """, False), ("""\ version: 1 odcs: api_url: https://odcs.example.com/api/1 auth: openidc_dir: /var/run/open_idc signing_intents: - name: release keys: [R123] default_signing_intent: default """, False), ("""\ version: 1 odcs: api_url: https://odcs.example.com/api/1 auth: openidc_dir: /var/run/open_idc ssl_certs_dir: /var/run/secrets/atomic-reactor/odcssecret signing_intents: - name: release keys: [R123] default_signing_intent: default """, True), ("""\ version: 1 odcs: api_url: https://odcs.example.com/api/1 auth: openidc_dir: /var/run/open_idc signing_intents: - name: release keys: [R123] """, True), ("""\ version: 1 odcs: api_url: https://odcs.example.com/api/1 auth: openidc_dir: /var/run/open_idc default_signing_intent: default """, True), ("""\ version: 1 odcs: auth: openidc_dir: /var/run/open_idc signing_intents: - name: release keys: [R123] default_signing_intent: default """, True), ]) def test_get_odcs_session(self, tmpdir, fallback, config, raise_error): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} if raise_error: with pytest.raises(Exception): read_yaml(config, 'schemas/config.json') return config_json = read_yaml(config, 'schemas/config.json') auth_info = {'insecure': config_json['odcs'].get('insecure', False)} if 'openidc_dir' in config_json['odcs']['auth']: config_json['odcs']['auth']['openidc_dir'] = str(tmpdir) filename = str(tmpdir.join('token')) with open(filename, 'w') as fp: fp.write("my_token") auth_info['token'] = "my_token" ssl_dir_raise = False if 'ssl_certs_dir' in config_json['odcs']['auth']: if config_json['odcs']['auth']['ssl_certs_dir'] != "nonexistent": config_json['odcs']['auth']['ssl_certs_dir'] = str(tmpdir) filename = str(tmpdir.join('cert')) with open(filename, 'w') as fp: fp.write("my_cert") auth_info['cert'] = filename else: ssl_dir_raise = True fallback_map = {} if fallback: fallback_map = {'auth': deepcopy(auth_info), 'api_url': config_json['odcs']['api_url']} fallback_map['auth']['ssl_certs_dir'] = config_json['odcs']['auth'].get('ssl_certs_dir') fallback_map['auth']['openidc_dir'] = config_json['odcs']['auth'].get('openidc_dir') else: workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\ ReactorConfig(config_json) if not ssl_dir_raise: (flexmock(atomic_reactor.odcs_util.ODCSClient) .should_receive('__init__') .with_args(config_json['odcs']['api_url'], **auth_info) .once() .and_return(None)) get_odcs_session(workflow, fallback_map) else: with pytest.raises(KeyError): get_odcs_session(workflow, fallback_map) @pytest.mark.parametrize('fallback', (True, False)) @pytest.mark.parametrize(('config', 'raise_error'), [ ("""\ version: 1 smtp: host: smtp.example.com from_address: osbs@example.com """, False), ("""\ version: 1 smtp: from_address: osbs@example.com """, True), ("""\ version: 1 smtp: host: smtp.example.com """, True), ("""\ version: 1 smtp: """, True), ]) def test_get_smtp_session(self, fallback, config, raise_error): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} if raise_error: with pytest.raises(Exception): read_yaml(config, 'schemas/config.json') return config_json = read_yaml(config, 'schemas/config.json') fallback_map = {} if fallback: fallback_map['host'] = config_json['smtp']['host'] else: workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\ ReactorConfig(config_json) (flexmock(smtplib.SMTP) .should_receive('__init__') .with_args(config_json['smtp']['host']) .once() .and_return(None)) get_smtp_session(workflow, fallback_map) @pytest.mark.parametrize('fallback', (True, False)) @pytest.mark.parametrize('build_json_dir', [ None, "/tmp/build_json_dir", ]) @pytest.mark.parametrize(('config', 'raise_error'), [ ("""\ version: 1 openshift: url: https://openshift.example.com auth: ssl_certs_dir: /var/run/secrets/atomic-reactor/odcssecret """, False), ("""\ version: 1 openshift: url: https://openshift.example.com """, False), ("""\ version: 1 openshift: url: https://openshift.example.com auth: krb_principal: principal krb_keytab_path: /var/keytab """, False), ("""\ version: 1 openshift: url: https://openshift.example.com auth: krb_principal: principal krb_keytab_path: /var/keytab krb_cache_path: /var/krb/cache """, False), ("""\ version: 1 openshift: url: https://openshift.example.com auth: enable: True """, False), ("""\ version: 1 openshift: url: https://openshift.example.com auth: krb_keytab_path: /var/keytab """, True), ("""\ version: 1 openshift: url: https://openshift.example.com auth: krb_principal: principal """, True), ("""\ version: 1 openshift: auth: ssl_certs_dir: /var/run/secrets/atomic-reactor/odcssecret """, True), ("""\ version: 1 openshift: auth: krb_principal: principal krb_keytab_path: /var/keytab """, True), ("""\ version: 1 openshift: url: https://openshift.example.com auth: """, True), ("""\ version: 1 openshift: auth: ssl_certs_dir: /var/run/secrets/atomic-reactor/odcssecret """, True), ]) def test_get_openshift_session(self, fallback, build_json_dir, config, raise_error): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} if build_json_dir: config += " build_json_dir: " + build_json_dir if raise_error: with pytest.raises(Exception): read_yaml(config, 'schemas/config.json') return config_json = read_yaml(config, 'schemas/config.json') auth_info = { 'openshift_url': config_json['openshift']['url'], 'verify_ssl': not config_json['openshift'].get('insecure', False), 'use_auth': False, 'conf_file': None, 'namespace': 'namespace', 'build_json_dir': build_json_dir } if config_json['openshift'].get('auth'): if config_json['openshift']['auth'].get('krb_keytab_path'): auth_info['kerberos_keytab'] =\ config_json['openshift']['auth'].get('krb_keytab_path') if config_json['openshift']['auth'].get('krb_principal'): auth_info['kerberos_principal'] =\ config_json['openshift']['auth'].get('krb_principal') if config_json['openshift']['auth'].get('krb_cache_path'): auth_info['kerberos_ccache'] =\ config_json['openshift']['auth'].get('krb_cache_path') if config_json['openshift']['auth'].get('ssl_certs_dir'): auth_info['client_cert'] =\ os.path.join(config_json['openshift']['auth'].get('ssl_certs_dir'), 'cert') auth_info['client_key'] =\ os.path.join(config_json['openshift']['auth'].get('ssl_certs_dir'), 'key') auth_info['use_auth'] = config_json['openshift']['auth'].get('enable', False) fallback_map = {} if fallback: fallback_map = {'url': config_json['openshift']['url'], 'insecure': config_json['openshift'].get('insecure', False), 'build_json_dir': build_json_dir} if config_json['openshift'].get('auth'): fallback_map['auth'] = {} fallback_map['auth']['krb_keytab_path'] =\ config_json['openshift']['auth'].get('krb_keytab_path') fallback_map['auth']['krb_principal'] =\ config_json['openshift']['auth'].get('krb_principal') fallback_map['auth']['enable'] =\ config_json['openshift']['auth'].get('enable', False) fallback_map['auth']['krb_cache_path'] =\ config_json['openshift']['auth'].get('krb_cache_path') fallback_map['auth']['ssl_certs_dir'] =\ config_json['openshift']['auth'].get('ssl_certs_dir') else: workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\ ReactorConfig(config_json) (flexmock(osbs.conf.Configuration) .should_call('__init__') .with_args(**auth_info) .once()) (flexmock(osbs.api.OSBS) .should_call('__init__') .once()) flexmock(os, environ={'BUILD': '{"metadata": {"namespace": "namespace"}}'}) get_openshift_session(workflow, fallback_map)
true
true
f725b47e46e1f08db69cea2aabe9aacaac375090
1,044
py
Python
scripts/create_playlist.py
Spotify-Open-Recommendation-Engine/spotify-open-recommendation-engine
9417d8d45f662f3ca6337d599b4a91d932df2fed
[ "MIT" ]
1
2021-12-10T08:08:20.000Z
2021-12-10T08:08:20.000Z
scripts/create_playlist.py
Spotify-Open-Recommendation-Engine/spotify-open-recommendation-engine
9417d8d45f662f3ca6337d599b4a91d932df2fed
[ "MIT" ]
3
2021-11-07T00:40:49.000Z
2021-11-30T03:29:17.000Z
scripts/create_playlist.py
Spotify-Open-Recommendation-Engine/spotify-open-recommendation-engine
9417d8d45f662f3ca6337d599b4a91d932df2fed
[ "MIT" ]
1
2021-12-10T08:08:14.000Z
2021-12-10T08:08:14.000Z
""" create_playlist.py creates a playlist in user librabry and returns the playlist id parameters: auth, list of tracks to add """ import spotipy from spotipy.oauth2 import SpotifyOAuth from .spotifyoauth import get_token from ..common import session def create_playlist(name, songs): #get token session['token_info'], authorized = get_token() if authorized: sp = spotipy.Spotify(auth=session.get('token_info').get('access_token')) user_id = sp.me()['id'] playlist_name = name playlist_description = "Playlist generated by Spotify Open Recommendation Engine" #create playlist playlist = sp.user_playlist_create(user_id, playlist_name, public=True, collaborative=False, description = playlist_description ) #add tracks to playlist playlist_id = playlist['id'] sp.user_playlist_add_tracks(user_id, playlist_id = playlist_id, tracks = songs) return playlist_id else: return "(search_for) error: not authorized"
30.705882
138
0.694444
import spotipy from spotipy.oauth2 import SpotifyOAuth from .spotifyoauth import get_token from ..common import session def create_playlist(name, songs): session['token_info'], authorized = get_token() if authorized: sp = spotipy.Spotify(auth=session.get('token_info').get('access_token')) user_id = sp.me()['id'] playlist_name = name playlist_description = "Playlist generated by Spotify Open Recommendation Engine" playlist = sp.user_playlist_create(user_id, playlist_name, public=True, collaborative=False, description = playlist_description ) playlist_id = playlist['id'] sp.user_playlist_add_tracks(user_id, playlist_id = playlist_id, tracks = songs) return playlist_id else: return "(search_for) error: not authorized"
true
true
f725b4e6f7ed90c7f9aa29ca91d0ae4c5bd280a2
183
py
Python
tests/configs/config_for_test.py
akamaus/picograd
fe3a377806d3abd389a59d48981123c569c0e545
[ "MIT" ]
null
null
null
tests/configs/config_for_test.py
akamaus/picograd
fe3a377806d3abd389a59d48981123c569c0e545
[ "MIT" ]
null
null
null
tests/configs/config_for_test.py
akamaus/picograd
fe3a377806d3abd389a59d48981123c569c0e545
[ "MIT" ]
null
null
null
from picograd.configs.base import BaseConfig class Config(BaseConfig): def __init__(self, **kwargs): self.a = 2 self.b = None super().__init__(**kwargs)
20.333333
44
0.628415
from picograd.configs.base import BaseConfig class Config(BaseConfig): def __init__(self, **kwargs): self.a = 2 self.b = None super().__init__(**kwargs)
true
true
f725b4f6bffa7492d249043f68f18a216407ef16
1,145
py
Python
scripts-master/python/MCSingleFile.py
HanLabBU/Trace-conditioning-hippocampus
960e4b4d92e42697649b9b9a684ecf9c4cbb79f6
[ "Apache-2.0" ]
null
null
null
scripts-master/python/MCSingleFile.py
HanLabBU/Trace-conditioning-hippocampus
960e4b4d92e42697649b9b9a684ecf9c4cbb79f6
[ "Apache-2.0" ]
null
null
null
scripts-master/python/MCSingleFile.py
HanLabBU/Trace-conditioning-hippocampus
960e4b4d92e42697649b9b9a684ecf9c4cbb79f6
[ "Apache-2.0" ]
null
null
null
''' Script to motion correct a single multipage .tif stack using the Python Tif Motion Correction (ptmc) package Requires ptmc, PIL and their dependencies ''' from ptmc import io from ptmc import processing as pro from PIL import Image import numpy as np if __name__ == "__main__": #Full Processing without I/O takes (1288.67 sec, 21 min 29 sec) #Loading imgstack, fileparts = io.loadImageStack() #Processing Steps medstack = pro.doMedianFilter(imgstack, med_fsize=3) homomorphstack = pro.doHomomorphicFilter(medstack, sigmaVal=7) homoshift, yshift, xshift = pro.registerImages(homomorphstack) rawshift = pro.applyFrameShifts(imgstack, yshift, xshift) #Save Output io.saveFrameShifts(yshift, xshift, fileparts[0]+'/'+fileparts[1], fileparts[0]+'/'+fileparts[1][:-4]+'_frameShifts.hdf5') io.saveImageStack(homoshift, fileparts[0]+'/m_f_'+fileparts[1]) io.saveImageStack(rawshift, fileparts[0]+'/m_'+fileparts[1]) refIm = Image.fromarray(homoshift.mean(axis=0).astype(np.uint16)) refIm.save(fileparts[0]+'/'+fileparts[1][:-4]+'_MCrefImage.tif')
38.166667
108
0.70131
from ptmc import io from ptmc import processing as pro from PIL import Image import numpy as np if __name__ == "__main__": imgstack, fileparts = io.loadImageStack() medstack = pro.doMedianFilter(imgstack, med_fsize=3) homomorphstack = pro.doHomomorphicFilter(medstack, sigmaVal=7) homoshift, yshift, xshift = pro.registerImages(homomorphstack) rawshift = pro.applyFrameShifts(imgstack, yshift, xshift) io.saveFrameShifts(yshift, xshift, fileparts[0]+'/'+fileparts[1], fileparts[0]+'/'+fileparts[1][:-4]+'_frameShifts.hdf5') io.saveImageStack(homoshift, fileparts[0]+'/m_f_'+fileparts[1]) io.saveImageStack(rawshift, fileparts[0]+'/m_'+fileparts[1]) refIm = Image.fromarray(homoshift.mean(axis=0).astype(np.uint16)) refIm.save(fileparts[0]+'/'+fileparts[1][:-4]+'_MCrefImage.tif')
true
true
f725b57fcbeafb739b268af3654544d0b94e7b35
980
py
Python
prj/api/views.py
rendrom/django-dynamit
4280da60212ffd9ad6a8cb96a7eba0890a98fee5
[ "MIT" ]
3
2015-01-20T18:43:16.000Z
2015-12-09T06:46:55.000Z
prj/api/views.py
rendrom/django-dynamit
4280da60212ffd9ad6a8cb96a7eba0890a98fee5
[ "MIT" ]
null
null
null
prj/api/views.py
rendrom/django-dynamit
4280da60212ffd9ad6a8cb96a7eba0890a98fee5
[ "MIT" ]
null
null
null
from prj.api import serializers, permissions, authenticators from rest_framework.views import APIView from django.contrib.auth.models import User from rest_framework.response import Response from rest_framework import viewsets from django.contrib.auth import login, logout from rest_framework.permissions import AllowAny class UserView(viewsets.ModelViewSet): serializer_class = serializers.UserSerializer model = User def get_permissions(self): # allow non-authenticated user to create return (AllowAny() if self.request.method == 'POST' else permissions.IsStaffOrTargetUser()), class AuthView(APIView): authentication_classes = (authenticators.QuietBasicAuthentication,) def post(self, request, *args, **kwargs): login(request, request.user) return Response(serializers.UserSerializer(request.user).data) def delete(self, request, *args, **kwargs): logout(request) return Response()
32.666667
71
0.743878
from prj.api import serializers, permissions, authenticators from rest_framework.views import APIView from django.contrib.auth.models import User from rest_framework.response import Response from rest_framework import viewsets from django.contrib.auth import login, logout from rest_framework.permissions import AllowAny class UserView(viewsets.ModelViewSet): serializer_class = serializers.UserSerializer model = User def get_permissions(self): return (AllowAny() if self.request.method == 'POST' else permissions.IsStaffOrTargetUser()), class AuthView(APIView): authentication_classes = (authenticators.QuietBasicAuthentication,) def post(self, request, *args, **kwargs): login(request, request.user) return Response(serializers.UserSerializer(request.user).data) def delete(self, request, *args, **kwargs): logout(request) return Response()
true
true
f725b5d9ea2e0f39b32bd5e6e8f910abfce3039b
7,348
py
Python
tensorflow_datasets/structured/htru2.py
jedlimlx/datasets
dffdc800d3d1f5c39f311f35de3530487153d335
[ "Apache-2.0" ]
null
null
null
tensorflow_datasets/structured/htru2.py
jedlimlx/datasets
dffdc800d3d1f5c39f311f35de3530487153d335
[ "Apache-2.0" ]
null
null
null
tensorflow_datasets/structured/htru2.py
jedlimlx/datasets
dffdc800d3d1f5c39f311f35de3530487153d335
[ "Apache-2.0" ]
null
null
null
"""Dataset for Predicting a Pulsar Star""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow_datasets.public_api as tfds import tensorflow as tf import os _CITATION = """\ @article{10.1093/mnras/stw656, author = {Lyon, R. J. and Stappers, B. W. and Cooper, S. and Brooke, J. M. and Knowles, J. D.}, title = "{Fifty years of pulsar candidate selection: from simple filters to a new principled real-time classification approach}", journal = {Monthly Notices of the Royal Astronomical Society}, volume = {459}, number = {1}, pages = {1104-1123}, year = {2016}, month = {04}, abstract = "{Improving survey specifications are causing an exponential rise in pulsar candidate numbers and data volumes. We study the candidate filters used to mitigate these problems during the past 50 years. We find that some existing methods such as applying constraints on the total number of candidates collected per observation, may have detrimental effects on the success of pulsar searches. Those methods immune to such effects are found to be ill-equipped to deal with the problems associated with increasing data volumes and candidate numbers, motivating the development of new approaches. We therefore present a new method designed for online operation. It selects promising candidates using a purpose-built tree-based machine learning classifier, the Gaussian Hellinger Very Fast Decision Tree, and a new set of features for describing candidates. The features have been chosen so as to (i) maximize the separation between candidates arising from noise and those of probable astrophysical origin, and (ii) be as survey-independent as possible. Using these features our new approach can process millions of candidates in seconds (∼1 million every 15 s), with high levels of pulsar recall (90 per cent+). This technique is therefore applicable to the large volumes of data expected to be produced by the Square Kilometre Array. Use of this approach has assisted in the discovery of 20 new pulsars in data obtained during the Low-Frequency Array Tied-Array All-Sky Survey.}", issn = {0035-8711}, doi = {10.1093/mnras/stw656}, url = {https://doi.org/10.1093/mnras/stw656}, eprint = {http://oup.prod.sis.lan/mnras/article-pdf/459/1/1104/8115310/stw656.pdf}, } """ _DESCRIPTION = """\ HTRU2 is a data set which describes a sample of pulsar candidates collected during the High Time Resolution Universe Survey (South). Pulsars are a rare type of Neutron star that produce radio emission detectable here on Earth. They are of considerable scientific interest as probes of space-time, the inter-stellar medium, and states of matter. As pulsars rotate, their emission beam sweeps across the sky, and when this crosses our line of sight, produces a detectable pattern of broadband radio emission. As pulsars rotate rapidly, this pattern repeats periodically. Thus, pulsar search involves looking for periodic radio signals with large radio telescopes. Each pulsar produces a slightly different emission pattern, which varies slightly with each rotation. Thus a potential signal detection known as a 'candidate', is averaged over many rotations of the pulsar, as determined by the length of an observation. In the absence of additional info, each candidate could potentially describe a real pulsar. However, in practice almost all detections are caused by radio frequency interference (RFI) and noise, making legitimate signals hard to find. Machine learning tools are now being used to automatically label pulsar candidates to facilitate rapid analysis. Classification systems in particular are being widely adopted, which treat the candidate data sets as binary classification problems. Here the legitimate pulsar examples are a minority positive class, and spurious examples the majority negative class. At present multi-class labels are unavailable, given the costs associated with data annotation. The data set shared here contains 16,259 spurious examples caused by RFI/noise, and 1,639 real pulsar examples. These examples have all been checked by human annotators. """ _URL = "http://archive.ics.uci.edu/ml/machine-learning-databases/00372/HTRU2.zip" class Htru2(tfds.core.GeneratorBasedBuilder): """Dataset for Predicting a Pulsar Star""" VERSION = tfds.core.Version('2.0.0', experiments={tfds.core.Experiment.S3: False}) def _info(self): return tfds.core.DatasetInfo( builder=self, description=_DESCRIPTION, features=tfds.features.FeaturesDict({ "Features" : tfds.features.FeaturesDict({ "Mean of the integrated profile" : tf.float64, "Standard deviation of the integrated profile" : tf.float64, "Excess kurtosis of the integrated profile" : tf.float64, "Skewness of the integrated profile" : tf.float64, "Mean of the DM-SNR curve" : tf.float64, "Standard deviation of the DM-SNR curve" : tf.float64, "Excess kurtosis of the DM-SNR curve" : tf.float64, "Skewness of the DM-SNR curve" : tf.float64, }), "Class" : tfds.features.ClassLabel(num_classes=2) }), supervised_keys=None, homepage="https://archive.ics.uci.edu/ml/datasets/HTRU2", citation=_CITATION, ) def _split_generators(self, dl_manager): """Returns SplitGenerators.""" path = dl_manager.download_and_extract(_URL) return [ tfds.core.SplitGenerator( name=tfds.Split.TRAIN, num_shards=1, gen_kwargs={ 'file_path': path, }), ] def _generate_examples(self, file_path): """Yields examples.""" with tf.io.gfile.GFile(os.path.join(file_path, "HTRU_2.csv"), "r") as csvfile: features = [ "Mean of the integrated profile", "Standard deviation of the integrated profile", "Excess kurtosis of the integrated profile", "Skewness of the integrated profile", "Mean of the DM-SNR curve", "Standard deviation of the DM-SNR curve", "Excess kurtosis of the DM-SNR curve", "Skewness of the DM-SNR curve", "Class" # 0 for noise, 1 for pulsar ] lines = csvfile.readlines() for i in lines: feature_lst = i.split(",") length_increase = 0 for j in range(len(feature_lst)): if j % (len(features) - 1) == 0 and j != 0: temp = feature_lst[j + length_increase][0:] feature_lst[j + length_increase] = feature_lst[j + length_increase][0] feature_lst.insert(j + length_increase + 1, temp) length_increase += 1 feature_dict = {} for j in range(len(feature_lst)): if j % len(features) == 0: feature_dict = {} feature_dict[features[j % len(features)]] = float(feature_lst[j]) elif j % len(features) < len(features) - 1: feature_dict[features[j % len(features)]] = float(feature_lst[j]) elif j % len(features) == len(features) - 1: yield j // len(features), {"Features" : feature_dict, "Class" : int(feature_lst[j])}
56.523077
1,490
0.69951
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow_datasets.public_api as tfds import tensorflow as tf import os _CITATION = """\ @article{10.1093/mnras/stw656, author = {Lyon, R. J. and Stappers, B. W. and Cooper, S. and Brooke, J. M. and Knowles, J. D.}, title = "{Fifty years of pulsar candidate selection: from simple filters to a new principled real-time classification approach}", journal = {Monthly Notices of the Royal Astronomical Society}, volume = {459}, number = {1}, pages = {1104-1123}, year = {2016}, month = {04}, abstract = "{Improving survey specifications are causing an exponential rise in pulsar candidate numbers and data volumes. We study the candidate filters used to mitigate these problems during the past 50 years. We find that some existing methods such as applying constraints on the total number of candidates collected per observation, may have detrimental effects on the success of pulsar searches. Those methods immune to such effects are found to be ill-equipped to deal with the problems associated with increasing data volumes and candidate numbers, motivating the development of new approaches. We therefore present a new method designed for online operation. It selects promising candidates using a purpose-built tree-based machine learning classifier, the Gaussian Hellinger Very Fast Decision Tree, and a new set of features for describing candidates. The features have been chosen so as to (i) maximize the separation between candidates arising from noise and those of probable astrophysical origin, and (ii) be as survey-independent as possible. Using these features our new approach can process millions of candidates in seconds (∼1 million every 15 s), with high levels of pulsar recall (90 per cent+). This technique is therefore applicable to the large volumes of data expected to be produced by the Square Kilometre Array. Use of this approach has assisted in the discovery of 20 new pulsars in data obtained during the Low-Frequency Array Tied-Array All-Sky Survey.}", issn = {0035-8711}, doi = {10.1093/mnras/stw656}, url = {https://doi.org/10.1093/mnras/stw656}, eprint = {http://oup.prod.sis.lan/mnras/article-pdf/459/1/1104/8115310/stw656.pdf}, } """ _DESCRIPTION = """\ HTRU2 is a data set which describes a sample of pulsar candidates collected during the High Time Resolution Universe Survey (South). Pulsars are a rare type of Neutron star that produce radio emission detectable here on Earth. They are of considerable scientific interest as probes of space-time, the inter-stellar medium, and states of matter. As pulsars rotate, their emission beam sweeps across the sky, and when this crosses our line of sight, produces a detectable pattern of broadband radio emission. As pulsars rotate rapidly, this pattern repeats periodically. Thus, pulsar search involves looking for periodic radio signals with large radio telescopes. Each pulsar produces a slightly different emission pattern, which varies slightly with each rotation. Thus a potential signal detection known as a 'candidate', is averaged over many rotations of the pulsar, as determined by the length of an observation. In the absence of additional info, each candidate could potentially describe a real pulsar. However, in practice almost all detections are caused by radio frequency interference (RFI) and noise, making legitimate signals hard to find. Machine learning tools are now being used to automatically label pulsar candidates to facilitate rapid analysis. Classification systems in particular are being widely adopted, which treat the candidate data sets as binary classification problems. Here the legitimate pulsar examples are a minority positive class, and spurious examples the majority negative class. At present multi-class labels are unavailable, given the costs associated with data annotation. The data set shared here contains 16,259 spurious examples caused by RFI/noise, and 1,639 real pulsar examples. These examples have all been checked by human annotators. """ _URL = "http://archive.ics.uci.edu/ml/machine-learning-databases/00372/HTRU2.zip" class Htru2(tfds.core.GeneratorBasedBuilder): VERSION = tfds.core.Version('2.0.0', experiments={tfds.core.Experiment.S3: False}) def _info(self): return tfds.core.DatasetInfo( builder=self, description=_DESCRIPTION, features=tfds.features.FeaturesDict({ "Features" : tfds.features.FeaturesDict({ "Mean of the integrated profile" : tf.float64, "Standard deviation of the integrated profile" : tf.float64, "Excess kurtosis of the integrated profile" : tf.float64, "Skewness of the integrated profile" : tf.float64, "Mean of the DM-SNR curve" : tf.float64, "Standard deviation of the DM-SNR curve" : tf.float64, "Excess kurtosis of the DM-SNR curve" : tf.float64, "Skewness of the DM-SNR curve" : tf.float64, }), "Class" : tfds.features.ClassLabel(num_classes=2) }), supervised_keys=None, homepage="https://archive.ics.uci.edu/ml/datasets/HTRU2", citation=_CITATION, ) def _split_generators(self, dl_manager): path = dl_manager.download_and_extract(_URL) return [ tfds.core.SplitGenerator( name=tfds.Split.TRAIN, num_shards=1, gen_kwargs={ 'file_path': path, }), ] def _generate_examples(self, file_path): with tf.io.gfile.GFile(os.path.join(file_path, "HTRU_2.csv"), "r") as csvfile: features = [ "Mean of the integrated profile", "Standard deviation of the integrated profile", "Excess kurtosis of the integrated profile", "Skewness of the integrated profile", "Mean of the DM-SNR curve", "Standard deviation of the DM-SNR curve", "Excess kurtosis of the DM-SNR curve", "Skewness of the DM-SNR curve", "Class" ] lines = csvfile.readlines() for i in lines: feature_lst = i.split(",") length_increase = 0 for j in range(len(feature_lst)): if j % (len(features) - 1) == 0 and j != 0: temp = feature_lst[j + length_increase][0:] feature_lst[j + length_increase] = feature_lst[j + length_increase][0] feature_lst.insert(j + length_increase + 1, temp) length_increase += 1 feature_dict = {} for j in range(len(feature_lst)): if j % len(features) == 0: feature_dict = {} feature_dict[features[j % len(features)]] = float(feature_lst[j]) elif j % len(features) < len(features) - 1: feature_dict[features[j % len(features)]] = float(feature_lst[j]) elif j % len(features) == len(features) - 1: yield j // len(features), {"Features" : feature_dict, "Class" : int(feature_lst[j])}
true
true
f725b98098001c143ac1f1d06ba793a9900a5629
4,010
py
Python
test/mitmproxy/io/test_protobuf.py
asfaltboy/mitmproxy
f245d247674b0d7c7cca327cd2be5a0bcf01b27d
[ "MIT" ]
7
2020-11-29T11:42:44.000Z
2022-03-28T15:31:38.000Z
test/mitmproxy/io/test_protobuf.py
asfaltboy/mitmproxy
f245d247674b0d7c7cca327cd2be5a0bcf01b27d
[ "MIT" ]
7
2020-06-16T06:35:02.000Z
2022-03-15T20:15:53.000Z
test/mitmproxy/io/test_protobuf.py
asfaltboy/mitmproxy
f245d247674b0d7c7cca327cd2be5a0bcf01b27d
[ "MIT" ]
1
2021-08-31T05:02:59.000Z
2021-08-31T05:02:59.000Z
import pytest from mitmproxy import certs from mitmproxy import http from mitmproxy import exceptions from mitmproxy.test import tflow, tutils from mitmproxy.io import protobuf class TestProtobuf: def test_roundtrip_client(self): c = tflow.tclient_conn() del c.reply c.rfile = None c.wfile = None pc = protobuf._dump_http_client_conn(c) lc = protobuf._load_http_client_conn(pc) assert c.__dict__ == lc.__dict__ def test_roundtrip_client_cert(self, tdata): c = tflow.tclient_conn() c.rfile = None c.wfile = None del c.reply with open(tdata.path("mitmproxy/net/data/clientcert/client.pem"), "rb") as f: d = f.read() c.clientcert = certs.Cert.from_pem(d) pc = protobuf._dump_http_client_conn(c) lc = protobuf._load_http_client_conn(pc) assert c.__dict__ == lc.__dict__ def test_roundtrip_server(self): s = tflow.tserver_conn() del s.reply s.wfile = None s.rfile = None ps = protobuf._dump_http_server_conn(s) ls = protobuf._load_http_server_conn(ps) assert s.__dict__ == ls.__dict__ def test_roundtrip_server_cert(self, tdata): s = tflow.tserver_conn() del s.reply s.wfile = None s.rfile = None with open(tdata.path("mitmproxy/net/data/text_cert"), "rb") as f: d = f.read() s.cert = certs.Cert.from_pem(d) ps = protobuf._dump_http_server_conn(s) ls = protobuf._load_http_server_conn(ps) assert s.__dict__ == ls.__dict__ def test_roundtrip_server_via(self): s = tflow.tserver_conn() s.via = tflow.tserver_conn() del s.reply s.wfile = None s.rfile = None ps = protobuf._dump_http_server_conn(s) ls = protobuf._load_http_server_conn(ps) assert s.__dict__ == ls.__dict__ del s.via.reply s.via.wfile = None s.via.rfile = None assert s.via.__dict__ == ls.via.__dict__ def test_roundtrip_http_request(self): req = http.HTTPRequest.wrap(tutils.treq()) preq = protobuf._dump_http_request(req) lreq = protobuf._load_http_request(preq) assert req.__dict__ == lreq.__dict__ def test_roundtrip_http_request_empty_content(self): req = http.HTTPRequest.wrap(tutils.treq(content=b"")) preq = protobuf._dump_http_request(req) lreq = protobuf._load_http_request(preq) assert req.__dict__ == lreq.__dict__ def test_roundtrip_http_response(self): res = http.HTTPResponse.wrap(tutils.tresp()) pres = protobuf._dump_http_response(res) lres = protobuf._load_http_response(pres) assert res.__dict__ == lres.__dict__ def test_roundtrip_http_response_empty_content(self): res = http.HTTPResponse.wrap(tutils.tresp(content=b"")) pres = protobuf._dump_http_response(res) lres = protobuf._load_http_response(pres) assert res.__dict__ == lres.__dict__ def test_roundtrip_http_error(self): err = tflow.terr() perr = protobuf._dump_http_error(err) lerr = protobuf._load_http_error(perr) assert err.__dict__ == lerr.__dict__ def test_roundtrip_http_flow_only_req(self): f = tflow.tflow() f.reply = None pf = protobuf.dumps(f) lf = protobuf.loads(pf, "http") assert f.__dict__ == lf.__dict__ def test_roundtrip_http_flow_res(self): f = tflow.tflow(resp=True) f.reply = None pf = protobuf.dumps(f) lf = protobuf.loads(pf, "http") assert f.__dict__ == lf.__dict__ def test_unsupported_dumps(self): w = tflow.twebsocketflow() with pytest.raises(exceptions.TypeError): protobuf.dumps(w) def test_unsupported_loads(self): b = b"blobs" with pytest.raises(exceptions.TypeError): protobuf.loads(b, 'not-http')
33.140496
85
0.638903
import pytest from mitmproxy import certs from mitmproxy import http from mitmproxy import exceptions from mitmproxy.test import tflow, tutils from mitmproxy.io import protobuf class TestProtobuf: def test_roundtrip_client(self): c = tflow.tclient_conn() del c.reply c.rfile = None c.wfile = None pc = protobuf._dump_http_client_conn(c) lc = protobuf._load_http_client_conn(pc) assert c.__dict__ == lc.__dict__ def test_roundtrip_client_cert(self, tdata): c = tflow.tclient_conn() c.rfile = None c.wfile = None del c.reply with open(tdata.path("mitmproxy/net/data/clientcert/client.pem"), "rb") as f: d = f.read() c.clientcert = certs.Cert.from_pem(d) pc = protobuf._dump_http_client_conn(c) lc = protobuf._load_http_client_conn(pc) assert c.__dict__ == lc.__dict__ def test_roundtrip_server(self): s = tflow.tserver_conn() del s.reply s.wfile = None s.rfile = None ps = protobuf._dump_http_server_conn(s) ls = protobuf._load_http_server_conn(ps) assert s.__dict__ == ls.__dict__ def test_roundtrip_server_cert(self, tdata): s = tflow.tserver_conn() del s.reply s.wfile = None s.rfile = None with open(tdata.path("mitmproxy/net/data/text_cert"), "rb") as f: d = f.read() s.cert = certs.Cert.from_pem(d) ps = protobuf._dump_http_server_conn(s) ls = protobuf._load_http_server_conn(ps) assert s.__dict__ == ls.__dict__ def test_roundtrip_server_via(self): s = tflow.tserver_conn() s.via = tflow.tserver_conn() del s.reply s.wfile = None s.rfile = None ps = protobuf._dump_http_server_conn(s) ls = protobuf._load_http_server_conn(ps) assert s.__dict__ == ls.__dict__ del s.via.reply s.via.wfile = None s.via.rfile = None assert s.via.__dict__ == ls.via.__dict__ def test_roundtrip_http_request(self): req = http.HTTPRequest.wrap(tutils.treq()) preq = protobuf._dump_http_request(req) lreq = protobuf._load_http_request(preq) assert req.__dict__ == lreq.__dict__ def test_roundtrip_http_request_empty_content(self): req = http.HTTPRequest.wrap(tutils.treq(content=b"")) preq = protobuf._dump_http_request(req) lreq = protobuf._load_http_request(preq) assert req.__dict__ == lreq.__dict__ def test_roundtrip_http_response(self): res = http.HTTPResponse.wrap(tutils.tresp()) pres = protobuf._dump_http_response(res) lres = protobuf._load_http_response(pres) assert res.__dict__ == lres.__dict__ def test_roundtrip_http_response_empty_content(self): res = http.HTTPResponse.wrap(tutils.tresp(content=b"")) pres = protobuf._dump_http_response(res) lres = protobuf._load_http_response(pres) assert res.__dict__ == lres.__dict__ def test_roundtrip_http_error(self): err = tflow.terr() perr = protobuf._dump_http_error(err) lerr = protobuf._load_http_error(perr) assert err.__dict__ == lerr.__dict__ def test_roundtrip_http_flow_only_req(self): f = tflow.tflow() f.reply = None pf = protobuf.dumps(f) lf = protobuf.loads(pf, "http") assert f.__dict__ == lf.__dict__ def test_roundtrip_http_flow_res(self): f = tflow.tflow(resp=True) f.reply = None pf = protobuf.dumps(f) lf = protobuf.loads(pf, "http") assert f.__dict__ == lf.__dict__ def test_unsupported_dumps(self): w = tflow.twebsocketflow() with pytest.raises(exceptions.TypeError): protobuf.dumps(w) def test_unsupported_loads(self): b = b"blobs" with pytest.raises(exceptions.TypeError): protobuf.loads(b, 'not-http')
true
true
f725baf4c670c00b71a89f3aa043b3ec06944a52
530
py
Python
AI DIET PLANNER Microservice/website/migrations/0011_auto_20201208_0103.py
ricksaha2000/MedBay-V1
ee8ead4c3583066c778dc76ed0749feb70f412c8
[ "MIT" ]
null
null
null
AI DIET PLANNER Microservice/website/migrations/0011_auto_20201208_0103.py
ricksaha2000/MedBay-V1
ee8ead4c3583066c778dc76ed0749feb70f412c8
[ "MIT" ]
null
null
null
AI DIET PLANNER Microservice/website/migrations/0011_auto_20201208_0103.py
ricksaha2000/MedBay-V1
ee8ead4c3583066c778dc76ed0749feb70f412c8
[ "MIT" ]
null
null
null
# Generated by Django 3.1.3 on 2020-12-07 19:33 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('website', '0010_auto_20201120_2052'), ] operations = [ migrations.AlterField( model_name='profile', name='image', field=models.ImageField(default='C:\\\\Users\\\\jayit\\\\Downloads\\\\medbay\\\\AI DIET PLANNER Microservice\\\\media\\\\website\\\\images\\\\avtar.png', upload_to='website/images'), ), ]
27.894737
194
0.615094
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('website', '0010_auto_20201120_2052'), ] operations = [ migrations.AlterField( model_name='profile', name='image', field=models.ImageField(default='C:\\\\Users\\\\jayit\\\\Downloads\\\\medbay\\\\AI DIET PLANNER Microservice\\\\media\\\\website\\\\images\\\\avtar.png', upload_to='website/images'), ), ]
true
true
f725bb2c710b888e594d6f958fc334d74efebf61
10,916
py
Python
lib/ContigFilter_mlee/ContigFilter_mleeImpl.py
mollee55/ContigFilter
fa57051bab1c4c4d2341ecdcef9bb14955ed0a1d
[ "MIT" ]
null
null
null
lib/ContigFilter_mlee/ContigFilter_mleeImpl.py
mollee55/ContigFilter
fa57051bab1c4c4d2341ecdcef9bb14955ed0a1d
[ "MIT" ]
null
null
null
lib/ContigFilter_mlee/ContigFilter_mleeImpl.py
mollee55/ContigFilter
fa57051bab1c4c4d2341ecdcef9bb14955ed0a1d
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- #BEGIN_HEADER # The header block is where all import statments should live import logging import os from pprint import pformat from Bio import SeqIO from installed_clients.AssemblyUtilClient import AssemblyUtil from installed_clients.KBaseReportClient import KBaseReport #END_HEADER class ContigFilter_mlee: ''' Module Name: ContigFilter_mlee Module Description: A KBase module: ContigFilter This sample module contains one small method that filters contigs. ''' ######## WARNING FOR GEVENT USERS ####### noqa # Since asynchronous IO can lead to methods - even the same method - # interrupting each other, you must be *very* careful when using global # state. A method could easily clobber the state set by another while # the latter method is running. ######################################### noqa VERSION = "0.0.1" GIT_URL = "https://github.com/mollee55/ContigFilter.git" GIT_COMMIT_HASH = "0d13a1e1a62ee662a29ac8b87c900314e876611d" #BEGIN_CLASS_HEADER # Class variables and functions can be defined in this block #END_CLASS_HEADER # config contains contents of config file in a hash or None if it couldn't # be found def __init__(self, config): #BEGIN_CONSTRUCTOR # Any configuration parameters that are important should be parsed and # saved in the constructor. self.callback_url = os.environ['SDK_CALLBACK_URL'] self.shared_folder = config['scratch'] logging.basicConfig(format='%(created)s %(levelname)s: %(message)s', level=logging.INFO) #END_CONSTRUCTOR pass def run_ContigFilter(self, ctx, params): """ This example function accepts any number of parameters and returns results in a KBaseReport :param params: instance of mapping from String to unspecified object :returns: instance of type "ReportResults" -> structure: parameter "report_name" of String, parameter "report_ref" of String """ # ctx is the context object # return variables are: output #BEGIN run_ContigFilter # Print statements to stdout/stderr are captured and available as the App log logging.info('Starting run_ContigFilter function. Params=' + pformat(params)) # Step 1 - Parse/examine the parameters and catch any errors # It is important to check that parameters exist and are defined, and that nice error # messages are returned to users. Parameter values go through basic validation when # defined in a Narrative App, but advanced users or other SDK developers can call # this function directly, so validation is still important. logging.info('Validating parameters.') if 'workspace_name' not in params: raise ValueError('Parameter workspace_name is not set in input arguments') workspace_name = params['workspace_name'] if 'assembly_input_ref' not in params: raise ValueError('Parameter assembly_input_ref is not set in input arguments') assembly_input_ref = params['assembly_input_ref'] if 'min_length' not in params: raise ValueError('Parameter min_length is not set in input arguments') min_length_orig = params['min_length'] min_length = None try: min_length = int(min_length_orig) except ValueError: raise ValueError('Cannot parse integer from min_length parameter (' + str(min_length_orig) + ')') if min_length < 0: raise ValueError('min_length parameter cannot be negative (' + str(min_length) + ')') # Step 2 - Download the input data as a Fasta and # We can use the AssemblyUtils module to download a FASTA file from our Assembly data object. # The return object gives us the path to the file that was created. logging.info('Downloading Assembly data as a Fasta file.') assemblyUtil = AssemblyUtil(self.callback_url) fasta_file = assemblyUtil.get_assembly_as_fasta({'ref': assembly_input_ref}) # Step 3 - Actually perform the filter operation, saving the good contigs to a new fasta file. # We can use BioPython to parse the Fasta file and build and save the output to a file. good_contigs = [] n_total = 0 n_remaining = 0 for record in SeqIO.parse(fasta_file['path'], 'fasta'): n_total += 1 if len(record.seq) >= min_length: good_contigs.append(record) n_remaining += 1 logging.info('Filtered Assembly to ' + str(n_remaining) + ' contigs out of ' + str(n_total)) filtered_fasta_file = os.path.join(self.shared_folder, 'filtered.fasta') SeqIO.write(good_contigs, filtered_fasta_file, 'fasta') # Step 4 - Save the new Assembly back to the system logging.info('Uploading filtered Assembly data.') new_assembly = assemblyUtil.save_assembly_from_fasta({'file': {'path': filtered_fasta_file}, 'workspace_name': workspace_name, 'assembly_name': fasta_file['assembly_name'] }) # Step 5 - Build a Report and return reportObj = { 'objects_created': [{'ref': new_assembly, 'description': 'Filtered contigs'}], 'text_message': 'Filtered Assembly to ' + str(n_remaining) + ' contigs out of ' + str(n_total) } report = KBaseReport(self.callback_url) report_info = report.create({'report': reportObj, 'workspace_name': params['workspace_name']}) # STEP 6: contruct the output to send back output = {'report_name': report_info['name'], 'report_ref': report_info['ref'], 'assembly_output': new_assembly, 'n_initial_contigs': n_total, 'n_contigs_removed': n_total - n_remaining, 'n_contigs_remaining': n_remaining } logging.info('returning:' + pformat(output)) #END run_ContigFilter # At some point might do deeper type checking... if not isinstance(output, dict): raise ValueError('Method run_ContigFilter return value ' + 'output is not type dict as required.') # return the results return [output] def run_ContigFilter_max(self, ctx, params): """ New app which filters contigs in an assembly using both a minimum and a maximum contig length :param params: instance of mapping from String to unspecified object :returns: instance of type "ReportResults" -> structure: parameter "report_name" of String, parameter "report_ref" of String """ # ctx is the context object # return variables are: output #BEGIN run_ContigFilter_max # Check that the parameters are valid for name in ['min_length', 'max_length', 'assembly_input_ref', 'workspace_name']: if name not in params: raise ValueError('Parameter "' + name + '" is required but missing') if not isinstance(params['min_length'], int) or (params['min_length'] < 0): raise ValueError('Min length must be a non-negative integer') if not isinstance(params['max_length'], int) or (params['max_length'] < 0): raise ValueError('Max length must be a non-negative integer') if not isinstance(params['assembly_input_ref'], str) or not len(params['assembly_input_ref']): raise ValueError('Pass in a valid assembly reference string') print(params['min_length'], params['max_length'], params['assembly_input_ref']) output = {} assembly_util = AssemblyUtil(self.callback_url) fasta_file = assembly_util.get_assembly_as_fasta({'ref': params['assembly_input_ref']}) print(fasta_file) # Parse the downloaded file in FASTA format parsed_assembly = SeqIO.parse(fasta_file['path'], 'fasta') min_length = params['min_length'] max_length = params['max_length'] # Keep a list of contigs greater than min_length good_contigs = [] # total contigs regardless of length n_total = 0 # total contigs over the min_length n_remaining = 0 for record in parsed_assembly: n_total += 1 if len(record.seq) >= min_length and len(record.seq) <= max_length: good_contigs.append(record) n_remaining += 1 # Create a file to hold the filtered data workspace_name = params['workspace_name'] filtered_path = os.path.join(self.shared_folder, 'filtered.fasta') SeqIO.write(good_contigs, filtered_path, 'fasta') # Upload the filtered data to the workspace new_ref = assembly_util.save_assembly_from_fasta({ 'file': {'path': filtered_path}, 'workspace_name': workspace_name, 'assembly_name': fasta_file['assembly_name'] }) # Create an output summary message for the report text_message = "".join([ 'Filtered assembly to ', str(n_remaining), ' contigs out of ', str(n_total) ]) # Data for creating the report, referencing the assembly we uploaded report_data = { 'objects_created': [ {'ref': new_ref, 'description': 'Filtered contigs'} ], 'text_message': text_message } # Initialize the report kbase_report = KBaseReport(self.callback_url) report = kbase_report.create({ 'report': report_data, 'workspace_name': workspace_name }) # Return the report reference and name in our results output = { 'report_ref': report['ref'], 'report_name': report['name'], 'n_total': n_total, 'n_remaining': n_remaining, 'filtered_assembly_ref': new_ref } #END run_ContigFilter_max # At some point might do deeper type checking... if not isinstance(output, dict): raise ValueError('Method run_ContigFilter_max return value ' + 'output is not type dict as required.') # return the results return [output] def status(self, ctx): #BEGIN_STATUS returnVal = {'state': "OK", 'message': "", 'version': self.VERSION, 'git_url': self.GIT_URL, 'git_commit_hash': self.GIT_COMMIT_HASH} #END_STATUS return [returnVal]
43.49004
109
0.620282
import logging import os from pprint import pformat from Bio import SeqIO from installed_clients.AssemblyUtilClient import AssemblyUtil from installed_clients.KBaseReportClient import KBaseReport class ContigFilter_mlee: idation is still important. logging.info('Validating parameters.') if 'workspace_name' not in params: raise ValueError('Parameter workspace_name is not set in input arguments') workspace_name = params['workspace_name'] if 'assembly_input_ref' not in params: raise ValueError('Parameter assembly_input_ref is not set in input arguments') assembly_input_ref = params['assembly_input_ref'] if 'min_length' not in params: raise ValueError('Parameter min_length is not set in input arguments') min_length_orig = params['min_length'] min_length = None try: min_length = int(min_length_orig) except ValueError: raise ValueError('Cannot parse integer from min_length parameter (' + str(min_length_orig) + ')') if min_length < 0: raise ValueError('min_length parameter cannot be negative (' + str(min_length) + ')') # Step 2 - Download the input data as a Fasta and # We can use the AssemblyUtils module to download a FASTA file from our Assembly data object. # The return object gives us the path to the file that was created. logging.info('Downloading Assembly data as a Fasta file.') assemblyUtil = AssemblyUtil(self.callback_url) fasta_file = assemblyUtil.get_assembly_as_fasta({'ref': assembly_input_ref}) # Step 3 - Actually perform the filter operation, saving the good contigs to a new fasta file. # We can use BioPython to parse the Fasta file and build and save the output to a file. good_contigs = [] n_total = 0 n_remaining = 0 for record in SeqIO.parse(fasta_file['path'], 'fasta'): n_total += 1 if len(record.seq) >= min_length: good_contigs.append(record) n_remaining += 1 logging.info('Filtered Assembly to ' + str(n_remaining) + ' contigs out of ' + str(n_total)) filtered_fasta_file = os.path.join(self.shared_folder, 'filtered.fasta') SeqIO.write(good_contigs, filtered_fasta_file, 'fasta') # Step 4 - Save the new Assembly back to the system logging.info('Uploading filtered Assembly data.') new_assembly = assemblyUtil.save_assembly_from_fasta({'file': {'path': filtered_fasta_file}, 'workspace_name': workspace_name, 'assembly_name': fasta_file['assembly_name'] }) # Step 5 - Build a Report and return reportObj = { 'objects_created': [{'ref': new_assembly, 'description': 'Filtered contigs'}], 'text_message': 'Filtered Assembly to ' + str(n_remaining) + ' contigs out of ' + str(n_total) } report = KBaseReport(self.callback_url) report_info = report.create({'report': reportObj, 'workspace_name': params['workspace_name']}) # STEP 6: contruct the output to send back output = {'report_name': report_info['name'], 'report_ref': report_info['ref'], 'assembly_output': new_assembly, 'n_initial_contigs': n_total, 'n_contigs_removed': n_total - n_remaining, 'n_contigs_remaining': n_remaining } logging.info('returning:' + pformat(output)) #END run_ContigFilter # At some point might do deeper type checking... if not isinstance(output, dict): raise ValueError('Method run_ContigFilter return value ' + 'output is not type dict as required.') # return the results return [output] def run_ContigFilter_max(self, ctx, params): # ctx is the context object # return variables are: output #BEGIN run_ContigFilter_max # Check that the parameters are valid for name in ['min_length', 'max_length', 'assembly_input_ref', 'workspace_name']: if name not in params: raise ValueError('Parameter "' + name + '" is required but missing') if not isinstance(params['min_length'], int) or (params['min_length'] < 0): raise ValueError('Min length must be a non-negative integer') if not isinstance(params['max_length'], int) or (params['max_length'] < 0): raise ValueError('Max length must be a non-negative integer') if not isinstance(params['assembly_input_ref'], str) or not len(params['assembly_input_ref']): raise ValueError('Pass in a valid assembly reference string') print(params['min_length'], params['max_length'], params['assembly_input_ref']) output = {} assembly_util = AssemblyUtil(self.callback_url) fasta_file = assembly_util.get_assembly_as_fasta({'ref': params['assembly_input_ref']}) print(fasta_file) # Parse the downloaded file in FASTA format parsed_assembly = SeqIO.parse(fasta_file['path'], 'fasta') min_length = params['min_length'] max_length = params['max_length'] # Keep a list of contigs greater than min_length good_contigs = [] # total contigs regardless of length n_total = 0 # total contigs over the min_length n_remaining = 0 for record in parsed_assembly: n_total += 1 if len(record.seq) >= min_length and len(record.seq) <= max_length: good_contigs.append(record) n_remaining += 1 # Create a file to hold the filtered data workspace_name = params['workspace_name'] filtered_path = os.path.join(self.shared_folder, 'filtered.fasta') SeqIO.write(good_contigs, filtered_path, 'fasta') # Upload the filtered data to the workspace new_ref = assembly_util.save_assembly_from_fasta({ 'file': {'path': filtered_path}, 'workspace_name': workspace_name, 'assembly_name': fasta_file['assembly_name'] }) # Create an output summary message for the report text_message = "".join([ 'Filtered assembly to ', str(n_remaining), ' contigs out of ', str(n_total) ]) # Data for creating the report, referencing the assembly we uploaded report_data = { 'objects_created': [ {'ref': new_ref, 'description': 'Filtered contigs'} ], 'text_message': text_message } # Initialize the report kbase_report = KBaseReport(self.callback_url) report = kbase_report.create({ 'report': report_data, 'workspace_name': workspace_name }) # Return the report reference and name in our results output = { 'report_ref': report['ref'], 'report_name': report['name'], 'n_total': n_total, 'n_remaining': n_remaining, 'filtered_assembly_ref': new_ref } #END run_ContigFilter_max # At some point might do deeper type checking... if not isinstance(output, dict): raise ValueError('Method run_ContigFilter_max return value ' + 'output is not type dict as required.') # return the results return [output] def status(self, ctx): #BEGIN_STATUS returnVal = {'state': "OK", 'message': "", 'version': self.VERSION, 'git_url': self.GIT_URL, 'git_commit_hash': self.GIT_COMMIT_HASH} #END_STATUS return [returnVal]
true
true
f725bb3c0b460966653fe516ad1697e8a427a136
481
py
Python
shiSock-0.3.0/test/test_one_unsecure/t2.py
AnanyaRamanA/shiSock
51efb0eba17eb106b9480598d278536ddd7732c3
[ "MIT" ]
null
null
null
shiSock-0.3.0/test/test_one_unsecure/t2.py
AnanyaRamanA/shiSock
51efb0eba17eb106b9480598d278536ddd7732c3
[ "MIT" ]
null
null
null
shiSock-0.3.0/test/test_one_unsecure/t2.py
AnanyaRamanA/shiSock
51efb0eba17eb106b9480598d278536ddd7732c3
[ "MIT" ]
1
2021-10-31T13:47:42.000Z
2021-10-31T13:47:42.000Z
from PySock import client def abc(data,con): print(f"Message from {data['sender_name']} : {data['data']}") con.SEND("test","Hurrah! it's working.") def client_msg(data): print(f"Message from : {data['sender_name']} => {data['data']}") c = client(client_name = "swat", debug = True) c.CLIENT("localhost",8888) c.CREATE_CHANNEL("test") while True: c.LISTEN( channel = "test", function = abc, args = (c,) ) c.LISTEN( channel = "DSP_MSG", function = client_msg)
30.0625
68
0.64657
from PySock import client def abc(data,con): print(f"Message from {data['sender_name']} : {data['data']}") con.SEND("test","Hurrah! it's working.") def client_msg(data): print(f"Message from : {data['sender_name']} => {data['data']}") c = client(client_name = "swat", debug = True) c.CLIENT("localhost",8888) c.CREATE_CHANNEL("test") while True: c.LISTEN( channel = "test", function = abc, args = (c,) ) c.LISTEN( channel = "DSP_MSG", function = client_msg)
true
true
f725bb9042591218ea998eef0a3d5cf5dc021084
19,126
py
Python
ultracart/models/order_format.py
UltraCart/rest_api_v2_sdk_python
d734ea13fabc7a57872ff68bac06861edb8fd882
[ "Apache-2.0" ]
1
2018-03-15T16:56:23.000Z
2018-03-15T16:56:23.000Z
ultracart/models/order_format.py
UltraCart/rest_api_v2_sdk_python
d734ea13fabc7a57872ff68bac06861edb8fd882
[ "Apache-2.0" ]
null
null
null
ultracart/models/order_format.py
UltraCart/rest_api_v2_sdk_python
d734ea13fabc7a57872ff68bac06861edb8fd882
[ "Apache-2.0" ]
null
null
null
# coding: utf-8 """ UltraCart Rest API V2 UltraCart REST API Version 2 # noqa: E501 OpenAPI spec version: 2.0.0 Contact: support@ultracart.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class OrderFormat(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'context': 'str', 'dont_link_email_to_search': 'bool', 'email_as_link': 'bool', 'filter_distribution_center_oid': 'int', 'filter_to_items_in_contact_oid': 'int', 'format': 'str', 'hide_bill_to_address': 'bool', 'hide_price_information': 'bool', 'link_file_attachments': 'bool', 'show_contact_info': 'bool', 'show_in_merchant_currency': 'bool', 'show_internal_information': 'bool', 'show_merchant_notes': 'bool', 'show_non_sensitive_payment_info': 'bool', 'show_payment_info': 'bool', 'translate': 'bool' } attribute_map = { 'context': 'context', 'dont_link_email_to_search': 'dont_link_email_to_search', 'email_as_link': 'email_as_link', 'filter_distribution_center_oid': 'filter_distribution_center_oid', 'filter_to_items_in_contact_oid': 'filter_to_items_in_contact_oid', 'format': 'format', 'hide_bill_to_address': 'hide_bill_to_address', 'hide_price_information': 'hide_price_information', 'link_file_attachments': 'link_file_attachments', 'show_contact_info': 'show_contact_info', 'show_in_merchant_currency': 'show_in_merchant_currency', 'show_internal_information': 'show_internal_information', 'show_merchant_notes': 'show_merchant_notes', 'show_non_sensitive_payment_info': 'show_non_sensitive_payment_info', 'show_payment_info': 'show_payment_info', 'translate': 'translate' } def __init__(self, context=None, dont_link_email_to_search=None, email_as_link=None, filter_distribution_center_oid=None, filter_to_items_in_contact_oid=None, format=None, hide_bill_to_address=None, hide_price_information=None, link_file_attachments=None, show_contact_info=None, show_in_merchant_currency=None, show_internal_information=None, show_merchant_notes=None, show_non_sensitive_payment_info=None, show_payment_info=None, translate=None): # noqa: E501 """OrderFormat - a model defined in Swagger""" # noqa: E501 self._context = None self._dont_link_email_to_search = None self._email_as_link = None self._filter_distribution_center_oid = None self._filter_to_items_in_contact_oid = None self._format = None self._hide_bill_to_address = None self._hide_price_information = None self._link_file_attachments = None self._show_contact_info = None self._show_in_merchant_currency = None self._show_internal_information = None self._show_merchant_notes = None self._show_non_sensitive_payment_info = None self._show_payment_info = None self._translate = None self.discriminator = None if context is not None: self.context = context if dont_link_email_to_search is not None: self.dont_link_email_to_search = dont_link_email_to_search if email_as_link is not None: self.email_as_link = email_as_link if filter_distribution_center_oid is not None: self.filter_distribution_center_oid = filter_distribution_center_oid if filter_to_items_in_contact_oid is not None: self.filter_to_items_in_contact_oid = filter_to_items_in_contact_oid if format is not None: self.format = format if hide_bill_to_address is not None: self.hide_bill_to_address = hide_bill_to_address if hide_price_information is not None: self.hide_price_information = hide_price_information if link_file_attachments is not None: self.link_file_attachments = link_file_attachments if show_contact_info is not None: self.show_contact_info = show_contact_info if show_in_merchant_currency is not None: self.show_in_merchant_currency = show_in_merchant_currency if show_internal_information is not None: self.show_internal_information = show_internal_information if show_merchant_notes is not None: self.show_merchant_notes = show_merchant_notes if show_non_sensitive_payment_info is not None: self.show_non_sensitive_payment_info = show_non_sensitive_payment_info if show_payment_info is not None: self.show_payment_info = show_payment_info if translate is not None: self.translate = translate @property def context(self): """Gets the context of this OrderFormat. # noqa: E501 The context to generate the order view for. # noqa: E501 :return: The context of this OrderFormat. # noqa: E501 :rtype: str """ return self._context @context.setter def context(self, context): """Sets the context of this OrderFormat. The context to generate the order view for. # noqa: E501 :param context: The context of this OrderFormat. # noqa: E501 :type: str """ self._context = context @property def dont_link_email_to_search(self): """Gets the dont_link_email_to_search of this OrderFormat. # noqa: E501 True to not link the email address to the order search # noqa: E501 :return: The dont_link_email_to_search of this OrderFormat. # noqa: E501 :rtype: bool """ return self._dont_link_email_to_search @dont_link_email_to_search.setter def dont_link_email_to_search(self, dont_link_email_to_search): """Sets the dont_link_email_to_search of this OrderFormat. True to not link the email address to the order search # noqa: E501 :param dont_link_email_to_search: The dont_link_email_to_search of this OrderFormat. # noqa: E501 :type: bool """ self._dont_link_email_to_search = dont_link_email_to_search @property def email_as_link(self): """Gets the email_as_link of this OrderFormat. # noqa: E501 True to make the email address a clickable mailto link # noqa: E501 :return: The email_as_link of this OrderFormat. # noqa: E501 :rtype: bool """ return self._email_as_link @email_as_link.setter def email_as_link(self, email_as_link): """Sets the email_as_link of this OrderFormat. True to make the email address a clickable mailto link # noqa: E501 :param email_as_link: The email_as_link of this OrderFormat. # noqa: E501 :type: bool """ self._email_as_link = email_as_link @property def filter_distribution_center_oid(self): """Gets the filter_distribution_center_oid of this OrderFormat. # noqa: E501 Specify a distribution center oid to filter the items displayed to that particular distribution center. # noqa: E501 :return: The filter_distribution_center_oid of this OrderFormat. # noqa: E501 :rtype: int """ return self._filter_distribution_center_oid @filter_distribution_center_oid.setter def filter_distribution_center_oid(self, filter_distribution_center_oid): """Sets the filter_distribution_center_oid of this OrderFormat. Specify a distribution center oid to filter the items displayed to that particular distribution center. # noqa: E501 :param filter_distribution_center_oid: The filter_distribution_center_oid of this OrderFormat. # noqa: E501 :type: int """ self._filter_distribution_center_oid = filter_distribution_center_oid @property def filter_to_items_in_contact_oid(self): """Gets the filter_to_items_in_contact_oid of this OrderFormat. # noqa: E501 The container oid to filter items to. # noqa: E501 :return: The filter_to_items_in_contact_oid of this OrderFormat. # noqa: E501 :rtype: int """ return self._filter_to_items_in_contact_oid @filter_to_items_in_contact_oid.setter def filter_to_items_in_contact_oid(self, filter_to_items_in_contact_oid): """Sets the filter_to_items_in_contact_oid of this OrderFormat. The container oid to filter items to. # noqa: E501 :param filter_to_items_in_contact_oid: The filter_to_items_in_contact_oid of this OrderFormat. # noqa: E501 :type: int """ self._filter_to_items_in_contact_oid = filter_to_items_in_contact_oid @property def format(self): """Gets the format of this OrderFormat. # noqa: E501 The desired format. # noqa: E501 :return: The format of this OrderFormat. # noqa: E501 :rtype: str """ return self._format @format.setter def format(self, format): """Sets the format of this OrderFormat. The desired format. # noqa: E501 :param format: The format of this OrderFormat. # noqa: E501 :type: str """ allowed_values = ["text", "div", "table", "email"] # noqa: E501 if format not in allowed_values: raise ValueError( "Invalid value for `format` ({0}), must be one of {1}" # noqa: E501 .format(format, allowed_values) ) self._format = format @property def hide_bill_to_address(self): """Gets the hide_bill_to_address of this OrderFormat. # noqa: E501 True to ide the bill to address # noqa: E501 :return: The hide_bill_to_address of this OrderFormat. # noqa: E501 :rtype: bool """ return self._hide_bill_to_address @hide_bill_to_address.setter def hide_bill_to_address(self, hide_bill_to_address): """Sets the hide_bill_to_address of this OrderFormat. True to ide the bill to address # noqa: E501 :param hide_bill_to_address: The hide_bill_to_address of this OrderFormat. # noqa: E501 :type: bool """ self._hide_bill_to_address = hide_bill_to_address @property def hide_price_information(self): """Gets the hide_price_information of this OrderFormat. # noqa: E501 True to hide price information # noqa: E501 :return: The hide_price_information of this OrderFormat. # noqa: E501 :rtype: bool """ return self._hide_price_information @hide_price_information.setter def hide_price_information(self, hide_price_information): """Sets the hide_price_information of this OrderFormat. True to hide price information # noqa: E501 :param hide_price_information: The hide_price_information of this OrderFormat. # noqa: E501 :type: bool """ self._hide_price_information = hide_price_information @property def link_file_attachments(self): """Gets the link_file_attachments of this OrderFormat. # noqa: E501 True to link file attachments for download # noqa: E501 :return: The link_file_attachments of this OrderFormat. # noqa: E501 :rtype: bool """ return self._link_file_attachments @link_file_attachments.setter def link_file_attachments(self, link_file_attachments): """Sets the link_file_attachments of this OrderFormat. True to link file attachments for download # noqa: E501 :param link_file_attachments: The link_file_attachments of this OrderFormat. # noqa: E501 :type: bool """ self._link_file_attachments = link_file_attachments @property def show_contact_info(self): """Gets the show_contact_info of this OrderFormat. # noqa: E501 True to show contact information # noqa: E501 :return: The show_contact_info of this OrderFormat. # noqa: E501 :rtype: bool """ return self._show_contact_info @show_contact_info.setter def show_contact_info(self, show_contact_info): """Sets the show_contact_info of this OrderFormat. True to show contact information # noqa: E501 :param show_contact_info: The show_contact_info of this OrderFormat. # noqa: E501 :type: bool """ self._show_contact_info = show_contact_info @property def show_in_merchant_currency(self): """Gets the show_in_merchant_currency of this OrderFormat. # noqa: E501 True to show the order in the merchant currency # noqa: E501 :return: The show_in_merchant_currency of this OrderFormat. # noqa: E501 :rtype: bool """ return self._show_in_merchant_currency @show_in_merchant_currency.setter def show_in_merchant_currency(self, show_in_merchant_currency): """Sets the show_in_merchant_currency of this OrderFormat. True to show the order in the merchant currency # noqa: E501 :param show_in_merchant_currency: The show_in_merchant_currency of this OrderFormat. # noqa: E501 :type: bool """ self._show_in_merchant_currency = show_in_merchant_currency @property def show_internal_information(self): """Gets the show_internal_information of this OrderFormat. # noqa: E501 True to show internal information about the order # noqa: E501 :return: The show_internal_information of this OrderFormat. # noqa: E501 :rtype: bool """ return self._show_internal_information @show_internal_information.setter def show_internal_information(self, show_internal_information): """Sets the show_internal_information of this OrderFormat. True to show internal information about the order # noqa: E501 :param show_internal_information: The show_internal_information of this OrderFormat. # noqa: E501 :type: bool """ self._show_internal_information = show_internal_information @property def show_merchant_notes(self): """Gets the show_merchant_notes of this OrderFormat. # noqa: E501 True to show merchant notes # noqa: E501 :return: The show_merchant_notes of this OrderFormat. # noqa: E501 :rtype: bool """ return self._show_merchant_notes @show_merchant_notes.setter def show_merchant_notes(self, show_merchant_notes): """Sets the show_merchant_notes of this OrderFormat. True to show merchant notes # noqa: E501 :param show_merchant_notes: The show_merchant_notes of this OrderFormat. # noqa: E501 :type: bool """ self._show_merchant_notes = show_merchant_notes @property def show_non_sensitive_payment_info(self): """Gets the show_non_sensitive_payment_info of this OrderFormat. # noqa: E501 True to show non-sensitive payment information # noqa: E501 :return: The show_non_sensitive_payment_info of this OrderFormat. # noqa: E501 :rtype: bool """ return self._show_non_sensitive_payment_info @show_non_sensitive_payment_info.setter def show_non_sensitive_payment_info(self, show_non_sensitive_payment_info): """Sets the show_non_sensitive_payment_info of this OrderFormat. True to show non-sensitive payment information # noqa: E501 :param show_non_sensitive_payment_info: The show_non_sensitive_payment_info of this OrderFormat. # noqa: E501 :type: bool """ self._show_non_sensitive_payment_info = show_non_sensitive_payment_info @property def show_payment_info(self): """Gets the show_payment_info of this OrderFormat. # noqa: E501 True to show payment information # noqa: E501 :return: The show_payment_info of this OrderFormat. # noqa: E501 :rtype: bool """ return self._show_payment_info @show_payment_info.setter def show_payment_info(self, show_payment_info): """Sets the show_payment_info of this OrderFormat. True to show payment information # noqa: E501 :param show_payment_info: The show_payment_info of this OrderFormat. # noqa: E501 :type: bool """ self._show_payment_info = show_payment_info @property def translate(self): """Gets the translate of this OrderFormat. # noqa: E501 True to translate the order into the native language of the customer # noqa: E501 :return: The translate of this OrderFormat. # noqa: E501 :rtype: bool """ return self._translate @translate.setter def translate(self, translate): """Sets the translate of this OrderFormat. True to translate the order into the native language of the customer # noqa: E501 :param translate: The translate of this OrderFormat. # noqa: E501 :type: bool """ self._translate = translate def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(OrderFormat, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, OrderFormat): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
35.158088
466
0.664645
import pprint import re import six class OrderFormat(object): swagger_types = { 'context': 'str', 'dont_link_email_to_search': 'bool', 'email_as_link': 'bool', 'filter_distribution_center_oid': 'int', 'filter_to_items_in_contact_oid': 'int', 'format': 'str', 'hide_bill_to_address': 'bool', 'hide_price_information': 'bool', 'link_file_attachments': 'bool', 'show_contact_info': 'bool', 'show_in_merchant_currency': 'bool', 'show_internal_information': 'bool', 'show_merchant_notes': 'bool', 'show_non_sensitive_payment_info': 'bool', 'show_payment_info': 'bool', 'translate': 'bool' } attribute_map = { 'context': 'context', 'dont_link_email_to_search': 'dont_link_email_to_search', 'email_as_link': 'email_as_link', 'filter_distribution_center_oid': 'filter_distribution_center_oid', 'filter_to_items_in_contact_oid': 'filter_to_items_in_contact_oid', 'format': 'format', 'hide_bill_to_address': 'hide_bill_to_address', 'hide_price_information': 'hide_price_information', 'link_file_attachments': 'link_file_attachments', 'show_contact_info': 'show_contact_info', 'show_in_merchant_currency': 'show_in_merchant_currency', 'show_internal_information': 'show_internal_information', 'show_merchant_notes': 'show_merchant_notes', 'show_non_sensitive_payment_info': 'show_non_sensitive_payment_info', 'show_payment_info': 'show_payment_info', 'translate': 'translate' } def __init__(self, context=None, dont_link_email_to_search=None, email_as_link=None, filter_distribution_center_oid=None, filter_to_items_in_contact_oid=None, format=None, hide_bill_to_address=None, hide_price_information=None, link_file_attachments=None, show_contact_info=None, show_in_merchant_currency=None, show_internal_information=None, show_merchant_notes=None, show_non_sensitive_payment_info=None, show_payment_info=None, translate=None): self._context = None self._dont_link_email_to_search = None self._email_as_link = None self._filter_distribution_center_oid = None self._filter_to_items_in_contact_oid = None self._format = None self._hide_bill_to_address = None self._hide_price_information = None self._link_file_attachments = None self._show_contact_info = None self._show_in_merchant_currency = None self._show_internal_information = None self._show_merchant_notes = None self._show_non_sensitive_payment_info = None self._show_payment_info = None self._translate = None self.discriminator = None if context is not None: self.context = context if dont_link_email_to_search is not None: self.dont_link_email_to_search = dont_link_email_to_search if email_as_link is not None: self.email_as_link = email_as_link if filter_distribution_center_oid is not None: self.filter_distribution_center_oid = filter_distribution_center_oid if filter_to_items_in_contact_oid is not None: self.filter_to_items_in_contact_oid = filter_to_items_in_contact_oid if format is not None: self.format = format if hide_bill_to_address is not None: self.hide_bill_to_address = hide_bill_to_address if hide_price_information is not None: self.hide_price_information = hide_price_information if link_file_attachments is not None: self.link_file_attachments = link_file_attachments if show_contact_info is not None: self.show_contact_info = show_contact_info if show_in_merchant_currency is not None: self.show_in_merchant_currency = show_in_merchant_currency if show_internal_information is not None: self.show_internal_information = show_internal_information if show_merchant_notes is not None: self.show_merchant_notes = show_merchant_notes if show_non_sensitive_payment_info is not None: self.show_non_sensitive_payment_info = show_non_sensitive_payment_info if show_payment_info is not None: self.show_payment_info = show_payment_info if translate is not None: self.translate = translate @property def context(self): return self._context @context.setter def context(self, context): self._context = context @property def dont_link_email_to_search(self): return self._dont_link_email_to_search @dont_link_email_to_search.setter def dont_link_email_to_search(self, dont_link_email_to_search): self._dont_link_email_to_search = dont_link_email_to_search @property def email_as_link(self): return self._email_as_link @email_as_link.setter def email_as_link(self, email_as_link): self._email_as_link = email_as_link @property def filter_distribution_center_oid(self): return self._filter_distribution_center_oid @filter_distribution_center_oid.setter def filter_distribution_center_oid(self, filter_distribution_center_oid): self._filter_distribution_center_oid = filter_distribution_center_oid @property def filter_to_items_in_contact_oid(self): return self._filter_to_items_in_contact_oid @filter_to_items_in_contact_oid.setter def filter_to_items_in_contact_oid(self, filter_to_items_in_contact_oid): self._filter_to_items_in_contact_oid = filter_to_items_in_contact_oid @property def format(self): return self._format @format.setter def format(self, format): allowed_values = ["text", "div", "table", "email"] if format not in allowed_values: raise ValueError( "Invalid value for `format` ({0}), must be one of {1}" .format(format, allowed_values) ) self._format = format @property def hide_bill_to_address(self): return self._hide_bill_to_address @hide_bill_to_address.setter def hide_bill_to_address(self, hide_bill_to_address): self._hide_bill_to_address = hide_bill_to_address @property def hide_price_information(self): return self._hide_price_information @hide_price_information.setter def hide_price_information(self, hide_price_information): self._hide_price_information = hide_price_information @property def link_file_attachments(self): return self._link_file_attachments @link_file_attachments.setter def link_file_attachments(self, link_file_attachments): self._link_file_attachments = link_file_attachments @property def show_contact_info(self): return self._show_contact_info @show_contact_info.setter def show_contact_info(self, show_contact_info): self._show_contact_info = show_contact_info @property def show_in_merchant_currency(self): return self._show_in_merchant_currency @show_in_merchant_currency.setter def show_in_merchant_currency(self, show_in_merchant_currency): self._show_in_merchant_currency = show_in_merchant_currency @property def show_internal_information(self): return self._show_internal_information @show_internal_information.setter def show_internal_information(self, show_internal_information): self._show_internal_information = show_internal_information @property def show_merchant_notes(self): return self._show_merchant_notes @show_merchant_notes.setter def show_merchant_notes(self, show_merchant_notes): self._show_merchant_notes = show_merchant_notes @property def show_non_sensitive_payment_info(self): return self._show_non_sensitive_payment_info @show_non_sensitive_payment_info.setter def show_non_sensitive_payment_info(self, show_non_sensitive_payment_info): self._show_non_sensitive_payment_info = show_non_sensitive_payment_info @property def show_payment_info(self): return self._show_payment_info @show_payment_info.setter def show_payment_info(self, show_payment_info): self._show_payment_info = show_payment_info @property def translate(self): return self._translate @translate.setter def translate(self, translate): self._translate = translate def to_dict(self): result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(OrderFormat, dict): for key, value in self.items(): result[key] = value return result def to_str(self): return pprint.pformat(self.to_dict()) def __repr__(self): return self.to_str() def __eq__(self, other): if not isinstance(other, OrderFormat): return False return self.__dict__ == other.__dict__ def __ne__(self, other): return not self == other
true
true
f725bbab055480c19d9e0e8d0883d64f3353823b
666
py
Python
circle_and_dock.py
skullydazed/PyRoombaAdapter
88824e91b0f0cec008b16cfaa5a62a6546f1226e
[ "MIT" ]
null
null
null
circle_and_dock.py
skullydazed/PyRoombaAdapter
88824e91b0f0cec008b16cfaa5a62a6546f1226e
[ "MIT" ]
null
null
null
circle_and_dock.py
skullydazed/PyRoombaAdapter
88824e91b0f0cec008b16cfaa5a62a6546f1226e
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 """ Pull forward a few cm, spin around, dock. """ from math import radians from time import sleep from pyroombaadapter import PyRoombaAdapter PORT = "/dev/ttyUSB0" adapter = PyRoombaAdapter(PORT) adapter.change_mode_to_safe() # Warn people we're coming adapter.send_song_cmd(0, 9, [69, 69, 69, 65, 72, 69, 65, 72, 69], [40, 40, 40, 30, 10, 40, 30, 10, 80]) adapter.send_play_cmd(0) sleep(5.0) # Move forward adapter.move(-0.2, 32768) sleep(4) adapter.move(0, 0) # Spin left and right adapter.move(0, -1) sleep(2) adapter.move(0, 1) sleep(2) adapter.move(0, 0) # Dock adapter.start_seek_dock()
19.028571
59
0.660661
from math import radians from time import sleep from pyroombaadapter import PyRoombaAdapter PORT = "/dev/ttyUSB0" adapter = PyRoombaAdapter(PORT) adapter.change_mode_to_safe() adapter.send_song_cmd(0, 9, [69, 69, 69, 65, 72, 69, 65, 72, 69], [40, 40, 40, 30, 10, 40, 30, 10, 80]) adapter.send_play_cmd(0) sleep(5.0) # Move forward adapter.move(-0.2, 32768) sleep(4) adapter.move(0, 0) # Spin left and right adapter.move(0, -1) sleep(2) adapter.move(0, 1) sleep(2) adapter.move(0, 0) # Dock adapter.start_seek_dock()
true
true
f725bde4462ccc899cd0ce48915de444be82f7e8
21,890
py
Python
source/graph_3D_surface.py
yux1991/PyRHEED
b39ad03651c92e3649069919ae48b1e5158cd3dd
[ "MIT" ]
14
2019-01-08T14:32:31.000Z
2021-11-17T21:07:10.000Z
source/graph_3D_surface.py
yux1991/PyRHEED
b39ad03651c92e3649069919ae48b1e5158cd3dd
[ "MIT" ]
2
2019-05-14T08:56:36.000Z
2020-12-22T16:44:30.000Z
source/graph_3D_surface.py
yux1991/PyRHEED
b39ad03651c92e3649069919ae48b1e5158cd3dd
[ "MIT" ]
4
2019-03-12T20:03:54.000Z
2022-03-08T14:24:46.000Z
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar from PyQt5 import QtCore, QtGui, QtWidgets, QtDataVisualization import math import matplotlib.pyplot as plt import numpy as np import os import pandas as pd class Graph(QtWidgets.QWidget): SHOW_2D_CONTOUR_SIGNAL = QtCore.pyqtSignal(str,bool,float,float,float,float,int,str) def __init__(self): super(Graph,self).__init__() def run_3D_graph(self,path): self.graphPath = path self.graph = SurfaceGraph() self.container = QtWidgets.QWidget.createWindowContainer(self.graph) self.screenSize = self.graph.screen().size() self.container.setMinimumSize(self.screenSize.width()/2, self.screenSize.height()/2) self.container.setMaximumSize(self.screenSize) self.container.setSizePolicy(QtWidgets.QSizePolicy.Expanding,QtWidgets.QSizePolicy.Expanding) self.container.setFocusPolicy(QtCore.Qt.StrongFocus) self.mainVLayout = QtWidgets.QVBoxLayout(self) self.hLayout = QtWidgets.QHBoxLayout() self.vLayout = QtWidgets.QVBoxLayout() self.hLayout.addWidget(self.container,1) self.vLayout.setAlignment(QtCore.Qt.AlignTop) self.hLayout.addLayout(self.vLayout) self.mainVLayout.addLayout(self.hLayout) self.setWindowTitle("3D Surface") self.setWindowModality(QtCore.Qt.WindowModal) self.chooseGraph = QtWidgets.QGroupBox("Choose Graph") self.chooseGraph.setStyleSheet('QGroupBox::title {color:blue;}') self.chooseGraphGrid = QtWidgets.QGridLayout(self.chooseGraph) self.chooseSourceLabel = QtWidgets.QLabel("The path of the graph is:\n"+self.graphPath) self.chooseSourceLabel.setAlignment(QtCore.Qt.AlignTop) self.chooseSourceLabel.setFixedWidth(250) self.chooseSourceLabel.setFixedHeight(75) self.chooseSourceLabel.setWordWrap(True) self.chooseSourceButton = QtWidgets.QPushButton("Browse") self.chooseSourceButton.clicked.connect(self.choose_graph) self.chooseGraphGrid.addWidget(self.chooseSourceLabel,0,0) self.chooseGraphGrid.addWidget(self.chooseSourceButton,1,0) self.plotOptions = QtWidgets.QGroupBox("Contour Plot Options") self.plotOptions.setStyleSheet('QGroupBox::title {color:blue;}') self.plotOptionsVBox = QtWidgets.QVBoxLayout(self.plotOptions) self.plotOptionsGrid = QtWidgets.QGridLayout() self.colormapLabel = QtWidgets.QLabel("Colormap") self.colormap = QtWidgets.QComboBox() self.colormap.addItem("jet","jet") self.colormap.addItem("hsv","hsv") self.colormap.addItem("rainbow","rainbow") self.colormap.addItem("nipy_spectral","nipy_spectral") self.levelMinLabel = QtWidgets.QLabel("Level Min ({})".format(0.0)) self.levelMinSlider = QtWidgets.QSlider(QtCore.Qt.Horizontal) self.levelMinSlider.setMinimum(0) self.levelMinSlider.setMaximum(100) self.levelMinSlider.setValue(0) self.levelMinSlider.valueChanged.connect(self.refresh_level_min) self.levelMaxLabel = QtWidgets.QLabel("Level Max ({})".format(1.0)) self.levelMaxSlider = QtWidgets.QSlider(QtCore.Qt.Horizontal) self.levelMaxSlider.setMinimum(0) self.levelMaxSlider.setMaximum(100) self.levelMaxSlider.setValue(100) self.levelMaxSlider.valueChanged.connect(self.refresh_level_max) self.radiusMinLabel = QtWidgets.QLabel("Radius Min ({})".format(0.0)) self.radiusMinSlider = QtWidgets.QSlider(QtCore.Qt.Horizontal) self.radiusMinSlider.setMinimum(0) self.radiusMinSlider.setMaximum(1000) self.radiusMinSlider.setValue(0) self.radiusMinSlider.valueChanged.connect(self.refresh_radius_min) self.radiusMaxLabel = QtWidgets.QLabel("Radius Max ({})".format(10.0)) self.radiusMaxSlider = QtWidgets.QSlider(QtCore.Qt.Horizontal) self.radiusMaxSlider.setMinimum(0) self.radiusMaxSlider.setMaximum(1000) self.radiusMaxSlider.setValue(1000) self.radiusMaxSlider.valueChanged.connect(self.refresh_radius_max) self.numberOfContourLevelsLabel = QtWidgets.QLabel("Number of Contour Levels ({})".format(50)) self.numberOfContourLevelsLabel.setFixedWidth(160) self.numberOfContourLevelsSlider = QtWidgets.QSlider(QtCore.Qt.Horizontal) self.numberOfContourLevelsSlider.setMinimum(5) self.numberOfContourLevelsSlider.setMaximum(100) self.numberOfContourLevelsSlider.setValue(50) self.numberOfContourLevelsSlider.valueChanged.connect(self.refresh_number_of_contour_levels) self.show2DContourButton = QtWidgets.QPushButton("Show 2D Contour") self.show2DContourButton.clicked.connect(self.show_2D_contour_button_pressed) self.show2DContourButton.setEnabled(False) self.plotOptionsGrid.addWidget(self.colormapLabel,0,0) self.plotOptionsGrid.addWidget(self.colormap,0,1) self.plotOptionsGrid.addWidget(self.levelMinLabel,1,0) self.plotOptionsGrid.addWidget(self.levelMinSlider,1,1) self.plotOptionsGrid.addWidget(self.levelMaxLabel,2,0) self.plotOptionsGrid.addWidget(self.levelMaxSlider,2,1) self.plotOptionsGrid.addWidget(self.radiusMinLabel,3,0) self.plotOptionsGrid.addWidget(self.radiusMinSlider,3,1) self.plotOptionsGrid.addWidget(self.radiusMaxLabel,4,0) self.plotOptionsGrid.addWidget(self.radiusMaxSlider,4,1) self.plotOptionsGrid.addWidget(self.numberOfContourLevelsLabel,5,0) self.plotOptionsGrid.addWidget(self.numberOfContourLevelsSlider,5,1) self.plotOptionsVBox.addLayout(self.plotOptionsGrid) self.plotOptionsVBox.addWidget(self.show2DContourButton) self.themeList = QtWidgets.QComboBox(self) self.themeList.addItem("Qt") self.themeList.addItem("Primary Colors") self.themeList.addItem("Digia") self.themeList.addItem("Stone Moss") self.themeList.addItem("Army Blue") self.themeList.addItem("Retro") self.themeList.addItem("Ebony") self.themeList.addItem("Isabelle") self.colorGroupBox = QtWidgets.QGroupBox("3D Surface Colormap") self.colorGroupBox.setStyleSheet('QGroupBox::title {color:blue;}') self.grBtoY = QtGui.QLinearGradient(0,0,1,100) self.grBtoY.setColorAt(1.0,QtCore.Qt.black) self.grBtoY.setColorAt(0.67,QtCore.Qt.blue) self.grBtoY.setColorAt(0.33,QtCore.Qt.red) self.grBtoY.setColorAt(0.0,QtCore.Qt.yellow) self.pm = QtGui.QPixmap(50,100) self.pmp = QtGui.QPainter(self.pm) self.pmp.setBrush(QtGui.QBrush(self.grBtoY)) self.pmp.setPen(QtCore.Qt.NoPen) self.pmp.drawRect(0,0,50,100) self.pmp.end() self.gradientBtoYPB = QtWidgets.QPushButton(self) self.gradientBtoYPB.setIcon(QtGui.QIcon(self.pm)) self.gradientBtoYPB.setIconSize(QtCore.QSize(50,100)) self.gradientBtoYPB.setEnabled(False) self.grGtoR = QtGui.QLinearGradient(0,0,1,100) self.grGtoR.setColorAt(1.0,QtCore.Qt.darkGreen) self.grGtoR.setColorAt(0.5,QtCore.Qt.yellow) self.grGtoR.setColorAt(0.2,QtCore.Qt.red) self.grGtoR.setColorAt(0.0,QtCore.Qt.darkRed) self.pm2 = QtGui.QPixmap(50,100) self.pmp2 = QtGui.QPainter(self.pm2) self.pmp2.setBrush(QtGui.QBrush(self.grGtoR)) self.pmp2.drawRect(0,0,50,100) self.pmp2.end() self.gradientGtoRPB = QtWidgets.QPushButton(self) self.gradientGtoRPB.setIcon(QtGui.QIcon(self.pm2)) self.gradientGtoRPB.setIconSize(QtCore.QSize(50,100)) self.gradientGtoRPB.setEnabled(False) self.grBtoR = QtGui.QLinearGradient(0,0,1,100) self.grBtoR.setColorAt(1.0, QtCore.Qt.darkBlue) self.grBtoR.setColorAt(0.95, QtCore.Qt.blue) self.grBtoR.setColorAt(0.9, QtCore.Qt.darkCyan) self.grBtoR.setColorAt(0.8, QtCore.Qt.cyan) self.grBtoR.setColorAt(0.6, QtCore.Qt.green) self.grBtoR.setColorAt(0.2, QtCore.Qt.yellow) self.grBtoR.setColorAt(0.0, QtCore.Qt.red) self.pm3 = QtGui.QPixmap(50,100) self.pmp3 = QtGui.QPainter(self.pm3) self.pmp3.setBrush(QtGui.QBrush(self.grBtoR)) self.pmp3.drawRect(0,0,50,100) self.pmp3.end() self.gradientBtoRPB = QtWidgets.QPushButton(self) self.gradientBtoRPB.setIcon(QtGui.QIcon(self.pm3)) self.gradientBtoRPB.setIconSize(QtCore.QSize(50,100)) self.gradientBtoRPB.setEnabled(False) self.colorHBox = QtWidgets.QHBoxLayout() self.colorHBox.addWidget(self.gradientBtoYPB) self.colorHBox.addWidget(self.gradientGtoRPB) self.colorHBox.addWidget(self.gradientBtoRPB) self.colorGroupBox.setLayout(self.colorHBox) self.statusBar = QtWidgets.QGroupBox("Log") self.statusBar.setStyleSheet('QGroupBox::title {color:blue;}') self.statusGrid = QtWidgets.QGridLayout(self.statusBar) self.statusBar.setFixedHeight(150) self.statusBar.setSizePolicy(QtWidgets.QSizePolicy.Expanding,QtWidgets.QSizePolicy.Fixed) self.logBox = QtWidgets.QTextEdit(QtCore.QTime.currentTime().toString("hh:mm:ss")+ \ "\u00A0\u00A0\u00A0\u00A0Initialized!") self.logCursor = QtGui.QTextCursor(self.logBox.document()) self.logCursor.movePosition(QtGui.QTextCursor.End) self.logBox.setTextCursor(self.logCursor) self.logBox.ensureCursorVisible() self.logBox.setAlignment(QtCore.Qt.AlignTop) self.logBox.setFrameShape(QtWidgets.QFrame.NoFrame) self.logBoxScroll = QtWidgets.QScrollArea() self.logBoxScroll.setWidget(self.logBox) self.logBoxScroll.setWidgetResizable(True) self.logBoxScroll.setFrameShape(QtWidgets.QFrame.NoFrame) self.statusGrid.addWidget(self.logBoxScroll,0,0) self.vLayout.addWidget(self.chooseGraph) self.vLayout.addWidget(self.plotOptions) themeLabel = QtWidgets.QLabel("Theme") themeLabel.setStyleSheet("QLabel {color:blue;}") self.vLayout.addWidget(themeLabel) self.vLayout.addWidget(self.themeList) self.vLayout.addWidget(self.colorGroupBox) self.mainVLayout.addWidget(self.statusBar) self.show() desktopRect = QtWidgets.QApplication.desktop().availableGeometry(self) center = desktopRect.center() self.move(center.x()-self.width()*0.5,center.y()-self.height()*0.5) self.themeList.currentIndexChanged.connect(self.graph.change_theme) self.gradientBtoYPB.pressed.connect(self.graph.set_black_to_yellow_gradient) self.gradientGtoRPB.pressed.connect(self.graph.set_green_to_red_gradient) self.gradientBtoRPB.pressed.connect(self.graph.set_blue_to_red_gradient) self.SHOW_2D_CONTOUR_SIGNAL.connect(self.show_2d_contour) self.graph.LOG_MESSAGE.connect(self.update_log) self.themeList.setCurrentIndex(3) if not path=='': self.graph.fill_two_dimensional_mapping_proxy(path) self.graph.enable_two_dimensional_mapping_model(True) self.show2DContourButton.setEnabled(True) self.gradientBtoYPB.setEnabled(True) self.gradientGtoRPB.setEnabled(True) self.gradientBtoRPB.setEnabled(True) def choose_graph(self): path = QtWidgets.QFileDialog.getOpenFileName(None,"choose the graph",self.graphPath) self.graphPath = path[0] self.graphPathExtension = os.path.splitext(self.graphPath)[1] if not self.graphPathExtension == ".txt": self.raise_error('[Error: wrong file type] Please choose a *.txt file') self.update_log('[Error: wrong file type] Please choose a *.txt file') else: self.chooseSourceLabel.setText("The path of the graph is:\n"+self.graphPath) self.update_log("Loading DataArray...") QtCore.QCoreApplication.processEvents() self.graph.fill_two_dimensional_mapping_proxy(self.graphPath) self.graph.enable_two_dimensional_mapping_model(True) self.show2DContourButton.setEnabled(True) self.gradientBtoYPB.setEnabled(True) self.gradientGtoRPB.setEnabled(True) self.gradientBtoRPB.setEnabled(True) def refresh_level_min(self): self.levelMinLabel.setText("Level Min ({})".format(self.levelMinSlider.value()/100)) if self.levelMinSlider.value() > self.levelMaxSlider.value(): self.levelMaxSlider.setValue(self.levelMinSlider.value()) def refresh_level_max(self): self.levelMaxLabel.setText("Level Max ({})".format(self.levelMaxSlider.value()/100)) if self.levelMinSlider.value() > self.levelMaxSlider.value(): self.levelMinSlider.setValue(self.levelMaxSlider.value()) def refresh_radius_min(self): self.radiusMinLabel.setText("Radius Min ({})".format(self.radiusMinSlider.value()/100)) if self.radiusMinSlider.value() > self.radiusMaxSlider.value(): self.radiusMaxSlider.setValue(self.radiusMinSlider.value()) def refresh_radius_max(self): self.radiusMaxLabel.setText("Radius Max ({})".format(self.radiusMaxSlider.value()/100)) if self.radiusMinSlider.value() > self.radiusMaxSlider.value(): self.radiusMinSlider.setValue(self.radiusMaxSlider.value()) def refresh_number_of_contour_levels(self): self.numberOfContourLevelsLabel.setText("Number of Contour Levels ({})".format(self.numberOfContourLevelsSlider.value())) def show_2D_contour_button_pressed(self): self.update_log("Showing contour plot...") QtCore.QCoreApplication.processEvents() self.SHOW_2D_CONTOUR_SIGNAL.emit(self.graphPath,True,self.levelMinSlider.value()/100,self.levelMaxSlider.value()/100,\ self.radiusMinSlider.value()/100,self.radiusMaxSlider.value()/100,\ self.numberOfContourLevelsSlider.value(),self.colormap.currentText()) def show_2d_contour(self,path, insideGraph3D = False, min=0.0, max=1.0, radius_min=0, radius_max=10, number_of_levels=50, colormap='jet'): window = QtWidgets.QDialog() layout = QtWidgets.QVBoxLayout(window) figure = plt.figure() canvas = FigureCanvas(figure) toolbar = NavigationToolbar(canvas,window) figure.clear() if not path == None: if os.path.splitext(path)[1] == '.txt': radius,theta,intensity = self.convert_to_RTI(path) levels = np.linspace(min,max,number_of_levels) ax = figure.add_subplot(111,polar = True) ax.contourf(theta,radius,intensity,levels=levels,cmap=colormap) ax.set_ylim(radius_min,radius_max) canvas.draw() else: self.raise_error('[Error: wrong file type] Please choose a *.txt file') else: self.raise_error('[Error: no file] Please choose a valid file first') layout.addWidget(toolbar) layout.addWidget(canvas) window.setWindowTitle("2D Contour") window.show() if insideGraph3D: window.finished.connect(self.contour_plot_finished) def contour_plot_finished(self): self.update_log('Contour plot ended.') def update_log(self,msg): self.logBox.append(QtCore.QTime.currentTime().toString("hh:mm:ss")+"\u00A0\u00A0\u00A0\u00A0"+msg) def convert_to_RTI(self,path): raw_data = np.loadtxt(path) if np.amin(raw_data[:,0])<0: data = np.empty(raw_data.shape) data[:,0] = np.abs(raw_data[:,0]) data[:,1] = np.where(raw_data[:,0]>0,0,180)+raw_data[:,1] data[:,2] = raw_data[:,2] else: data = raw_data df = pd.DataFrame(data,columns = ['radius','theta','intensity']) table = df.pivot_table(values = 'intensity',index='radius',columns='theta') return table.index.tolist(),[a/180*math.pi for a in table.columns.tolist()],table def raise_error(self,message): msg = QtWidgets.QMessageBox() msg.setIcon(QtWidgets.QMessageBox.Warning) msg.setText(message) msg.setWindowTitle("Error") msg.setStandardButtons(QtWidgets.QMessageBox.Ok) msg.setEscapeButton(QtWidgets.QMessageBox.Close) msg.exec() def raise_attention(self,information): info = QtWidgets.QMessageBox() info.setIcon(QtWidgets.QMessageBox.Information) info.setText(information) info.setWindowTitle("Information") info.setStandardButtons(QtWidgets.QMessageBox.Ok) info.setEscapeButton(QtWidgets.QMessageBox.Close) info.exec() class SurfaceGraph(QtDataVisualization.Q3DSurface): LOG_MESSAGE = QtCore.pyqtSignal(str) def __init__(self): super(SurfaceGraph,self).__init__() self.twoDimensionalMappingProxy = QtDataVisualization.QSurfaceDataProxy() self.twoDimensionalMappingSeries = QtDataVisualization.QSurface3DSeries(self.twoDimensionalMappingProxy) def convert_to_data_array(self,path): data = np.loadtxt(path) df = pd.DataFrame(data,columns = ['radius','theta','intensity']) table = df.pivot_table(values = 'intensity',index='radius',columns='theta') radius = table.index.tolist() theta = table.columns.tolist() self.sampleMin,self.sampleMax = -max(radius),max(radius) dataArray = [] for i in range(table.shape[0]): newRow=[] for j in range(table.shape[1]): item = QtDataVisualization.QSurfaceDataItem() X,Y,Z = radius[i]*np.cos(theta[j]/180*math.pi),\ radius[i]*np.sin(theta[j]/180*math.pi),\ table.loc[radius[i],theta[j]] item.setPosition(QtGui.QVector3D(X,Z,Y)) newRow.append(item) dataArray.append(newRow) return dataArray def fill_two_dimensional_mapping_proxy(self,path): dataArray = self.convert_to_data_array(path) self.twoDimensionalMappingProxy.resetArray(dataArray) self.LOG_MESSAGE.emit("DataArray Loaded!") def enable_two_dimensional_mapping_model(self,enable): if enable: for series in self.seriesList(): self.removeSeries(series) self.twoDimensionalMappingSeries.setDrawMode(QtDataVisualization.QSurface3DSeries.DrawSurface) self.twoDimensionalMappingSeries.setFlatShadingEnabled(True) self.axisX().setLabelFormat("%.2f") self.axisZ().setLabelFormat("%.2f") self.axisX().setRange(self.sampleMin,self.sampleMax) self.axisY().setRange(0,1) self.axisZ().setRange(self.sampleMin,self.sampleMax) self.axisX().setTitle("Kx (\u212B\u207B\u00B9)") self.axisX().setTitleVisible(True) self.axisZ().setTitle("Ky (\u212B\u207B\u00B9)") self.axisZ().setTitleVisible(True) self.axisY().setTitle("Normalized Intensity (arb. units)") self.axisY().setTitleVisible(True) self.axisX().setLabelAutoRotation(30) self.axisY().setLabelAutoRotation(90) self.axisZ().setLabelAutoRotation(30) self.addSeries(self.twoDimensionalMappingSeries) def change_theme(self, theme): self.activeTheme().setType(QtDataVisualization.Q3DTheme.Theme(theme)) def set_black_to_yellow_gradient(self): self.gr = QtGui.QLinearGradient() self.gr.setColorAt(0.0, QtCore.Qt.black) self.gr.setColorAt(0.33, QtCore.Qt.blue) self.gr.setColorAt(0.67, QtCore.Qt.red) self.gr.setColorAt(1.0, QtCore.Qt.yellow) self.seriesList()[0].setBaseGradient(self.gr) self.seriesList()[0].setColorStyle(QtDataVisualization.Q3DTheme.ColorStyleRangeGradient) def set_green_to_red_gradient(self): self.gr = QtGui.QLinearGradient() self.gr.setColorAt(0.0, QtCore.Qt.darkGreen) self.gr.setColorAt(0.5, QtCore.Qt.yellow) self.gr.setColorAt(0.8, QtCore.Qt.red) self.gr.setColorAt(1.0, QtCore.Qt.darkRed) self.seriesList()[0].setBaseGradient(self.gr) self.seriesList()[0].setColorStyle(QtDataVisualization.Q3DTheme.ColorStyleRangeGradient) def set_blue_to_red_gradient(self): self.gr = QtGui.QLinearGradient() self.gr.setColorAt(0.0, QtCore.Qt.darkBlue) self.gr.setColorAt(0.05, QtCore.Qt.blue) self.gr.setColorAt(0.1, QtCore.Qt.darkCyan) self.gr.setColorAt(0.2, QtCore.Qt.cyan) self.gr.setColorAt(0.4, QtCore.Qt.green) self.gr.setColorAt(0.8, QtCore.Qt.yellow) self.gr.setColorAt(1.0, QtCore.Qt.red) self.seriesList()[0].setBaseGradient(self.gr) self.seriesList()[0].setColorStyle(QtDataVisualization.Q3DTheme.ColorStyleRangeGradient) def raise_error(self,message): msg = QtWidgets.QMessageBox() msg.setIcon(QtWidgets.QMessageBox.Warning) msg.setText(message) msg.setWindowTitle("Error") msg.setStandardButtons(QtWidgets.QMessageBox.Ok) msg.setEscapeButton(QtWidgets.QMessageBox.Close) msg.exec() def raise_attention(self,information): info = QtWidgets.QMessageBox() info.setIcon(QtWidgets.QMessageBox.Information) info.setText(information) info.setWindowTitle("Information") info.setStandardButtons(QtWidgets.QMessageBox.Ok) info.setEscapeButton(QtWidgets.QMessageBox.Close) info.exec()
49.301802
142
0.685381
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar from PyQt5 import QtCore, QtGui, QtWidgets, QtDataVisualization import math import matplotlib.pyplot as plt import numpy as np import os import pandas as pd class Graph(QtWidgets.QWidget): SHOW_2D_CONTOUR_SIGNAL = QtCore.pyqtSignal(str,bool,float,float,float,float,int,str) def __init__(self): super(Graph,self).__init__() def run_3D_graph(self,path): self.graphPath = path self.graph = SurfaceGraph() self.container = QtWidgets.QWidget.createWindowContainer(self.graph) self.screenSize = self.graph.screen().size() self.container.setMinimumSize(self.screenSize.width()/2, self.screenSize.height()/2) self.container.setMaximumSize(self.screenSize) self.container.setSizePolicy(QtWidgets.QSizePolicy.Expanding,QtWidgets.QSizePolicy.Expanding) self.container.setFocusPolicy(QtCore.Qt.StrongFocus) self.mainVLayout = QtWidgets.QVBoxLayout(self) self.hLayout = QtWidgets.QHBoxLayout() self.vLayout = QtWidgets.QVBoxLayout() self.hLayout.addWidget(self.container,1) self.vLayout.setAlignment(QtCore.Qt.AlignTop) self.hLayout.addLayout(self.vLayout) self.mainVLayout.addLayout(self.hLayout) self.setWindowTitle("3D Surface") self.setWindowModality(QtCore.Qt.WindowModal) self.chooseGraph = QtWidgets.QGroupBox("Choose Graph") self.chooseGraph.setStyleSheet('QGroupBox::title {color:blue;}') self.chooseGraphGrid = QtWidgets.QGridLayout(self.chooseGraph) self.chooseSourceLabel = QtWidgets.QLabel("The path of the graph is:\n"+self.graphPath) self.chooseSourceLabel.setAlignment(QtCore.Qt.AlignTop) self.chooseSourceLabel.setFixedWidth(250) self.chooseSourceLabel.setFixedHeight(75) self.chooseSourceLabel.setWordWrap(True) self.chooseSourceButton = QtWidgets.QPushButton("Browse") self.chooseSourceButton.clicked.connect(self.choose_graph) self.chooseGraphGrid.addWidget(self.chooseSourceLabel,0,0) self.chooseGraphGrid.addWidget(self.chooseSourceButton,1,0) self.plotOptions = QtWidgets.QGroupBox("Contour Plot Options") self.plotOptions.setStyleSheet('QGroupBox::title {color:blue;}') self.plotOptionsVBox = QtWidgets.QVBoxLayout(self.plotOptions) self.plotOptionsGrid = QtWidgets.QGridLayout() self.colormapLabel = QtWidgets.QLabel("Colormap") self.colormap = QtWidgets.QComboBox() self.colormap.addItem("jet","jet") self.colormap.addItem("hsv","hsv") self.colormap.addItem("rainbow","rainbow") self.colormap.addItem("nipy_spectral","nipy_spectral") self.levelMinLabel = QtWidgets.QLabel("Level Min ({})".format(0.0)) self.levelMinSlider = QtWidgets.QSlider(QtCore.Qt.Horizontal) self.levelMinSlider.setMinimum(0) self.levelMinSlider.setMaximum(100) self.levelMinSlider.setValue(0) self.levelMinSlider.valueChanged.connect(self.refresh_level_min) self.levelMaxLabel = QtWidgets.QLabel("Level Max ({})".format(1.0)) self.levelMaxSlider = QtWidgets.QSlider(QtCore.Qt.Horizontal) self.levelMaxSlider.setMinimum(0) self.levelMaxSlider.setMaximum(100) self.levelMaxSlider.setValue(100) self.levelMaxSlider.valueChanged.connect(self.refresh_level_max) self.radiusMinLabel = QtWidgets.QLabel("Radius Min ({})".format(0.0)) self.radiusMinSlider = QtWidgets.QSlider(QtCore.Qt.Horizontal) self.radiusMinSlider.setMinimum(0) self.radiusMinSlider.setMaximum(1000) self.radiusMinSlider.setValue(0) self.radiusMinSlider.valueChanged.connect(self.refresh_radius_min) self.radiusMaxLabel = QtWidgets.QLabel("Radius Max ({})".format(10.0)) self.radiusMaxSlider = QtWidgets.QSlider(QtCore.Qt.Horizontal) self.radiusMaxSlider.setMinimum(0) self.radiusMaxSlider.setMaximum(1000) self.radiusMaxSlider.setValue(1000) self.radiusMaxSlider.valueChanged.connect(self.refresh_radius_max) self.numberOfContourLevelsLabel = QtWidgets.QLabel("Number of Contour Levels ({})".format(50)) self.numberOfContourLevelsLabel.setFixedWidth(160) self.numberOfContourLevelsSlider = QtWidgets.QSlider(QtCore.Qt.Horizontal) self.numberOfContourLevelsSlider.setMinimum(5) self.numberOfContourLevelsSlider.setMaximum(100) self.numberOfContourLevelsSlider.setValue(50) self.numberOfContourLevelsSlider.valueChanged.connect(self.refresh_number_of_contour_levels) self.show2DContourButton = QtWidgets.QPushButton("Show 2D Contour") self.show2DContourButton.clicked.connect(self.show_2D_contour_button_pressed) self.show2DContourButton.setEnabled(False) self.plotOptionsGrid.addWidget(self.colormapLabel,0,0) self.plotOptionsGrid.addWidget(self.colormap,0,1) self.plotOptionsGrid.addWidget(self.levelMinLabel,1,0) self.plotOptionsGrid.addWidget(self.levelMinSlider,1,1) self.plotOptionsGrid.addWidget(self.levelMaxLabel,2,0) self.plotOptionsGrid.addWidget(self.levelMaxSlider,2,1) self.plotOptionsGrid.addWidget(self.radiusMinLabel,3,0) self.plotOptionsGrid.addWidget(self.radiusMinSlider,3,1) self.plotOptionsGrid.addWidget(self.radiusMaxLabel,4,0) self.plotOptionsGrid.addWidget(self.radiusMaxSlider,4,1) self.plotOptionsGrid.addWidget(self.numberOfContourLevelsLabel,5,0) self.plotOptionsGrid.addWidget(self.numberOfContourLevelsSlider,5,1) self.plotOptionsVBox.addLayout(self.plotOptionsGrid) self.plotOptionsVBox.addWidget(self.show2DContourButton) self.themeList = QtWidgets.QComboBox(self) self.themeList.addItem("Qt") self.themeList.addItem("Primary Colors") self.themeList.addItem("Digia") self.themeList.addItem("Stone Moss") self.themeList.addItem("Army Blue") self.themeList.addItem("Retro") self.themeList.addItem("Ebony") self.themeList.addItem("Isabelle") self.colorGroupBox = QtWidgets.QGroupBox("3D Surface Colormap") self.colorGroupBox.setStyleSheet('QGroupBox::title {color:blue;}') self.grBtoY = QtGui.QLinearGradient(0,0,1,100) self.grBtoY.setColorAt(1.0,QtCore.Qt.black) self.grBtoY.setColorAt(0.67,QtCore.Qt.blue) self.grBtoY.setColorAt(0.33,QtCore.Qt.red) self.grBtoY.setColorAt(0.0,QtCore.Qt.yellow) self.pm = QtGui.QPixmap(50,100) self.pmp = QtGui.QPainter(self.pm) self.pmp.setBrush(QtGui.QBrush(self.grBtoY)) self.pmp.setPen(QtCore.Qt.NoPen) self.pmp.drawRect(0,0,50,100) self.pmp.end() self.gradientBtoYPB = QtWidgets.QPushButton(self) self.gradientBtoYPB.setIcon(QtGui.QIcon(self.pm)) self.gradientBtoYPB.setIconSize(QtCore.QSize(50,100)) self.gradientBtoYPB.setEnabled(False) self.grGtoR = QtGui.QLinearGradient(0,0,1,100) self.grGtoR.setColorAt(1.0,QtCore.Qt.darkGreen) self.grGtoR.setColorAt(0.5,QtCore.Qt.yellow) self.grGtoR.setColorAt(0.2,QtCore.Qt.red) self.grGtoR.setColorAt(0.0,QtCore.Qt.darkRed) self.pm2 = QtGui.QPixmap(50,100) self.pmp2 = QtGui.QPainter(self.pm2) self.pmp2.setBrush(QtGui.QBrush(self.grGtoR)) self.pmp2.drawRect(0,0,50,100) self.pmp2.end() self.gradientGtoRPB = QtWidgets.QPushButton(self) self.gradientGtoRPB.setIcon(QtGui.QIcon(self.pm2)) self.gradientGtoRPB.setIconSize(QtCore.QSize(50,100)) self.gradientGtoRPB.setEnabled(False) self.grBtoR = QtGui.QLinearGradient(0,0,1,100) self.grBtoR.setColorAt(1.0, QtCore.Qt.darkBlue) self.grBtoR.setColorAt(0.95, QtCore.Qt.blue) self.grBtoR.setColorAt(0.9, QtCore.Qt.darkCyan) self.grBtoR.setColorAt(0.8, QtCore.Qt.cyan) self.grBtoR.setColorAt(0.6, QtCore.Qt.green) self.grBtoR.setColorAt(0.2, QtCore.Qt.yellow) self.grBtoR.setColorAt(0.0, QtCore.Qt.red) self.pm3 = QtGui.QPixmap(50,100) self.pmp3 = QtGui.QPainter(self.pm3) self.pmp3.setBrush(QtGui.QBrush(self.grBtoR)) self.pmp3.drawRect(0,0,50,100) self.pmp3.end() self.gradientBtoRPB = QtWidgets.QPushButton(self) self.gradientBtoRPB.setIcon(QtGui.QIcon(self.pm3)) self.gradientBtoRPB.setIconSize(QtCore.QSize(50,100)) self.gradientBtoRPB.setEnabled(False) self.colorHBox = QtWidgets.QHBoxLayout() self.colorHBox.addWidget(self.gradientBtoYPB) self.colorHBox.addWidget(self.gradientGtoRPB) self.colorHBox.addWidget(self.gradientBtoRPB) self.colorGroupBox.setLayout(self.colorHBox) self.statusBar = QtWidgets.QGroupBox("Log") self.statusBar.setStyleSheet('QGroupBox::title {color:blue;}') self.statusGrid = QtWidgets.QGridLayout(self.statusBar) self.statusBar.setFixedHeight(150) self.statusBar.setSizePolicy(QtWidgets.QSizePolicy.Expanding,QtWidgets.QSizePolicy.Fixed) self.logBox = QtWidgets.QTextEdit(QtCore.QTime.currentTime().toString("hh:mm:ss")+ \ "\u00A0\u00A0\u00A0\u00A0Initialized!") self.logCursor = QtGui.QTextCursor(self.logBox.document()) self.logCursor.movePosition(QtGui.QTextCursor.End) self.logBox.setTextCursor(self.logCursor) self.logBox.ensureCursorVisible() self.logBox.setAlignment(QtCore.Qt.AlignTop) self.logBox.setFrameShape(QtWidgets.QFrame.NoFrame) self.logBoxScroll = QtWidgets.QScrollArea() self.logBoxScroll.setWidget(self.logBox) self.logBoxScroll.setWidgetResizable(True) self.logBoxScroll.setFrameShape(QtWidgets.QFrame.NoFrame) self.statusGrid.addWidget(self.logBoxScroll,0,0) self.vLayout.addWidget(self.chooseGraph) self.vLayout.addWidget(self.plotOptions) themeLabel = QtWidgets.QLabel("Theme") themeLabel.setStyleSheet("QLabel {color:blue;}") self.vLayout.addWidget(themeLabel) self.vLayout.addWidget(self.themeList) self.vLayout.addWidget(self.colorGroupBox) self.mainVLayout.addWidget(self.statusBar) self.show() desktopRect = QtWidgets.QApplication.desktop().availableGeometry(self) center = desktopRect.center() self.move(center.x()-self.width()*0.5,center.y()-self.height()*0.5) self.themeList.currentIndexChanged.connect(self.graph.change_theme) self.gradientBtoYPB.pressed.connect(self.graph.set_black_to_yellow_gradient) self.gradientGtoRPB.pressed.connect(self.graph.set_green_to_red_gradient) self.gradientBtoRPB.pressed.connect(self.graph.set_blue_to_red_gradient) self.SHOW_2D_CONTOUR_SIGNAL.connect(self.show_2d_contour) self.graph.LOG_MESSAGE.connect(self.update_log) self.themeList.setCurrentIndex(3) if not path=='': self.graph.fill_two_dimensional_mapping_proxy(path) self.graph.enable_two_dimensional_mapping_model(True) self.show2DContourButton.setEnabled(True) self.gradientBtoYPB.setEnabled(True) self.gradientGtoRPB.setEnabled(True) self.gradientBtoRPB.setEnabled(True) def choose_graph(self): path = QtWidgets.QFileDialog.getOpenFileName(None,"choose the graph",self.graphPath) self.graphPath = path[0] self.graphPathExtension = os.path.splitext(self.graphPath)[1] if not self.graphPathExtension == ".txt": self.raise_error('[Error: wrong file type] Please choose a *.txt file') self.update_log('[Error: wrong file type] Please choose a *.txt file') else: self.chooseSourceLabel.setText("The path of the graph is:\n"+self.graphPath) self.update_log("Loading DataArray...") QtCore.QCoreApplication.processEvents() self.graph.fill_two_dimensional_mapping_proxy(self.graphPath) self.graph.enable_two_dimensional_mapping_model(True) self.show2DContourButton.setEnabled(True) self.gradientBtoYPB.setEnabled(True) self.gradientGtoRPB.setEnabled(True) self.gradientBtoRPB.setEnabled(True) def refresh_level_min(self): self.levelMinLabel.setText("Level Min ({})".format(self.levelMinSlider.value()/100)) if self.levelMinSlider.value() > self.levelMaxSlider.value(): self.levelMaxSlider.setValue(self.levelMinSlider.value()) def refresh_level_max(self): self.levelMaxLabel.setText("Level Max ({})".format(self.levelMaxSlider.value()/100)) if self.levelMinSlider.value() > self.levelMaxSlider.value(): self.levelMinSlider.setValue(self.levelMaxSlider.value()) def refresh_radius_min(self): self.radiusMinLabel.setText("Radius Min ({})".format(self.radiusMinSlider.value()/100)) if self.radiusMinSlider.value() > self.radiusMaxSlider.value(): self.radiusMaxSlider.setValue(self.radiusMinSlider.value()) def refresh_radius_max(self): self.radiusMaxLabel.setText("Radius Max ({})".format(self.radiusMaxSlider.value()/100)) if self.radiusMinSlider.value() > self.radiusMaxSlider.value(): self.radiusMinSlider.setValue(self.radiusMaxSlider.value()) def refresh_number_of_contour_levels(self): self.numberOfContourLevelsLabel.setText("Number of Contour Levels ({})".format(self.numberOfContourLevelsSlider.value())) def show_2D_contour_button_pressed(self): self.update_log("Showing contour plot...") QtCore.QCoreApplication.processEvents() self.SHOW_2D_CONTOUR_SIGNAL.emit(self.graphPath,True,self.levelMinSlider.value()/100,self.levelMaxSlider.value()/100,\ self.radiusMinSlider.value()/100,self.radiusMaxSlider.value()/100,\ self.numberOfContourLevelsSlider.value(),self.colormap.currentText()) def show_2d_contour(self,path, insideGraph3D = False, min=0.0, max=1.0, radius_min=0, radius_max=10, number_of_levels=50, colormap='jet'): window = QtWidgets.QDialog() layout = QtWidgets.QVBoxLayout(window) figure = plt.figure() canvas = FigureCanvas(figure) toolbar = NavigationToolbar(canvas,window) figure.clear() if not path == None: if os.path.splitext(path)[1] == '.txt': radius,theta,intensity = self.convert_to_RTI(path) levels = np.linspace(min,max,number_of_levels) ax = figure.add_subplot(111,polar = True) ax.contourf(theta,radius,intensity,levels=levels,cmap=colormap) ax.set_ylim(radius_min,radius_max) canvas.draw() else: self.raise_error('[Error: wrong file type] Please choose a *.txt file') else: self.raise_error('[Error: no file] Please choose a valid file first') layout.addWidget(toolbar) layout.addWidget(canvas) window.setWindowTitle("2D Contour") window.show() if insideGraph3D: window.finished.connect(self.contour_plot_finished) def contour_plot_finished(self): self.update_log('Contour plot ended.') def update_log(self,msg): self.logBox.append(QtCore.QTime.currentTime().toString("hh:mm:ss")+"\u00A0\u00A0\u00A0\u00A0"+msg) def convert_to_RTI(self,path): raw_data = np.loadtxt(path) if np.amin(raw_data[:,0])<0: data = np.empty(raw_data.shape) data[:,0] = np.abs(raw_data[:,0]) data[:,1] = np.where(raw_data[:,0]>0,0,180)+raw_data[:,1] data[:,2] = raw_data[:,2] else: data = raw_data df = pd.DataFrame(data,columns = ['radius','theta','intensity']) table = df.pivot_table(values = 'intensity',index='radius',columns='theta') return table.index.tolist(),[a/180*math.pi for a in table.columns.tolist()],table def raise_error(self,message): msg = QtWidgets.QMessageBox() msg.setIcon(QtWidgets.QMessageBox.Warning) msg.setText(message) msg.setWindowTitle("Error") msg.setStandardButtons(QtWidgets.QMessageBox.Ok) msg.setEscapeButton(QtWidgets.QMessageBox.Close) msg.exec() def raise_attention(self,information): info = QtWidgets.QMessageBox() info.setIcon(QtWidgets.QMessageBox.Information) info.setText(information) info.setWindowTitle("Information") info.setStandardButtons(QtWidgets.QMessageBox.Ok) info.setEscapeButton(QtWidgets.QMessageBox.Close) info.exec() class SurfaceGraph(QtDataVisualization.Q3DSurface): LOG_MESSAGE = QtCore.pyqtSignal(str) def __init__(self): super(SurfaceGraph,self).__init__() self.twoDimensionalMappingProxy = QtDataVisualization.QSurfaceDataProxy() self.twoDimensionalMappingSeries = QtDataVisualization.QSurface3DSeries(self.twoDimensionalMappingProxy) def convert_to_data_array(self,path): data = np.loadtxt(path) df = pd.DataFrame(data,columns = ['radius','theta','intensity']) table = df.pivot_table(values = 'intensity',index='radius',columns='theta') radius = table.index.tolist() theta = table.columns.tolist() self.sampleMin,self.sampleMax = -max(radius),max(radius) dataArray = [] for i in range(table.shape[0]): newRow=[] for j in range(table.shape[1]): item = QtDataVisualization.QSurfaceDataItem() X,Y,Z = radius[i]*np.cos(theta[j]/180*math.pi),\ radius[i]*np.sin(theta[j]/180*math.pi),\ table.loc[radius[i],theta[j]] item.setPosition(QtGui.QVector3D(X,Z,Y)) newRow.append(item) dataArray.append(newRow) return dataArray def fill_two_dimensional_mapping_proxy(self,path): dataArray = self.convert_to_data_array(path) self.twoDimensionalMappingProxy.resetArray(dataArray) self.LOG_MESSAGE.emit("DataArray Loaded!") def enable_two_dimensional_mapping_model(self,enable): if enable: for series in self.seriesList(): self.removeSeries(series) self.twoDimensionalMappingSeries.setDrawMode(QtDataVisualization.QSurface3DSeries.DrawSurface) self.twoDimensionalMappingSeries.setFlatShadingEnabled(True) self.axisX().setLabelFormat("%.2f") self.axisZ().setLabelFormat("%.2f") self.axisX().setRange(self.sampleMin,self.sampleMax) self.axisY().setRange(0,1) self.axisZ().setRange(self.sampleMin,self.sampleMax) self.axisX().setTitle("Kx (\u212B\u207B\u00B9)") self.axisX().setTitleVisible(True) self.axisZ().setTitle("Ky (\u212B\u207B\u00B9)") self.axisZ().setTitleVisible(True) self.axisY().setTitle("Normalized Intensity (arb. units)") self.axisY().setTitleVisible(True) self.axisX().setLabelAutoRotation(30) self.axisY().setLabelAutoRotation(90) self.axisZ().setLabelAutoRotation(30) self.addSeries(self.twoDimensionalMappingSeries) def change_theme(self, theme): self.activeTheme().setType(QtDataVisualization.Q3DTheme.Theme(theme)) def set_black_to_yellow_gradient(self): self.gr = QtGui.QLinearGradient() self.gr.setColorAt(0.0, QtCore.Qt.black) self.gr.setColorAt(0.33, QtCore.Qt.blue) self.gr.setColorAt(0.67, QtCore.Qt.red) self.gr.setColorAt(1.0, QtCore.Qt.yellow) self.seriesList()[0].setBaseGradient(self.gr) self.seriesList()[0].setColorStyle(QtDataVisualization.Q3DTheme.ColorStyleRangeGradient) def set_green_to_red_gradient(self): self.gr = QtGui.QLinearGradient() self.gr.setColorAt(0.0, QtCore.Qt.darkGreen) self.gr.setColorAt(0.5, QtCore.Qt.yellow) self.gr.setColorAt(0.8, QtCore.Qt.red) self.gr.setColorAt(1.0, QtCore.Qt.darkRed) self.seriesList()[0].setBaseGradient(self.gr) self.seriesList()[0].setColorStyle(QtDataVisualization.Q3DTheme.ColorStyleRangeGradient) def set_blue_to_red_gradient(self): self.gr = QtGui.QLinearGradient() self.gr.setColorAt(0.0, QtCore.Qt.darkBlue) self.gr.setColorAt(0.05, QtCore.Qt.blue) self.gr.setColorAt(0.1, QtCore.Qt.darkCyan) self.gr.setColorAt(0.2, QtCore.Qt.cyan) self.gr.setColorAt(0.4, QtCore.Qt.green) self.gr.setColorAt(0.8, QtCore.Qt.yellow) self.gr.setColorAt(1.0, QtCore.Qt.red) self.seriesList()[0].setBaseGradient(self.gr) self.seriesList()[0].setColorStyle(QtDataVisualization.Q3DTheme.ColorStyleRangeGradient) def raise_error(self,message): msg = QtWidgets.QMessageBox() msg.setIcon(QtWidgets.QMessageBox.Warning) msg.setText(message) msg.setWindowTitle("Error") msg.setStandardButtons(QtWidgets.QMessageBox.Ok) msg.setEscapeButton(QtWidgets.QMessageBox.Close) msg.exec() def raise_attention(self,information): info = QtWidgets.QMessageBox() info.setIcon(QtWidgets.QMessageBox.Information) info.setText(information) info.setWindowTitle("Information") info.setStandardButtons(QtWidgets.QMessageBox.Ok) info.setEscapeButton(QtWidgets.QMessageBox.Close) info.exec()
true
true
f725bee9770f6b2e7f8623f5101b820360ca8b9e
3,329
py
Python
src/build_workflow/build_recorder.py
Rishikesh1159/opensearch-build
9f402afe9c945c9b715a69e94cbf0137bfbcd8b7
[ "Apache-2.0" ]
null
null
null
src/build_workflow/build_recorder.py
Rishikesh1159/opensearch-build
9f402afe9c945c9b715a69e94cbf0137bfbcd8b7
[ "Apache-2.0" ]
null
null
null
src/build_workflow/build_recorder.py
Rishikesh1159/opensearch-build
9f402afe9c945c9b715a69e94cbf0137bfbcd8b7
[ "Apache-2.0" ]
null
null
null
# SPDX-License-Identifier: Apache-2.0 # # The OpenSearch Contributors require contributions made to # this file be licensed under the Apache-2.0 license or a # compatible open source license. import logging import os import shutil from build_workflow.build_artifact_checks import BuildArtifactChecks from manifests.build_manifest import BuildManifest class BuildRecorder: def __init__(self, target): self.build_manifest = self.BuildManifestBuilder(target) self.target = target self.name = target.name def record_component(self, component_name, git_repo): self.build_manifest.append_component( component_name, self.target.component_version, git_repo.url, git_repo.ref, git_repo.sha, ) def record_artifact( self, component_name, artifact_type, artifact_path, artifact_file ): logging.info( f"Recording {artifact_type} artifact for {component_name}: {artifact_path} (from {artifact_file})" ) # Ensure the target directory exists dest_file = os.path.join(self.target.output_dir, artifact_path) dest_dir = os.path.dirname(dest_file) os.makedirs(dest_dir, exist_ok=True) # Check artifact BuildArtifactChecks.check(self.target, artifact_type, artifact_file) # Copy the file shutil.copyfile(artifact_file, dest_file) # Notify the recorder self.build_manifest.append_artifact( component_name, artifact_type, artifact_path ) def get_manifest(self): return self.build_manifest.to_manifest() def write_manifest(self): manifest_path = os.path.join(self.target.output_dir, "manifest.yml") self.get_manifest().to_file(manifest_path) logging.info(f"Created build manifest {manifest_path}") class BuildManifestBuilder: def __init__(self, target): self.data = {} self.data["build"] = {} self.data["build"]["id"] = target.build_id self.data["build"]["name"] = target.name self.data["build"]["version"] = target.opensearch_version self.data["build"]["architecture"] = target.arch self.data["schema-version"] = "1.1" self.components_hash = {} def append_component(self, name, version, repository_url, ref, commit_id): component = { "name": name, "repository": repository_url, "ref": ref, "commit_id": commit_id, "artifacts": {}, "version": version, } self.components_hash[name] = component def append_artifact(self, component, type, path): artifacts = self.components_hash[component]["artifacts"] list = artifacts.get(type, []) if len(list) == 0: artifacts[type] = list list.append(path) def to_manifest(self): # The build manifest expects `components` to be a list, not a hash, so we need to munge things a bit components = self.components_hash.values() if len(components) > 0: self.data["components"] = list(components) return BuildManifest(self.data)
36.184783
112
0.620907
import logging import os import shutil from build_workflow.build_artifact_checks import BuildArtifactChecks from manifests.build_manifest import BuildManifest class BuildRecorder: def __init__(self, target): self.build_manifest = self.BuildManifestBuilder(target) self.target = target self.name = target.name def record_component(self, component_name, git_repo): self.build_manifest.append_component( component_name, self.target.component_version, git_repo.url, git_repo.ref, git_repo.sha, ) def record_artifact( self, component_name, artifact_type, artifact_path, artifact_file ): logging.info( f"Recording {artifact_type} artifact for {component_name}: {artifact_path} (from {artifact_file})" ) dest_file = os.path.join(self.target.output_dir, artifact_path) dest_dir = os.path.dirname(dest_file) os.makedirs(dest_dir, exist_ok=True) BuildArtifactChecks.check(self.target, artifact_type, artifact_file) shutil.copyfile(artifact_file, dest_file) self.build_manifest.append_artifact( component_name, artifact_type, artifact_path ) def get_manifest(self): return self.build_manifest.to_manifest() def write_manifest(self): manifest_path = os.path.join(self.target.output_dir, "manifest.yml") self.get_manifest().to_file(manifest_path) logging.info(f"Created build manifest {manifest_path}") class BuildManifestBuilder: def __init__(self, target): self.data = {} self.data["build"] = {} self.data["build"]["id"] = target.build_id self.data["build"]["name"] = target.name self.data["build"]["version"] = target.opensearch_version self.data["build"]["architecture"] = target.arch self.data["schema-version"] = "1.1" self.components_hash = {} def append_component(self, name, version, repository_url, ref, commit_id): component = { "name": name, "repository": repository_url, "ref": ref, "commit_id": commit_id, "artifacts": {}, "version": version, } self.components_hash[name] = component def append_artifact(self, component, type, path): artifacts = self.components_hash[component]["artifacts"] list = artifacts.get(type, []) if len(list) == 0: artifacts[type] = list list.append(path) def to_manifest(self): components = self.components_hash.values() if len(components) > 0: self.data["components"] = list(components) return BuildManifest(self.data)
true
true
f725bf0dff062fe048d70f6120efa6e9747d1111
15,159
py
Python
StaticAnalysis/dockerfile_info2/Parser/static_parser.py
FaniD/SecureWilly
f929f94c6a778b2527e493edbc7309cf10e616e0
[ "Apache-2.0" ]
9
2019-03-11T22:57:14.000Z
2021-12-14T13:04:09.000Z
StaticAnalysis/dockerfile_info2/Parser/static_parser.py
FaniD/Security-on-Docker
f929f94c6a778b2527e493edbc7309cf10e616e0
[ "Apache-2.0" ]
null
null
null
StaticAnalysis/dockerfile_info2/Parser/static_parser.py
FaniD/Security-on-Docker
f929f94c6a778b2527e493edbc7309cf10e616e0
[ "Apache-2.0" ]
1
2021-01-30T15:23:01.000Z
2021-01-30T15:23:01.000Z
#!/usr/bin/env python import io import sys from collections import OrderedDict current_dir = "dockerfileinfo2" current_dir = current_dir.lower() pwd = "/home/ubuntu/SecureWilly/StaticAnalysis/dockerfile_info2/Parser" pre_pwd = "/home/ubuntu/SecureWilly/StaticAnalysis/dockerfile_info2" #This will be our preliminery profile from Static Analysis. Append every rule extracted to it. static_profile = [] #Rules #We prepare some fixed rules that will be added below under the right conditions #This rule is needed so that we can work with files in containers and handling containers filesystem file_rule = '\tfile, #Allows access to containers filesystem\n' #These rules are needed so that we can switch between users setuid_setgid_rule = '\tcapability setuid, #Needed to switch between users\n\tcapability setgid, #Needed to switch between users\n' deny_setuid_setgid_rule = '\tdeny capability setuid, #Deny capability to create new login session\n\tdeny capability setgid, #Deny capability to create new login session\n' #Chown capability chown_cap = '\tcapability chown, #This capability is needed to use chown\n' #Docker rule is needed in every container so it has access to its filesystem layers docker_rule = '\t/var/lib/docker/* r, #Access to layers of filesystem\n' #Deny ptrace rule to confront container breakouts deny_ptrace_rule = '\tdeny ptrace (readby, tracedby), #Confront container breakout attacks\n' #These rules are added by default to every profile static_profile.append(file_rule) static_profile.append(docker_rule) static_profile.append(deny_ptrace_rule) #-------------------------------------Dockerfile------------------------------------------------- dockerfile = str(sys.argv[1]) #If there is no dockerfile provided, SecureWilly_API gives an empty file as argument with open(dockerfile,'r') as infile: data = infile.readlines() #Keywords to search for in Dockerfile chmod = 'RUN chmod' chown = 'RUN chown' user1 = 'USER' user1_names = [] user1_counter = 0 user2 = 'RUN useradd' user2_names = [] user2_counter = 0 copy = 'COPY' add = 'ADD' expose = 'EXPOSE' #Parse the whole file, line per line for line in data: #Exposed ports if expose in line: line = line.split(' ') port_proto = line[1] if 'udp' in port_proto: proto='udp' else: proto='tcp' #At the time we strip the protocol #When the bind rule is supported in AppArmor #We will fix this if it's actually needed in the rule port_cont = port_proto.replace(proto, '') port_cont = port_cont.replace('/','') port_cont = port_cont.strip('\n') ports_rule='\tnetwork ' + proto + ', #Allowing networking with ports forwarding\n' static_profile.append(ports_rule) #port refers to container's port #In order for an app to bind to ports < 1024 capability net bind service is needed if int(port_cont) < 1024: static_profile.append('\tcapability net_bind_service, #This capability is needed to bind a socket to well-known ports\n') #Users #There should be permission to switch only to this user but athough it is given in the documentation, this specification is not yet implemented: #setuid -> userA #static_profile.append(setuid_setgid_rule) if user1 in line: #USER found. Augment the counter and keep the name in names list line = line.strip('\n') line = line.split(' ') user1_counter+=1 user1_names.append(line[1]) if user2 in line: #Run useradd found: Augment the counter and keep the name in names list #There should be permission to switch only to this user but athough it is given in the documentation, this specification is not yet implemented: #setuid -> userA #static_profile.append(setuid_setgid_rule) line = line.strip('\n') line = line.split(' ') user2_counter+=1 user2_names.append(line[2]) if chmod in line: #Chmod found so we have to deal with files (file rule) and fix permission bits line = line.strip('\n') line = line.split(' ') #flags TODO s = line[1].split('-', 1) #Chmod Rule - not supported #Add the right permissions to owner of the file and others #Path permission rule - File access rule chmod_path = line[len(line)-1] chmod_permission = list(line[len(line)-2]) #chmod permissions calculate both for letters and numbers. ONLY FOR OWNER and OTHERS. Not supported for owning group! if chmod_permission[0] == 'u': owner = line[len(line)-2].split('+') if chmod_permission[0] == '1': owner = 'ix' if chmod_permission[0] == '2': owner = 'w' if chmod_permission[0] == '3': owner = 'wix' if chmod_permission[0] == '4': owner = 'r' if chmod_permission[0] == '5': owner = 'rix' if chmod_permission[0] == '6': owner = 'rw' if chmod_permission[0] == '7': owner = 'rwix' if chmod_permission[2] == 'u': others = line[len(line)-2].split('+') if chmod_permission[2] == '1': others = 'ix' if chmod_permission[2] == '2': others = 'w' if chmod_permission[2] == '3': others = 'wix' if chmod_permission[2] == '4': others = 'r' if chmod_permission[2] == '5': others = 'rix' if chmod_permission[2] == '6': others = 'rw' if chmod_permission[2] == '7': others = 'rwix' #Owner's permissions chmod_owner = '\towner ' + chmod_path + ' ' + owner + ',\n' #Others' permissions chmod_others = '\t' + chmod_path + ' ' + others + ',\n' static_profile.append(chmod_owner) static_profile.append(chmod_others) #if chown in line: #Chown command found so we need file rule, setuid rule and permission bits - if given #Add capability rule if we want to allow chown command to be used in the container #Not needed. Do it only if it is asked #static_profile.append('\tcapability chown,\n') #static_profile.append(setuid_setgid_rule) #Not supported! #Chown Rule needed as well #line = line.strip('\n') #line = line.split(' ') #path = line[len(line)-1] #owner_group = line[len(line)-2] #owner_group = owner_group.split(':') #owner = owner_group[0] #if len(owner_group) == 2: # group = owner_group[1] # chown_rule = '\tchown ' + path + ' to owner=' + owner + ' group=' + group + ',\n' #else: # chown_rule = '\tchown ' + path + ' to owner=' + owner + ',\n' #Add chown rule #static_profile.append(chown_rule) #Count number of users used and added in Dockerfile to determine if there should be a switching at the image or not if user1_counter>1: static_profile.append(setuid_setgid_rule) if user2_counter==1: if user1_counter==1: if user1_names[0]!=user2_names[0]: static_profile.append(setuid_setgid_rule) else: #This is about 0 USER commands (>1 is already taken into account) static_profile.append(setuid_setgid_rule) if user2_counter>1: static_profile.append(setuid_setgid_rule) #-------------------------------------DockerCompose------------------------------------- all_capabilities = ['audit_control', 'audit_write', 'chown', 'dac_override', 'dac_read_search', 'fowner', 'fsetid', 'kill', 'ipc_lock', 'ipc_owner', 'lease', 'linux_immutable', 'mac_admin', 'mac_override', 'mknod', 'net_admin', 'net_bind_service', 'net_broadcast', 'net_raw', 'setgid', 'setpcap', 'setuid', 'sys_admin', 'sys_boot', 'sys_chroot', 'sys_module', 'sys_nice', 'sys_pacct', 'sys_ptrace', 'sys_rawio', 'sys_resource', 'sys_time', 'sys_tty_config', 'setfcap'] dockercompose = str(sys.argv[2]) #If no docker-compose is provided, SecureWilly_API will create one by the docker run flags given by user with open(dockercompose,'r') as infile: data = infile.readlines() network = 'ports:' expose = 'expose:' mount = 'volumes:' capability = 'cap_add:' capability_deny = 'cap_drop:' ulimit = 'ulimits' for i in xrange(len(data)): #because we will need the next line if network in data[i]: z = i while ('-' in data[z+1]): #checking for multiple ports (same with volumes, capabilities etc) ports = data[z+1].strip() if 'udp' in ports: proto='udp' else: proto='tcp' #At the time we strip the protocol #When the bind rule is supported in AppArmor #We will fix this if it's actually needed in the rule ports = ports.replace(proto,'') ports = ports.replace('/','') ports = ports.strip('\n') ports = ports.strip('"') if ':' in ports: ports = ports.split(':') port_host = ports[0].strip('-') port_host = port_host.strip() port_host = port_host.strip('"') port_container = ports[1] else: port_container = ports if int(port_container) < 1024: #In order for an app to bind to ports < 1024 capability net bind service is needed static_profile.append('\tcapability net_bind_service, #This capability is needed to bind a socket to well-known ports\n') #bind_rule = '\tnetwork bind ' + port_host + ' to ' + port_container + ',\n' NOT SUPPORTED YET static_profile.append('\tnetwork ' + proto + ', #Allowing networking with ports forwarding\n') z = z+1 if expose in data[i]: z = i while ('-' in data[z+1]): #checking for multiple ports (same with volumes, capabilities etc) port = data[z+1].strip() if 'udp' in ports: proto='udp' else: proto='tcp' port = port.replace(proto, '') port = port.replace('/','') port = port.strip('\n') port = port.strip('"') if int(port) < 1024: #In order for an app to bind to ports < 1024 capability net bind service is needed static_profile.append('\tcapability net_bind_service, #This capability is needed to bind a socket to well-known ports\n') static_profile.append('\tnetwork ' + proto + ', #Allowing networking with ports forwarding\n') z = z+1 if mount in data[i]: z = i while ('-' in data[z+1]): src_mntpnt = data[z+1].strip() src_mntpnt = src_mntpnt.strip('"') src_mntpnt = src_mntpnt.split(':') src = src_mntpnt[0].strip('-') src = src.strip() src = src.strip('"') mntpnt = src_mntpnt[1] if (mntpnt.endswith('/')): mntpnt = mntpnt.rstrip('/') #If source does not start with / then it is one of the following #Relative path . -> pwd #Relative path .. -> father of pwd #Not a path but a named volume #So we change it into the real host path if (src.startswith('..')): src = pwd_dir elif (src.startswith('.')): src = pre_pwd elif (not src.startswith('/')): src="/var/lib/docker/volumes/" + current_dir + "_" + src + "/_data" #If there is a mount option: if len(src_mntpnt)==3: option = src_mntpnt[2] if 'ro' in option: ro_rule = '\tdeny ' + mntpnt + ' w,\n' static_profile.append(ro_rule) mount_rule = '\tmount options=ro ' + src + ' -> ' + mntpnt + ', #Bind host volume to docker container volume\n' file_mnt_rule = '\t' + mntpnt + '/* r,\n' else: mount_rule = '\tmount ' + src + ' -> ' + mntpnt + ', #Bind host volume to docker container volume\n' file_mnt_rule = '\t' + mntpnt + '/* rw,\n' else: mount_rule = '\tmount ' + src + ' -> ' + mntpnt + ', #Bind host volume to docker container volume\n' file_mnt_rule = '\t' + mntpnt + '/* rw,\n' if mntpnt == '': #Then it was root's dir and we stripped of the / mntpnt = '/' umount_rule = '\tdeny umount ' + mntpnt + ', #Disallow anybody that wants to break this mountpoint\n' remount_rule = '\tdeny remount '+ mntpnt + ', #Disallow anybody that wants to remount this mountpoint\n' static_profile.append(mount_rule) static_profile.append(umount_rule) static_profile.append(remount_rule) static_profile.append(file_mnt_rule) z = z+1 #If docker.sock is mounted in one of the following ways, deny capabilities setuid and setgid so the user won't be able to start a new login session if src=='/': static_profile.append(deny_setuid_setgid_rule) else: if (src.endswith('/')): src = src.rstrip('/') if src=='/var': static_profile.append(deny_setuid_setgid_rule) if src=='/var/run': static_profile.append(deny_setuid_setgid_rule) if src=='/var/run/docker.sock': static_profile.append(deny_setuid_setgid_rule) if capability in data[i]: z = i while ('-' in data[z+1]): x = data[z+1].strip() x = x.strip('-') x = x.strip() if x=='ALL': cap = '\tcapability, #Add all capabilities\n' static_profile.append(cap) else: x = x.lower() cap = '\tcapability ' + x + ',\n' static_profile.append(cap) z = z+1 if capability_deny in data[i]: z = i while ('-' in data[z+1]): x = data[z+1].strip() x = x.strip('-') x = x.strip() if x=='ALL': cap = '\tdeny capability, #Drop all capabilities\n' static_profile.append(cap) else: x = x.lower() cap = '\tdeny capability ' + x + ',\n' static_profile.append(cap) z = z+1 if ulimit in data[i]: z = i+1; my_ulimit = data[z].strip() my_ulimit = my_ulimit.strip(":") slimits = data[z+1].split(':') soft = slimits[1].strip() hlimits = data[z+2].split(':') hard = hlimits[1].strip() #TODO More than one ulimits #TODO Single value ulimit (this is hard limit) ulimit_rule = "\tset rlimit " + my_ulimit + " <= " + hard + ",\n" static_profile.append(ulimit_rule) z = z+3 #-------Static profile is ready-------- #Delete duplicate rules by converting list to set. Convert back to list to keep the order of the beggining and ending of a profile #This is the way to delete duplicates, when we don't care about the order static_profile = list(set(static_profile)) #Add the beggining and ending of the profile #beggining static_profile.insert(0, '#include <tunables/global>\n\nprofile static_profile flags=(attach_disconnected,mediate_deleted) {\n\n') #ending static_profile.append('}\n') #Output with open('static_profile', 'w') as outfile: outfile.writelines( static_profile )
38.474619
468
0.605779
import io import sys from collections import OrderedDict current_dir = "dockerfileinfo2" current_dir = current_dir.lower() pwd = "/home/ubuntu/SecureWilly/StaticAnalysis/dockerfile_info2/Parser" pre_pwd = "/home/ubuntu/SecureWilly/StaticAnalysis/dockerfile_info2" static_profile = [] file_rule = '\tfile, #Allows access to containers filesystem\n' setuid_setgid_rule = '\tcapability setuid, #Needed to switch between users\n\tcapability setgid, #Needed to switch between users\n' deny_setuid_setgid_rule = '\tdeny capability setuid, #Deny capability to create new login session\n\tdeny capability setgid, #Deny capability to create new login session\n' chown_cap = '\tcapability chown, #This capability is needed to use chown\n' docker_rule = '\t/var/lib/docker/* r, #Access to layers of filesystem\n' deny_ptrace_rule = '\tdeny ptrace (readby, tracedby), #Confront container breakout attacks\n' static_profile.append(file_rule) static_profile.append(docker_rule) static_profile.append(deny_ptrace_rule) dockerfile = str(sys.argv[1]) with open(dockerfile,'r') as infile: data = infile.readlines() chmod = 'RUN chmod' chown = 'RUN chown' user1 = 'USER' user1_names = [] user1_counter = 0 user2 = 'RUN useradd' user2_names = [] user2_counter = 0 copy = 'COPY' add = 'ADD' expose = 'EXPOSE' for line in data: if expose in line: line = line.split(' ') port_proto = line[1] if 'udp' in port_proto: proto='udp' else: proto='tcp' port_cont = port_proto.replace(proto, '') port_cont = port_cont.replace('/','') port_cont = port_cont.strip('\n') ports_rule='\tnetwork ' + proto + ', static_profile.append(ports_rule) #port refers to container's port if int(port_cont) < 1024: static_profile.append('\tcapability net_bind_service, #This capability is needed to bind a socket to well-known ports\n') if user1 in line: line = line.strip('\n') line = line.split(' ') user1_counter+=1 user1_names.append(line[1]) if user2 in line: line = line.strip('\n') line = line.split(' ') user2_counter+=1 user2_names.append(line[2]) if chmod in line: line = line.strip('\n') line = line.split(' ') chmod_path = line[len(line)-1] chmod_permission = list(line[len(line)-2]) if chmod_permission[0] == 'u': owner = line[len(line)-2].split('+') if chmod_permission[0] == '1': owner = 'ix' if chmod_permission[0] == '2': owner = 'w' if chmod_permission[0] == '3': owner = 'wix' if chmod_permission[0] == '4': owner = 'r' if chmod_permission[0] == '5': owner = 'rix' if chmod_permission[0] == '6': owner = 'rw' if chmod_permission[0] == '7': owner = 'rwix' if chmod_permission[2] == 'u': others = line[len(line)-2].split('+') if chmod_permission[2] == '1': others = 'ix' if chmod_permission[2] == '2': others = 'w' if chmod_permission[2] == '3': others = 'wix' if chmod_permission[2] == '4': others = 'r' if chmod_permission[2] == '5': others = 'rix' if chmod_permission[2] == '6': others = 'rw' if chmod_permission[2] == '7': others = 'rwix' chmod_owner = '\towner ' + chmod_path + ' ' + owner + ',\n' #Others' permissions chmod_others = '\t' + chmod_path + ' ' + others + ',\n' static_profile.append(chmod_owner) static_profile.append(chmod_others) if user1_counter>1: static_profile.append(setuid_setgid_rule) if user2_counter==1: if user1_counter==1: if user1_names[0]!=user2_names[0]: static_profile.append(setuid_setgid_rule) else: static_profile.append(setuid_setgid_rule) if user2_counter>1: static_profile.append(setuid_setgid_rule) all_capabilities = ['audit_control', 'audit_write', 'chown', 'dac_override', 'dac_read_search', 'fowner', 'fsetid', 'kill', 'ipc_lock', 'ipc_owner', 'lease', 'linux_immutable', 'mac_admin', 'mac_override', 'mknod', 'net_admin', 'net_bind_service', 'net_broadcast', 'net_raw', 'setgid', 'setpcap', 'setuid', 'sys_admin', 'sys_boot', 'sys_chroot', 'sys_module', 'sys_nice', 'sys_pacct', 'sys_ptrace', 'sys_rawio', 'sys_resource', 'sys_time', 'sys_tty_config', 'setfcap'] dockercompose = str(sys.argv[2]) with open(dockercompose,'r') as infile: data = infile.readlines() network = 'ports:' expose = 'expose:' mount = 'volumes:' capability = 'cap_add:' capability_deny = 'cap_drop:' ulimit = 'ulimits' for i in xrange(len(data)): if network in data[i]: z = i while ('-' in data[z+1]): ports = data[z+1].strip() if 'udp' in ports: proto='udp' else: proto='tcp' ports = ports.replace(proto,'') ports = ports.replace('/','') ports = ports.strip('\n') ports = ports.strip('"') if ':' in ports: ports = ports.split(':') port_host = ports[0].strip('-') port_host = port_host.strip() port_host = port_host.strip('"') port_container = ports[1] else: port_container = ports if int(port_container) < 1024: #In order for an app to bind to ports < 1024 capability net bind service is needed static_profile.append('\tcapability net_bind_service, #bind_rule = '\tnetwork bind ' + port_host + ' to ' + port_container + ',\n' NOT SUPPORTED YET static_profile.append('\tnetwork ' + proto + ', z = z+1 if expose in data[i]: z = i while ('-' in data[z+1]): #checking for multiple ports (same with volumes, capabilities etc) port = data[z+1].strip() if 'udp' in ports: proto='udp' else: proto='tcp' port = port.replace(proto, '') port = port.replace('/','') port = port.strip('\n') port = port.strip('"') if int(port) < 1024: #In order for an app to bind to ports < 1024 capability net bind service is needed static_profile.append('\tcapability net_bind_service, #This capability is needed to bind a socket to well-known ports\n') static_profile.append('\tnetwork ' + proto + ', #Allowing networking with ports forwarding\n') z = z+1 if mount in data[i]: z = i while ('-' in data[z+1]): src_mntpnt = data[z+1].strip() src_mntpnt = src_mntpnt.strip('"') src_mntpnt = src_mntpnt.split(':') src = src_mntpnt[0].strip('-') src = src.strip() src = src.strip('"') mntpnt = src_mntpnt[1] if (mntpnt.endswith('/')): mntpnt = mntpnt.rstrip('/') #If source does not start with / then it is one of the following #Relative path . -> pwd #Relative path .. -> father of pwd #Not a path but a named volume #So we change it into the real host path if (src.startswith('..')): src = pwd_dir elif (src.startswith('.')): src = pre_pwd elif (not src.startswith('/')): src="/var/lib/docker/volumes/" + current_dir + "_" + src + "/_data" #If there is a mount option: if len(src_mntpnt)==3: option = src_mntpnt[2] if 'ro' in option: ro_rule = '\tdeny ' + mntpnt + ' w,\n' static_profile.append(ro_rule) mount_rule = '\tmount options=ro ' + src + ' -> ' + mntpnt + ', #Bind host volume to docker container volume\n' file_mnt_rule = '\t' + mntpnt + '/* r,\n' else: mount_rule = '\tmount ' + src + ' -> ' + mntpnt + ', #Bind host volume to docker container volume\n' file_mnt_rule = '\t' + mntpnt + '/* rw,\n' else: mount_rule = '\tmount ' + src + ' -> ' + mntpnt + ', #Bind host volume to docker container volume\n' file_mnt_rule = '\t' + mntpnt + '/* rw,\n' if mntpnt == '': #Then it was root's dir and we stripped of the / mntpnt = '/' umount_rule = '\tdeny umount ' + mntpnt + ', #Disallow anybody that wants to break this mountpoint\n' remount_rule = '\tdeny remount '+ mntpnt + ', #Disallow anybody that wants to remount this mountpoint\n' static_profile.append(mount_rule) static_profile.append(umount_rule) static_profile.append(remount_rule) static_profile.append(file_mnt_rule) z = z+1 #If docker.sock is mounted in one of the following ways, deny capabilities setuid and setgid so the user won't be able to start a new login session if src=='/': static_profile.append(deny_setuid_setgid_rule) else: if (src.endswith('/')): src = src.rstrip('/') if src=='/var': static_profile.append(deny_setuid_setgid_rule) if src=='/var/run': static_profile.append(deny_setuid_setgid_rule) if src=='/var/run/docker.sock': static_profile.append(deny_setuid_setgid_rule) if capability in data[i]: z = i while ('-' in data[z+1]): x = data[z+1].strip() x = x.strip('-') x = x.strip() if x=='ALL': cap = '\tcapability, #Add all capabilities\n' static_profile.append(cap) else: x = x.lower() cap = '\tcapability ' + x + ',\n' static_profile.append(cap) z = z+1 if capability_deny in data[i]: z = i while ('-' in data[z+1]): x = data[z+1].strip() x = x.strip('-') x = x.strip() if x=='ALL': cap = '\tdeny capability, #Drop all capabilities\n' static_profile.append(cap) else: x = x.lower() cap = '\tdeny capability ' + x + ',\n' static_profile.append(cap) z = z+1 if ulimit in data[i]: z = i+1; my_ulimit = data[z].strip() my_ulimit = my_ulimit.strip(":") slimits = data[z+1].split(':') soft = slimits[1].strip() hlimits = data[z+2].split(':') hard = hlimits[1].strip() #TODO More than one ulimits #TODO Single value ulimit (this is hard limit) ulimit_rule = "\tset rlimit " + my_ulimit + " <= " + hard + ",\n" static_profile.append(ulimit_rule) z = z+3 #-------Static profile is ready-------- #Delete duplicate rules by converting list to set. Convert back to list to keep the order of the beggining and ending of a profile #This is the way to delete duplicates, when we don't care about the order static_profile = list(set(static_profile)) #Add the beggining and ending of the profile #beggining static_profile.insert(0, '#include <tunables/global>\n\nprofile static_profile flags=(attach_disconnected,mediate_deleted) {\n\n') #ending static_profile.append('}\n') #Output with open('static_profile', 'w') as outfile: outfile.writelines( static_profile )
false
true
f725bf9e067d8091eae026f29cdbe029061aaa52
492
py
Python
leetcode/_27.py
simonzhang0428/LeetCode
7daee7572d8235a34071aa831452ed5d0e93d947
[ "Apache-2.0" ]
2
2021-07-09T23:22:25.000Z
2021-07-27T23:15:52.000Z
leetcode/_27.py
simonzhang0428/LeetCode
7daee7572d8235a34071aa831452ed5d0e93d947
[ "Apache-2.0" ]
null
null
null
leetcode/_27.py
simonzhang0428/LeetCode
7daee7572d8235a34071aa831452ed5d0e93d947
[ "Apache-2.0" ]
null
null
null
""" idx 0 1 2 3 val = 3 -> ret 2, [2, 2] elm 2 2 2 3 i idx i: all elements to the left hand side of i (including) are the result to return j: current index to scan whole input array res = 0 """ class Solution: def removeElement(self, nums: List[int], val: int) -> int: idx = 0 for i in range(len(nums)): if nums[i] != val: nums[idx] = nums[i] idx += 1 return idx
25.894737
79
0.481707
class Solution: def removeElement(self, nums: List[int], val: int) -> int: idx = 0 for i in range(len(nums)): if nums[i] != val: nums[idx] = nums[i] idx += 1 return idx
true
true
f725c0b724d8f884150602fbe330761c2b73e84f
576
py
Python
quiz/migrations/0013_tester.py
Rakesh10021997/UBF_backend
354942bb708f669211674f5a327ac8eafe1584df
[ "MIT" ]
null
null
null
quiz/migrations/0013_tester.py
Rakesh10021997/UBF_backend
354942bb708f669211674f5a327ac8eafe1584df
[ "MIT" ]
null
null
null
quiz/migrations/0013_tester.py
Rakesh10021997/UBF_backend
354942bb708f669211674f5a327ac8eafe1584df
[ "MIT" ]
null
null
null
# Generated by Django 2.2 on 2020-10-07 13:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('quiz', '0012_quiz_answerkey'), ] operations = [ migrations.CreateModel( name='Tester', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=10)), ('timestamp', models.DateTimeField(auto_now_add=True)), ], ), ]
26.181818
114
0.578125
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('quiz', '0012_quiz_answerkey'), ] operations = [ migrations.CreateModel( name='Tester', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=10)), ('timestamp', models.DateTimeField(auto_now_add=True)), ], ), ]
true
true
f725c116b568bd7ea26a4fe0e7a8944cb0a5794f
252
py
Python
Assignment 2/13.Dictionary.py
poojavaibhavsahu/Pooja_Python
58122bfa8586883145042b11fe1cc013c803ab4f
[ "bzip2-1.0.6" ]
null
null
null
Assignment 2/13.Dictionary.py
poojavaibhavsahu/Pooja_Python
58122bfa8586883145042b11fe1cc013c803ab4f
[ "bzip2-1.0.6" ]
null
null
null
Assignment 2/13.Dictionary.py
poojavaibhavsahu/Pooja_Python
58122bfa8586883145042b11fe1cc013c803ab4f
[ "bzip2-1.0.6" ]
null
null
null
size=int(input("enter size=")) dict1={} for i in range(1,size+1): subjects = input("enter subjects=") marks = int(input("enter marks=")) dict1[subjects]=marks print(dict1) for subjects,marks in dict1.items(): print(subjects,"=",marks)
25.2
39
0.65873
size=int(input("enter size=")) dict1={} for i in range(1,size+1): subjects = input("enter subjects=") marks = int(input("enter marks=")) dict1[subjects]=marks print(dict1) for subjects,marks in dict1.items(): print(subjects,"=",marks)
true
true
f725c1908ba5d833377d25ff6bb9702e9e24329f
2,983
py
Python
python/tvm/runtime/object.py
jheo4/incubator-tvm
c4c61cb766608fb2f0fd8c9facc480a43afed3f5
[ "Apache-2.0" ]
4
2018-01-09T07:35:33.000Z
2021-04-20T05:52:50.000Z
python/tvm/runtime/object.py
jheo4/incubator-tvm
c4c61cb766608fb2f0fd8c9facc480a43afed3f5
[ "Apache-2.0" ]
1
2020-04-17T10:53:14.000Z
2020-04-17T10:53:14.000Z
python/tvm/runtime/object.py
jheo4/incubator-tvm
c4c61cb766608fb2f0fd8c9facc480a43afed3f5
[ "Apache-2.0" ]
3
2020-12-10T23:21:18.000Z
2020-12-11T01:04:50.000Z
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name, unused-import """Runtime Object API""" import ctypes from tvm._ffi.base import _FFI_MODE, _RUNTIME_ONLY, check_call, _LIB, c_str from . import _ffi_api, _ffi_node_api try: # pylint: disable=wrong-import-position,unused-import if _FFI_MODE == "ctypes": raise ImportError() from tvm._ffi._cy3.core import _set_class_object, _set_class_object_generic from tvm._ffi._cy3.core import ObjectBase except (RuntimeError, ImportError): # pylint: disable=wrong-import-position,unused-import from tvm._ffi._ctypes.packed_func import _set_class_object, _set_class_object_generic from tvm._ffi._ctypes.object import ObjectBase def _new_object(cls): """Helper function for pickle""" return cls.__new__(cls) class Object(ObjectBase): """Base class for all tvm's runtime objects.""" def __repr__(self): return _ffi_node_api.AsRepr(self) def __dir__(self): fnames = _ffi_node_api.NodeListAttrNames(self) size = fnames(-1) return [fnames(i) for i in range(size)] def __getattr__(self, name): try: return _ffi_node_api.NodeGetAttr(self, name) except AttributeError: raise AttributeError( "%s has no attribute %s" % (str(type(self)), name)) def __hash__(self): return _ffi_api.ObjectHash(self) def __eq__(self, other): return self.same_as(other) def __ne__(self, other): return not self.__eq__(other) def __reduce__(self): cls = type(self) return (_new_object, (cls, ), self.__getstate__()) def __getstate__(self): handle = self.handle if handle is not None: return {'handle': _ffi_node_api.SaveJSON(self)} return {'handle': None} def __setstate__(self, state): # pylint: disable=assigning-non-slot, assignment-from-no-return handle = state['handle'] if handle is not None: json_str = handle other = _ffi_node_api.LoadJSON(json_str) self.handle = other.handle other.handle = None else: self.handle = None _set_class_object(Object)
33.144444
89
0.686222
import ctypes from tvm._ffi.base import _FFI_MODE, _RUNTIME_ONLY, check_call, _LIB, c_str from . import _ffi_api, _ffi_node_api try: if _FFI_MODE == "ctypes": raise ImportError() from tvm._ffi._cy3.core import _set_class_object, _set_class_object_generic from tvm._ffi._cy3.core import ObjectBase except (RuntimeError, ImportError): from tvm._ffi._ctypes.packed_func import _set_class_object, _set_class_object_generic from tvm._ffi._ctypes.object import ObjectBase def _new_object(cls): return cls.__new__(cls) class Object(ObjectBase): def __repr__(self): return _ffi_node_api.AsRepr(self) def __dir__(self): fnames = _ffi_node_api.NodeListAttrNames(self) size = fnames(-1) return [fnames(i) for i in range(size)] def __getattr__(self, name): try: return _ffi_node_api.NodeGetAttr(self, name) except AttributeError: raise AttributeError( "%s has no attribute %s" % (str(type(self)), name)) def __hash__(self): return _ffi_api.ObjectHash(self) def __eq__(self, other): return self.same_as(other) def __ne__(self, other): return not self.__eq__(other) def __reduce__(self): cls = type(self) return (_new_object, (cls, ), self.__getstate__()) def __getstate__(self): handle = self.handle if handle is not None: return {'handle': _ffi_node_api.SaveJSON(self)} return {'handle': None} def __setstate__(self, state): handle = state['handle'] if handle is not None: json_str = handle other = _ffi_node_api.LoadJSON(json_str) self.handle = other.handle other.handle = None else: self.handle = None _set_class_object(Object)
true
true
f725c257cf9a811b1104a4abcf2cefc06d1747df
1,212
py
Python
app/views/schemas.py
KaiserBloo/memegen
ee757e916aa37176a6562021cee9bb0ce0bdad0d
[ "MIT" ]
null
null
null
app/views/schemas.py
KaiserBloo/memegen
ee757e916aa37176a6562021cee9bb0ce0bdad0d
[ "MIT" ]
null
null
null
app/views/schemas.py
KaiserBloo/memegen
ee757e916aa37176a6562021cee9bb0ce0bdad0d
[ "MIT" ]
null
null
null
from dataclasses import dataclass from datetime import datetime @dataclass class AuthResponse: email: str image_access: bool search_access: bool created: datetime modified: datetime @dataclass class FontResponse: filename: str id: str alias: str _self: str @dataclass class MemeRequest: template_id: str style: list[str] text: list[str] font: str extension: str redirect: bool @dataclass class CustomRequest: background: str style: str text: list[str] font: str extension: str redirect: bool @dataclass class MemeTemplateRequest: style: list[str] text: list[str] font: str extension: str redirect: bool @dataclass class AutomaticRequest: text: str safe: bool redirect: bool @dataclass class MemeResponse: url: str @dataclass class ExampleResponse: url: str template: str @dataclass class _Example: text: list[str] url: str @dataclass class TemplateResponse: id: str name: str lines: int overlays: int styles: list[str] blank: str example: _Example source: str _self: str @dataclass class ErrorResponse: error: str
13.318681
33
0.664191
from dataclasses import dataclass from datetime import datetime @dataclass class AuthResponse: email: str image_access: bool search_access: bool created: datetime modified: datetime @dataclass class FontResponse: filename: str id: str alias: str _self: str @dataclass class MemeRequest: template_id: str style: list[str] text: list[str] font: str extension: str redirect: bool @dataclass class CustomRequest: background: str style: str text: list[str] font: str extension: str redirect: bool @dataclass class MemeTemplateRequest: style: list[str] text: list[str] font: str extension: str redirect: bool @dataclass class AutomaticRequest: text: str safe: bool redirect: bool @dataclass class MemeResponse: url: str @dataclass class ExampleResponse: url: str template: str @dataclass class _Example: text: list[str] url: str @dataclass class TemplateResponse: id: str name: str lines: int overlays: int styles: list[str] blank: str example: _Example source: str _self: str @dataclass class ErrorResponse: error: str
true
true
f725c299e78ae93819633c99b0ca91ef4159c618
159
py
Python
reviewboard/changedescs/evolutions/__init__.py
clach04/reviewboard
994e5cbcb7709bf2de851d5ecd261d64a4091f26
[ "MIT" ]
1
2015-09-11T15:50:17.000Z
2015-09-11T15:50:17.000Z
reviewboard/changedescs/evolutions/__init__.py
clach04/reviewboard
994e5cbcb7709bf2de851d5ecd261d64a4091f26
[ "MIT" ]
null
null
null
reviewboard/changedescs/evolutions/__init__.py
clach04/reviewboard
994e5cbcb7709bf2de851d5ecd261d64a4091f26
[ "MIT" ]
null
null
null
from django.conf import settings SEQUENCE = [] if settings.DATABASES['default']['ENGINE'].endswith('mysql'): SEQUENCE.append('fields_changed_longtext')
19.875
61
0.742138
from django.conf import settings SEQUENCE = [] if settings.DATABASES['default']['ENGINE'].endswith('mysql'): SEQUENCE.append('fields_changed_longtext')
true
true
f725c3671a76f70791f2bc04f5876fb34af22787
2,075
py
Python
examples/market_radio.py
mnovikov1/cryptology-ws-client-python
2ff019637854d5f92c1151065c939bc85df17cda
[ "MIT" ]
null
null
null
examples/market_radio.py
mnovikov1/cryptology-ws-client-python
2ff019637854d5f92c1151065c939bc85df17cda
[ "MIT" ]
null
null
null
examples/market_radio.py
mnovikov1/cryptology-ws-client-python
2ff019637854d5f92c1151065c939bc85df17cda
[ "MIT" ]
4
2019-04-29T10:12:00.000Z
2019-11-18T10:00:43.000Z
import asyncio import cryptology import logging import os from aiohttp import WSServerHandshakeError from datetime import datetime from decimal import Decimal from pathlib import Path from typing import Optional SERVER = os.getenv('SERVER', 'wss://marketdata.cryptology.com') NAME = Path(__file__).stem logging.basicConfig(level=logging.INFO) logger = logging.getLogger(NAME) async def read_order_book(order_id: int, pair: str, buy: dict, sell: dict) -> None: if pair in ('BTC_USD', 'ETH_USD', 'BTC_EUR', 'ETH_EUR',): if len(buy) == 0: logger.error('%s buy order book has size %i @ order %i', pair, len(buy), order_id) if len(sell) == 0: logger.error('%s sell order book has size %i @ order %i', pair, len(sell), order_id) logger.info(f'order book @{order_id}') logger.info(f'sell orders of {pair} @{order_id}: {sell}') logger.info(f'buy orders of {pair} @{order_id}: {buy}') async def read_trades(ts: datetime, order_id: int, pair: str, amount: Decimal, price: Decimal) -> None: currencies = pair.split("_") logger.info(f'{ts}@{order_id} a buy of {amount} {currencies[0]} for {price} {currencies[1]} took place') async def main(loop: Optional[asyncio.AbstractEventLoop] = None): logger.info(f'connecting to {SERVER}') while True: try: await cryptology.run_market_data( ws_addr=SERVER, market_data_callback=None, order_book_callback=read_order_book, trades_callback=read_trades, loop=loop ) except cryptology.exceptions.RateLimit: logger.error('rate limit reached') except cryptology.exceptions.ServerRestart: logger.warning('server restart') await asyncio.sleep(80) except (cryptology.exceptions.Disconnected, WSServerHandshakeError) as ex: logger.error(ex) await asyncio.sleep(30) if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(main(loop=loop))
34.583333
108
0.654458
import asyncio import cryptology import logging import os from aiohttp import WSServerHandshakeError from datetime import datetime from decimal import Decimal from pathlib import Path from typing import Optional SERVER = os.getenv('SERVER', 'wss://marketdata.cryptology.com') NAME = Path(__file__).stem logging.basicConfig(level=logging.INFO) logger = logging.getLogger(NAME) async def read_order_book(order_id: int, pair: str, buy: dict, sell: dict) -> None: if pair in ('BTC_USD', 'ETH_USD', 'BTC_EUR', 'ETH_EUR',): if len(buy) == 0: logger.error('%s buy order book has size %i @ order %i', pair, len(buy), order_id) if len(sell) == 0: logger.error('%s sell order book has size %i @ order %i', pair, len(sell), order_id) logger.info(f'order book @{order_id}') logger.info(f'sell orders of {pair} @{order_id}: {sell}') logger.info(f'buy orders of {pair} @{order_id}: {buy}') async def read_trades(ts: datetime, order_id: int, pair: str, amount: Decimal, price: Decimal) -> None: currencies = pair.split("_") logger.info(f'{ts}@{order_id} a buy of {amount} {currencies[0]} for {price} {currencies[1]} took place') async def main(loop: Optional[asyncio.AbstractEventLoop] = None): logger.info(f'connecting to {SERVER}') while True: try: await cryptology.run_market_data( ws_addr=SERVER, market_data_callback=None, order_book_callback=read_order_book, trades_callback=read_trades, loop=loop ) except cryptology.exceptions.RateLimit: logger.error('rate limit reached') except cryptology.exceptions.ServerRestart: logger.warning('server restart') await asyncio.sleep(80) except (cryptology.exceptions.Disconnected, WSServerHandshakeError) as ex: logger.error(ex) await asyncio.sleep(30) if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(main(loop=loop))
true
true
f725c3bd2b571aa08f3545969b2bc56209e7455d
93
py
Python
pyshiki/__init__.py
vadyur/PyShiki
e6a678056d46b15969af64895911ae0a2df4df69
[ "MIT" ]
null
null
null
pyshiki/__init__.py
vadyur/PyShiki
e6a678056d46b15969af64895911ae0a2df4df69
[ "MIT" ]
null
null
null
pyshiki/__init__.py
vadyur/PyShiki
e6a678056d46b15969af64895911ae0a2df4df69
[ "MIT" ]
1
2021-04-12T18:48:38.000Z
2021-04-12T18:48:38.000Z
#!/usr/bin/env python3 #-*- coding: UTF-8 -*- from .shikimoriapi import * __all__ = ['Api']
15.5
27
0.623656
from .shikimoriapi import * __all__ = ['Api']
true
true
f725c440dafb3649fab82e15f86d026ee595aa5b
2,771
py
Python
src/formattedcode/format_json.py
chetanya-shrimali/scancode-toolkit
a1a22fb225cbeb211bd6f92272a46f1351f57d6b
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
src/formattedcode/format_json.py
chetanya-shrimali/scancode-toolkit
a1a22fb225cbeb211bd6f92272a46f1351f57d6b
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
src/formattedcode/format_json.py
chetanya-shrimali/scancode-toolkit
a1a22fb225cbeb211bd6f92272a46f1351f57d6b
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
# # Copyright (c) 2017 nexB Inc. and others. All rights reserved. # http://nexb.com and https://github.com/nexB/scancode-toolkit/ # The ScanCode software is licensed under the Apache License version 2.0. # Data generated with ScanCode require an acknowledgment. # ScanCode is a trademark of nexB Inc. # # You may not use this software except in compliance with the License. # You may obtain a copy of the License at: http://apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software distributed # under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR # CONDITIONS OF ANY KIND, either express or implied. See the License for the # specific language governing permissions and limitations under the License. # # When you publish or redistribute any data created with ScanCode or any ScanCode # derivative work, you must accompany this data with the following acknowledgment: # # Generated with ScanCode and provided on an "AS IS" BASIS, WITHOUT WARRANTIES # OR CONDITIONS OF ANY KIND, either express or implied. No content created from # ScanCode should be considered or used as legal advice. Consult an Attorney # for any legal advice. # ScanCode is a free software code scanning tool from nexB Inc. and others. # Visit https://github.com/nexB/scancode-toolkit/ for support and download. from __future__ import absolute_import from __future__ import unicode_literals from collections import OrderedDict import simplejson from plugincode.output import scan_output_writer """ Output plugins to write scan results as JSON. """ @scan_output_writer def write_json_compact(files_count, version, notice, scanned_files, options, output_file, *args, **kwargs): """ Write scan output formatted as compact JSON. """ _write_json(files_count, version, notice, scanned_files, options, output_file, pretty=False) @scan_output_writer def write_json_pretty_printed(files_count, version, notice, scanned_files, options, output_file, *args, **kwargs): """ Write scan output formatted as pretty-printed JSON. """ _write_json(files_count, version, notice, scanned_files, options, output_file, pretty=True) def _write_json(files_count, version, notice, scanned_files, options, output_file, pretty=False): scan = OrderedDict([ ('scancode_notice', notice), ('scancode_version', version), ('scancode_options', options), ('files_count', files_count), ('files', scanned_files), ]) kwargs = dict(iterable_as_array=True, encoding='utf-8') if pretty: kwargs['indent'] = 2 * ' ' else: kwargs['separators'] = (',', ':',) output_file.write(unicode(simplejson.dumps(scan, **kwargs))) output_file.write('\n')
39.028169
114
0.74161
from __future__ import absolute_import from __future__ import unicode_literals from collections import OrderedDict import simplejson from plugincode.output import scan_output_writer @scan_output_writer def write_json_compact(files_count, version, notice, scanned_files, options, output_file, *args, **kwargs): _write_json(files_count, version, notice, scanned_files, options, output_file, pretty=False) @scan_output_writer def write_json_pretty_printed(files_count, version, notice, scanned_files, options, output_file, *args, **kwargs): _write_json(files_count, version, notice, scanned_files, options, output_file, pretty=True) def _write_json(files_count, version, notice, scanned_files, options, output_file, pretty=False): scan = OrderedDict([ ('scancode_notice', notice), ('scancode_version', version), ('scancode_options', options), ('files_count', files_count), ('files', scanned_files), ]) kwargs = dict(iterable_as_array=True, encoding='utf-8') if pretty: kwargs['indent'] = 2 * ' ' else: kwargs['separators'] = (',', ':',) output_file.write(unicode(simplejson.dumps(scan, **kwargs))) output_file.write('\n')
true
true
f725c4a8a7481af6a704ce6b7c4c8af37084a931
7,084
py
Python
clrnet/models/necks/fpn.py
Turoad/CLRNet
51e082db12973943bddefd76fd0d431fcb3350ff
[ "Apache-2.0" ]
18
2022-03-16T07:29:19.000Z
2022-03-31T07:05:37.000Z
clrnet/models/necks/fpn.py
Turoad/CLRNet
51e082db12973943bddefd76fd0d431fcb3350ff
[ "Apache-2.0" ]
1
2022-03-16T11:47:13.000Z
2022-03-17T10:15:25.000Z
clrnet/models/necks/fpn.py
Turoad/CLRNet
51e082db12973943bddefd76fd0d431fcb3350ff
[ "Apache-2.0" ]
1
2022-03-25T14:49:58.000Z
2022-03-25T14:49:58.000Z
import warnings import torch import torch.nn as nn import torch.nn.functional as F from mmcv.cnn import ConvModule from ..registry import NECKS @NECKS.register_module class FPN(nn.Module): def __init__(self, in_channels, out_channels, num_outs, start_level=0, end_level=-1, add_extra_convs=False, extra_convs_on_inputs=True, relu_before_extra_convs=False, no_norm_on_lateral=False, conv_cfg=None, norm_cfg=None, attention=False, act_cfg=None, upsample_cfg=dict(mode='nearest'), init_cfg=dict(type='Xavier', layer='Conv2d', distribution='uniform'), cfg=None): super(FPN, self).__init__() assert isinstance(in_channels, list) self.in_channels = in_channels self.out_channels = out_channels self.num_ins = len(in_channels) self.num_outs = num_outs self.attention = attention self.relu_before_extra_convs = relu_before_extra_convs self.no_norm_on_lateral = no_norm_on_lateral self.upsample_cfg = upsample_cfg.copy() if end_level == -1: self.backbone_end_level = self.num_ins assert num_outs >= self.num_ins - start_level else: # if end_level < inputs, no extra level is allowed self.backbone_end_level = end_level assert end_level <= len(in_channels) assert num_outs == end_level - start_level self.start_level = start_level self.end_level = end_level self.add_extra_convs = add_extra_convs assert isinstance(add_extra_convs, (str, bool)) if isinstance(add_extra_convs, str): # Extra_convs_source choices: 'on_input', 'on_lateral', 'on_output' assert add_extra_convs in ('on_input', 'on_lateral', 'on_output') elif add_extra_convs: # True if extra_convs_on_inputs: # TODO: deprecate `extra_convs_on_inputs` warnings.simplefilter('once') warnings.warn( '"extra_convs_on_inputs" will be deprecated in v2.9.0,' 'Please use "add_extra_convs"', DeprecationWarning) self.add_extra_convs = 'on_input' else: self.add_extra_convs = 'on_output' self.lateral_convs = nn.ModuleList() self.fpn_convs = nn.ModuleList() for i in range(self.start_level, self.backbone_end_level): l_conv = ConvModule( in_channels[i], out_channels, 1, conv_cfg=conv_cfg, norm_cfg=norm_cfg if not self.no_norm_on_lateral else None, act_cfg=act_cfg, inplace=False) fpn_conv = ConvModule(out_channels, out_channels, 3, padding=1, conv_cfg=conv_cfg, norm_cfg=norm_cfg, act_cfg=act_cfg, inplace=False) self.lateral_convs.append(l_conv) self.fpn_convs.append(fpn_conv) # add extra conv layers (e.g., RetinaNet) extra_levels = num_outs - self.backbone_end_level + self.start_level if self.add_extra_convs and extra_levels >= 1: for i in range(extra_levels): if i == 0 and self.add_extra_convs == 'on_input': in_channels = self.in_channels[self.backbone_end_level - 1] else: in_channels = out_channels extra_fpn_conv = ConvModule(in_channels, out_channels, 3, stride=2, padding=1, conv_cfg=conv_cfg, norm_cfg=norm_cfg, act_cfg=act_cfg, inplace=False) self.fpn_convs.append(extra_fpn_conv) def forward(self, inputs): """Forward function.""" assert len(inputs) >= len(self.in_channels) if len(inputs) > len(self.in_channels): for _ in range(len(inputs) - len(self.in_channels)): del inputs[0] # build laterals laterals = [ lateral_conv(inputs[i + self.start_level]) for i, lateral_conv in enumerate(self.lateral_convs) ] # build top-down path used_backbone_levels = len(laterals) for i in range(used_backbone_levels - 1, 0, -1): # In some cases, fixing `scale factor` (e.g. 2) is preferred, but # it cannot co-exist with `size` in `F.interpolate`. if 'scale_factor' in self.upsample_cfg: laterals[i - 1] += F.interpolate(laterals[i], **self.upsample_cfg) else: prev_shape = laterals[i - 1].shape[2:] laterals[i - 1] += F.interpolate(laterals[i], size=prev_shape, **self.upsample_cfg) # build outputs # part 1: from original levels outs = [ self.fpn_convs[i](laterals[i]) for i in range(used_backbone_levels) ] # part 2: add extra levels if self.num_outs > len(outs): # use max pool to get more levels on top of outputs # (e.g., Faster R-CNN, Mask R-CNN) if not self.add_extra_convs: for i in range(self.num_outs - used_backbone_levels): outs.append(F.max_pool2d(outs[-1], 1, stride=2)) # add conv layers on top of original feature maps (RetinaNet) else: if self.add_extra_convs == 'on_input': extra_source = inputs[self.backbone_end_level - 1] elif self.add_extra_convs == 'on_lateral': extra_source = laterals[-1] elif self.add_extra_convs == 'on_output': extra_source = outs[-1] else: raise NotImplementedError outs.append(self.fpn_convs[used_backbone_levels](extra_source)) for i in range(used_backbone_levels + 1, self.num_outs): if self.relu_before_extra_convs: outs.append(self.fpn_convs[i](F.relu(outs[-1]))) else: outs.append(self.fpn_convs[i](outs[-1])) return tuple(outs)
42.166667
79
0.511011
import warnings import torch import torch.nn as nn import torch.nn.functional as F from mmcv.cnn import ConvModule from ..registry import NECKS @NECKS.register_module class FPN(nn.Module): def __init__(self, in_channels, out_channels, num_outs, start_level=0, end_level=-1, add_extra_convs=False, extra_convs_on_inputs=True, relu_before_extra_convs=False, no_norm_on_lateral=False, conv_cfg=None, norm_cfg=None, attention=False, act_cfg=None, upsample_cfg=dict(mode='nearest'), init_cfg=dict(type='Xavier', layer='Conv2d', distribution='uniform'), cfg=None): super(FPN, self).__init__() assert isinstance(in_channels, list) self.in_channels = in_channels self.out_channels = out_channels self.num_ins = len(in_channels) self.num_outs = num_outs self.attention = attention self.relu_before_extra_convs = relu_before_extra_convs self.no_norm_on_lateral = no_norm_on_lateral self.upsample_cfg = upsample_cfg.copy() if end_level == -1: self.backbone_end_level = self.num_ins assert num_outs >= self.num_ins - start_level else: self.backbone_end_level = end_level assert end_level <= len(in_channels) assert num_outs == end_level - start_level self.start_level = start_level self.end_level = end_level self.add_extra_convs = add_extra_convs assert isinstance(add_extra_convs, (str, bool)) if isinstance(add_extra_convs, str): assert add_extra_convs in ('on_input', 'on_lateral', 'on_output') elif add_extra_convs: if extra_convs_on_inputs: warnings.simplefilter('once') warnings.warn( '"extra_convs_on_inputs" will be deprecated in v2.9.0,' 'Please use "add_extra_convs"', DeprecationWarning) self.add_extra_convs = 'on_input' else: self.add_extra_convs = 'on_output' self.lateral_convs = nn.ModuleList() self.fpn_convs = nn.ModuleList() for i in range(self.start_level, self.backbone_end_level): l_conv = ConvModule( in_channels[i], out_channels, 1, conv_cfg=conv_cfg, norm_cfg=norm_cfg if not self.no_norm_on_lateral else None, act_cfg=act_cfg, inplace=False) fpn_conv = ConvModule(out_channels, out_channels, 3, padding=1, conv_cfg=conv_cfg, norm_cfg=norm_cfg, act_cfg=act_cfg, inplace=False) self.lateral_convs.append(l_conv) self.fpn_convs.append(fpn_conv) extra_levels = num_outs - self.backbone_end_level + self.start_level if self.add_extra_convs and extra_levels >= 1: for i in range(extra_levels): if i == 0 and self.add_extra_convs == 'on_input': in_channels = self.in_channels[self.backbone_end_level - 1] else: in_channels = out_channels extra_fpn_conv = ConvModule(in_channels, out_channels, 3, stride=2, padding=1, conv_cfg=conv_cfg, norm_cfg=norm_cfg, act_cfg=act_cfg, inplace=False) self.fpn_convs.append(extra_fpn_conv) def forward(self, inputs): assert len(inputs) >= len(self.in_channels) if len(inputs) > len(self.in_channels): for _ in range(len(inputs) - len(self.in_channels)): del inputs[0] laterals = [ lateral_conv(inputs[i + self.start_level]) for i, lateral_conv in enumerate(self.lateral_convs) ] used_backbone_levels = len(laterals) for i in range(used_backbone_levels - 1, 0, -1): if 'scale_factor' in self.upsample_cfg: laterals[i - 1] += F.interpolate(laterals[i], **self.upsample_cfg) else: prev_shape = laterals[i - 1].shape[2:] laterals[i - 1] += F.interpolate(laterals[i], size=prev_shape, **self.upsample_cfg) outs = [ self.fpn_convs[i](laterals[i]) for i in range(used_backbone_levels) ] if self.num_outs > len(outs): if not self.add_extra_convs: for i in range(self.num_outs - used_backbone_levels): outs.append(F.max_pool2d(outs[-1], 1, stride=2)) else: if self.add_extra_convs == 'on_input': extra_source = inputs[self.backbone_end_level - 1] elif self.add_extra_convs == 'on_lateral': extra_source = laterals[-1] elif self.add_extra_convs == 'on_output': extra_source = outs[-1] else: raise NotImplementedError outs.append(self.fpn_convs[used_backbone_levels](extra_source)) for i in range(used_backbone_levels + 1, self.num_outs): if self.relu_before_extra_convs: outs.append(self.fpn_convs[i](F.relu(outs[-1]))) else: outs.append(self.fpn_convs[i](outs[-1])) return tuple(outs)
true
true
f725c51873bca756304f94c52f620a6f9fb9ab38
44,255
py
Python
pdb2sql/StructureSimilarity.py
DarioMarzella/pdb2sql
64d5d4f27fb67a0ff41221bcd27667237048bb3f
[ "Apache-2.0" ]
null
null
null
pdb2sql/StructureSimilarity.py
DarioMarzella/pdb2sql
64d5d4f27fb67a0ff41221bcd27667237048bb3f
[ "Apache-2.0" ]
null
null
null
pdb2sql/StructureSimilarity.py
DarioMarzella/pdb2sql
64d5d4f27fb67a0ff41221bcd27667237048bb3f
[ "Apache-2.0" ]
null
null
null
import warnings import numpy as np from .pdb2sqlcore import pdb2sql from .interface import interface from .superpose import get_trans_vect, get_rotation_matrix, superpose_selection from . import transform import os import pickle class StructureSimilarity(object): def __init__(self, decoy, ref, verbose=False, enforce_residue_matching=True): """Compute structure similarity between two structures. This class allows to compute the i-RMSD, L-RMSD, Fnat and DockQ score of a given conformation. This can be a replacement for ProFIT. Note that the calculation of the zones are done by the class itself and does not require any extra input. Note: 1. The decoy and pdb must have consistent residue numbering. 2. The lzone files here are different with those from ProFit. lzone: here need only zone residues for fitting, no need of residue for rms calculation. RMS residues are automatically assumed as the other chain, Be careful with ProFit zone files that contain RZONE/RATOMS. 3. Missing residues/atoms will be ignored. Args: decoy : pdb file or sql database of the decoy conformation ref : pdb file or sql database of the reference conformation verbose (bool) : verbosity option Examples: >>> from pdb2sql import StructureSimilarity >>> decoy = '1AK4_5w.pdb' >>> ref = '1AK4.pdb' >>> sim = StructureSimilarity(decoy,ref) >>> irmsd_fast = sim.compute_irmsd_fast(method='svd', ... izone='1AK4.izone') >>> irmsd = sim.compute_irmsd_pdb2sql(method='svd', ... izone='1AK4.izone') >>> lrmsd_fast = sim.compute_lrmsd_fast(method='svd', ... lzone='1AK4.lzone',check=True) >>> lrmsd = sim.compute_lrmsd_pdb2sql(exportpath=None, ... method='svd') >>> Fnat = sim.compute_fnat_pdb2sql() >>> Fnat_fast = sim.compute_fnat_fast( ... ref_pairs='1AK4.ref_pairs') >>> dockQ = sim.compute_DockQScore(Fnat_fast, ... lrmsd_fast,irmsd_fast) """ self.decoy = decoy self.ref = ref self.verbose = verbose self.origin = [0., 0., 0.] self.enforce_residue_matching = enforce_residue_matching def __repr__(self): return f'{self.__module__}.{self.__class__.__name__}({self.decoy}, {self.ref}, {self.verbose})' def check_residues(self): """Check if the residue numbering matches.""" res_ref = pdb2sql(self.ref).get_residues() res_dec = pdb2sql(self.decoy).get_residues() if res_ref != res_dec: print('Residues are different in the reference and decoy') print('Residues found in %s and not in %s' % (self.ref, self.decoy)) print(set(res_ref).difference(set(res_dec))) print('Residues found in %s and not in %s' % (self.decoy, self.ref)) print(set(res_dec).difference(set(res_ref))) if self.enforce_residue_matching == True: raise ValueError( 'Residue numbering not identical in ref and decoy\n Set enforce_residue_matching=False to bypass this error.') else: warns.Warning('Residue numbering not identical in ref and decoy.') ########################################################################## # # FAST ROUTINE TO COMPUTE THE L-RMSD # Require the precalculation of the lzone # A dedicated routine is implemented to comoute the lzone # if lzone is not given in argument the routine will compute them automatically # ########################################################################## # compute the L-RMSD def compute_lrmsd_fast(self, lzone=None, method='svd', check=True, name=['C', 'CA', 'N', 'O']): """Fast routine to compute the L-RMSD. L-RMSD is computed by aligning the longest chain of the decoy to the one of the reference and computing the RMSD of the shortest chain between decoy and reference. By default, both fitting and rms calculation use only backbone atoms. See reference: DockQ: A Quality Measure for Protein-Protein Docking Models https://doi.org/10.1371/journal.pone.0161879 Args: lzone (None, optional): name of the file containing the zone definition. If None the file will be calculated first. method (str, optional): Method to align the fragments, 'svd' or 'quaternion'. check (bool, optional): Check if the sequences are aligned and fix it if not. Defaults to True. name (list, optional): atom name to include in the zone. Defaults to ['C', 'CA', 'N', 'O'] Returns: float: L-RMSD value of the conformation See also: :meth:`compute_lrmsd_pdb2sql` """ # create/read the lzone file if lzone is None: resData = self.compute_lzone(save_file=False) elif not os.path.isfile(lzone): resData = self.compute_lzone( save_file=True, filename=lzone) else: resData = self.read_zone(lzone) if check or self.enforce_residue_matching: # Note: # 1. get_data_zone_backbone returns in_zone and not_in_zone # here the in_zone defines the zone for fitting, # and not_in_zone defines the zone for rms calculation. self.check_residues() data_decoy_long, data_decoy_short = self.get_data_zone_backbone( self.decoy, resData, return_not_in_zone=True, name=name) data_ref_long, data_ref_short = self.get_data_zone_backbone( self.ref, resData, return_not_in_zone=True, name=name) atom_long = data_ref_long.intersection(data_decoy_long) xyz_decoy_long = self._get_xyz(self.decoy, atom_long) xyz_ref_long = self._get_xyz(self.ref, atom_long) atom_short = data_ref_short.intersection(data_decoy_short) xyz_decoy_short = self._get_xyz(self.decoy, atom_short) xyz_ref_short = self._get_xyz(self.ref, atom_short) # extract the xyz else: xyz_decoy_long, xyz_decoy_short = self.get_xyz_zone_backbone( self.decoy, resData, return_not_in_zone=True, name=name) xyz_ref_long, xyz_ref_short = self.get_xyz_zone_backbone( self.ref, resData, return_not_in_zone=True, name=name) xyz_decoy_short = superpose_selection( xyz_decoy_short, xyz_decoy_long, xyz_ref_long, method) # compute the RMSD return self.get_rmsd(xyz_decoy_short, xyz_ref_short) # compute the lzone file def compute_lzone(self, save_file=True, filename=None): """Compute the zone for L-RMSD calculation. Note: It only provides the zone of long chain(s) which is used for fitting. The zone used for calculating RMSD is defined in the function `compute_lrmsd_fast`. Args: save_file (bool, optional): save the zone file filename (str, optional): name of the file Returns: dict: definition of the zone. """ sql_ref = pdb2sql(self.ref) chains = list(sql_ref.get_chains()) if len(chains) != 2: raise ValueError( 'exactly two chains are needed for lrmsd calculation but we found %d' % len(chains), chains) nA = len(sql_ref.get('x,y,z', chainID=chains[0])) nB = len(sql_ref.get('x,y,z', chainID=chains[1])) # detect which chain is the longest long_chain = chains[0] if nA < nB: long_chain = chains[1] # extract data about the residue data_test = [ tuple(data) for data in sql_ref.get( 'chainID,resSeq', chainID=long_chain)] data_test = sorted(set(data_test)) # close the sql sql_ref._close() if save_file: if filename is None: f = open(self.ref.split('.')[0] + '.lzone', 'w') else: f = open(filename, 'w') for res in data_test: chain = res[0] num = res[1] f.write('zone %s%d-%s%d\n' % (chain, num, chain, num)) f.close() resData = {} for res in data_test: chain = res[0] num = res[1] if chain not in resData.keys(): resData[chain] = [] resData[chain].append(num) return resData ########################################################################## # # FAST ROUTINE TO COMPUTE THE I-RMSD # Require the precalculation of the izone # A dedicated routine is implemented to comoute the izone # if izone is not given in argument the routine will compute them automatcally # ########################################################################## def compute_irmsd_fast(self, izone=None, method='svd', cutoff=10, check=True): """Fast method to compute the i-rmsd. i-RMSD is computed by selecting the backbone atoms of reference interface that is defined as any pair of heavy atoms from two chains within 10Å of each other. Align these backbone atoms as best as possible with their coutner part in the decoy and compute the RMSD. See reference: DockQ: A Quality Measure for Protein-Protein Docking Models https://doi.org/10.1371/journal.pone.0161879 Args: izone (None, optional): file name of the zone. if None the zones will be calculated automatically. method (str, optional): Method to align the fragments, 'svd' or 'quaternion'. cutoff (float, optional): cutoff for the contact atoms check (bool, optional): Check if the sequences are aligned and fix it if not. Should be True. Returns: float: i-RMSD value of the conformation See also: :meth:`compute_irmsd_pdb2sql` """ # read the izone file if izone is None: resData = self.compute_izone(cutoff, save_file=False) elif not os.path.isfile(izone): resData = self.compute_izone( cutoff, save_file=True, filename=izone) else: resData = self.read_zone(izone) if check or self.enforce_residue_matching: self.check_residues() data_decoy = self.get_data_zone_backbone( self.decoy, resData, return_not_in_zone=False) data_ref = self.get_data_zone_backbone( self.ref, resData, return_not_in_zone=False) atom_common = data_ref.intersection(data_decoy) xyz_contact_decoy = self._get_xyz(self.decoy, atom_common) xyz_contact_ref = self._get_xyz(self.ref, atom_common) # extract the xyz else: xyz_contact_decoy = self.get_xyz_zone_backbone( self.decoy, resData) xyz_contact_ref = self.get_xyz_zone_backbone( self.ref, resData) # superpose the fragments xyz_contact_decoy = superpose_selection(xyz_contact_decoy, xyz_contact_decoy, xyz_contact_ref, method) # return the RMSD return self.get_rmsd(xyz_contact_decoy, xyz_contact_ref) def compute_izone(self, cutoff=10.0, save_file=True, filename=None): """Compute the zones for i-rmsd calculationss. Args: cutoff (float, optional): cutoff for the contact atoms save_file (bool, optional): svae file containing the zone filename (str, optional): filename Returns: dict: i-zone definition """ sql_ref = interface(self.ref) chains = list(sql_ref.get_chains()) if len(chains) != 2: raise ValueError( 'exactly two chains are needed for irmsd calculation but we found %d' % len(chains), chains) contact_ref = sql_ref.get_contact_atoms( cutoff=cutoff, extend_to_residue=True, chain1=chains[0], chain2=chains[1]) index_contact_ref = [] for _, v in contact_ref.items(): index_contact_ref += v # get the xyz and atom identifier of the decoy contact atoms data_test = [tuple(data) for data in sql_ref.get( 'chainID,resSeq', rowID=index_contact_ref, name=sql_ref.backbone_atoms)] data_test = sorted(set(data_test)) # close the sql sql_ref._close() if save_file: if filename is None: f = open(self.ref.split('.')[0] + '.izone', 'w') else: f = open(filename, 'w') for res in data_test: chain = res[0] num = res[1] f.write('zone %s%d-%s%d\n' % (chain, num, chain, num)) f.close() resData = {} for res in data_test: chain = res[0] num = res[1] if chain not in resData.keys(): resData[chain] = [] resData[chain].append(num) return resData ########################################################################## # # ROUTINE TO COMPUTE THE fnat QUICKLY # ########################################################################## def compute_fnat_fast(self, cutoff=5): """Fast method to cmpute the FNAT of the conformation. Fnat is the fraction of reference interface contacts preserved in the interface of decoy. The interface is defined as any pair of heavy atoms from two chains within 5Å of each other. Args: cutoff (int, optional): cutoff for the contact atoms Returns: float: FNAT value Raises: ValueError: if the decoy file is not found See also: :meth:`compute_fnat_pdb2sql` """ # compute ref residue pairs residue_pairs_ref = self.compute_residue_pairs_ref( cutoff, save_file=False) # create a dict of the decoy data data_decoy = pdb2sql.read_pdb(self.decoy) # read the decoy data residue_xyz = {} residue_name = {} for line in data_decoy: if line.startswith('ATOM'): chainID = line[21] if chainID == ' ': chainID = line[72] resSeq = int(line[22:26]) resName = line[17:20].strip() name = line[12:16].strip() x = float(line[30:38]) y = float(line[38:46]) z = float(line[46:54]) key = (chainID, resSeq, resName) if key not in residue_xyz.keys(): residue_xyz[key] = [] residue_name[key] = [] # if name in ['CA','C','N','O'] # exclude Hydrogen if name[0] != 'H': residue_xyz[key].append([x, y, z]) residue_name[key].append(name) # loop over the residue pairs of the ref nCommon, nTotal = 0, 0 for resA, resB_list in residue_pairs_ref.items(): if resA in residue_xyz.keys(): xyzA = residue_xyz[resA] for resB in resB_list: if resB in residue_xyz.keys(): xyzB = residue_xyz[resB] dist_min = np.min(np.array( [np.sqrt(np.sum((np.array(p1) - np.array(p2))**2)) for p1 in xyzA for p2 in xyzB])) if dist_min <= cutoff: nCommon += 1 nTotal += 1 else: msg = f'\t FNAT: not find residue: {resA}' warnings.warn(msg) # normalize return round(nCommon / nTotal, 6) # compute the residue pair of the reference def compute_residue_pairs_ref( self, cutoff=5.0, save_file=True, filename=None): """Compute the residue pair on the reference conformation. Args: cutoff (float, optional): cutoff for the contact atoms save_file (bool, optional): save the file containing the residue pairs filename (None, optional): filename Returns: dict: defintition of the residue pairs """ sql_ref = interface(self.ref) chains = list(sql_ref.get_chains()) if len(chains) != 2: raise ValueError( 'exactly two chains are needed for fnat calculation but we found %d' % len(chains), chains) residue_pairs_ref = sql_ref.get_contact_residues( cutoff=cutoff, return_contact_pairs=True, excludeH=True, chain1=chains[0], chain2=chains[1]) sql_ref._close() if save_file: if filename is None: f = open( self.ref.split('.')[0] + 'residue_contact_pairs.pckl', 'wb') else: f = open(filename, 'wb') # save as pickle pickle.dump(residue_pairs_ref, f) f.close() return residue_pairs_ref ########################################################################## # # ROUTINE TO COMPUTE THE L-RMSD USING PDB2SQL # DOES NOT REQUIRE THE PRECALCULATION OF ANYTHONG # CAN OUTPUT THE SUPERIMPOSED STRUCTURES # MUCH SLOWER THAN THE FAST ROUTINES BUT EASIER TO USE # ########################################################################## # compute the L-RMSD def compute_lrmsd_pdb2sql(self, exportpath=None, method='svd', **kwargs): """Slow routine to compute the L-RMSD. L-RMSD is computed by aligning the longest chain of the decoy to the one of the reference and computing the RMSD of the shortest chain between decoy and reference. Both fitting and rms calculation use only backbone atoms. See reference: DockQ: A Quality Measure for Protein-Protein Docking Models https://doi.org/10.1371/journal.pone.0161879 Args: exportpath (str, optional): file name where the aligned pdbs are exported. method (str, optional): Method to align the fragments, 'svd' or 'quaternion'. Kwargs: selection keywords used in the pdb2sql.get() method : 'rowID', 'serial', 'name', 'altLoc', 'resName', 'resSeq', 'iCode', 'x', 'y', 'z', 'occ', 'temp', 'element', 'model' Returns: float: L-RMSD value of the conformation See also: :meth:`compute_lrmsd_fast` """ backbone = ['CA', 'C', 'N', 'O'] if 'name' not in kwargs: kwargs['name'] = backbone if 'chainID' in kwargs: raise ValueError( 'do not specify chainID in compute_lrmsd_pdb2sql') # create the sql sql_decoy = pdb2sql(self.decoy, sqlfile='decoy.db') sql_ref = pdb2sql(self.ref, sqlfile='ref.db') # get the chains chains_decoy = sql_decoy.get_chains() chains_ref = sql_ref.get_chains() if chains_decoy != chains_ref: raise ValueError( 'Chains are different in decoy and reference structure') chain1 = chains_decoy[0] chain2 = chains_decoy[1] # extract the pos of chains A xyz_decoy_A = np.array( sql_decoy.get('x,y,z', chainID=chain1, **kwargs)) xyz_ref_A = np.array(sql_ref.get( 'x,y,z', chainID=chain1, **kwargs)) # extract the pos of chains B xyz_decoy_B = np.array( sql_decoy.get('x,y,z', chainID=chain2, **kwargs)) xyz_ref_B = np.array(sql_ref.get( 'x,y,z', chainID=chain2, **kwargs)) # check the lengthes if len(xyz_decoy_A) != len(xyz_ref_A): xyz_decoy_A, xyz_ref_A = self.get_identical_atoms( sql_decoy, sql_ref, chain1, **kwargs) if len(xyz_decoy_B) != len(xyz_ref_B): xyz_decoy_B, xyz_ref_B = self.get_identical_atoms( sql_decoy, sql_ref, **kwargs) # detect which chain is the longest nA, nB = len(xyz_decoy_A), len(xyz_decoy_B) if nA > nB: xyz_decoy_long = xyz_decoy_A xyz_ref_long = xyz_ref_A xyz_decoy_short = xyz_decoy_B xyz_ref_short = xyz_ref_B else: xyz_decoy_long = xyz_decoy_B xyz_ref_long = xyz_ref_B xyz_decoy_short = xyz_decoy_A xyz_ref_short = xyz_ref_A # get the translation so that both A chains are centered tr_decoy = get_trans_vect(xyz_decoy_long) tr_ref = get_trans_vect(xyz_ref_long) # translate everything for 1 xyz_decoy_short += tr_decoy xyz_decoy_long += tr_decoy # translate everuthing for 2 xyz_ref_short += tr_ref xyz_ref_long += tr_ref # get the ideal rotation matrix # to superimpose the A chains U = get_rotation_matrix( xyz_decoy_long, xyz_ref_long, method=method) # rotate the entire fragment xyz_decoy_short = transform.rotate( xyz_decoy_short, U, center=self.origin) # compute the RMSD lrmsd = self.get_rmsd(xyz_decoy_short, xyz_ref_short) # export the pdb for verifiactions if exportpath is not None: # extract the pos of the dimer xyz_decoy = np.array(sql_decoy.get('x,y,z')) xyz_ref = np.array(sql_ref.get('x,y,z')) # translate xyz_ref += tr_ref xyz_decoy += tr_decoy # rotate decoy xyz_decoy = transform.rotate( xyz_decoy, U, center=self.origin) # update the sql database sql_decoy.update_column('x', xyz_decoy[:, 0]) sql_decoy.update_column('y', xyz_decoy[:, 1]) sql_decoy.update_column('z', xyz_decoy[:, 2]) sql_ref.update_column('x', xyz_ref[:, 0]) sql_ref.update_column('y', xyz_ref[:, 1]) sql_ref.update_column('z', xyz_ref[:, 2]) # export sql_decoy.exportpdb(exportpath + '/lrmsd_decoy.pdb') sql_ref.exportpdb(exportpath + '/lrmsd_ref.pdb') # close the db sql_decoy._close() sql_ref._close() return lrmsd # RETURN THE ATOMS THAT ARE SHARED BY THE TWO DB # FOR A GIVEN CHAINID @staticmethod def get_identical_atoms(db1, db2, chain, **kwargs): """Return that atoms shared by both databse for a specific chain. Args: db1 (TYPE): pdb2sql database of the first conformation db2 (TYPE): pdb2sql database of the 2nd conformation chain (str): chain name Kwargs: selection keywords used in the pdb2sql.get() method : 'rowID', 'serial', 'name', 'altLoc', 'resName', 'chainID', 'resSeq', 'iCode', 'x', 'y', 'z', 'occ', 'temp', 'element', 'model' Returns: list, list: list of xyz for both database """ # get data data1 = db1.get('chainID,resSeq,name', chainID=chain, **kwargs) data2 = db2.get('chainID,resSeq,name', chainID=chain, **kwargs) # tuplify data1 = [tuple(d1) for d1 in data1] data2 = [tuple(d2) for d2 in data2] # get the intersection shared_data = list(set(data1).intersection(data2)) # get the xyz xyz1, xyz2 = [], [] for data in shared_data: query = 'SELECT x,y,z from ATOM WHERE chainID=? AND resSeq=? and name=?' xyz1.append(list(list(db1.c.execute(query, data))[0])) xyz2.append(list(list(db2.c.execute(query, data))[0])) return xyz1, xyz2 ########################################################################## # # ROUTINE TO COMPUTE THE I-RMSD USING PDB2SQL # DOES NOT REQUIRE THE PRECALCULATION OF ANYTHiNG # BUT CAN READ AN IZONE FILE AS WELL # CAN OUTPUT THE SUPERIMPOSED STRUCTURES # MUCH SLOWER THAN THE FAST ROUTINES BUT EASIER TO USE # ########################################################################## def compute_irmsd_pdb2sql( self, cutoff=10, method='svd', izone=None, exportpath=None): """Slow method to compute the i-rmsd. i-RMSD is computed by selecting the backbone atoms of reference interface that is defined as any pair of heavy atoms from two chains within 10Å of each other. Align these backbone atoms as best as possible with their coutner part in the decoy and compute the RMSD. See reference: DockQ: A Quality Measure for Protein-Protein Docking Models https://doi.org/10.1371/journal.pone.0161879 Args: izone (None, optional): file name of the zone. if None the zones will be calculated first. method (str, optional): Method to align the fragments, 'svd' or 'quaternion'. cutoff (float, optional): cutoff for the contact atoms exportpath (str, optional): file name where the aligned pdbs are exported. Returns: float: i-RMSD value of the conformation See also: :meth:`compute_irmsd_fast` """ # create thes sql sql_decoy = interface(self.decoy) sql_ref = interface(self.ref) # get the chains chains_decoy = sql_decoy.get_chains() chains_ref = sql_ref.get_chains() if chains_decoy != chains_ref: raise ValueError( 'Chains are different in decoy and reference structure') # get the contact atoms if izone is None: contact_ref = sql_ref.get_contact_atoms( cutoff=cutoff, extend_to_residue=True, chain1=chains_ref[0], chain2=chains_ref[1]) index_contact_ref = [] for v in contact_ref.values(): index_contact_ref += v index_contact_ref = sql_ref.get( 'rowID', rowID=index_contact_ref, name=sql_ref.backbone_atoms) else: index_contact_ref = self.get_izone_rowID( sql_ref, izone, return_only_backbone_atoms=True) # get the xyz and atom identifier of the decoy contact atoms xyz_contact_ref = sql_ref.get( 'x,y,z', rowID=index_contact_ref) data_contact_ref = sql_ref.get( 'chainID,resSeq,resName,name', rowID=index_contact_ref) # get the xyz and atom indeitifier of the reference xyz_decoy = sql_decoy.get('x,y,z') data_decoy = sql_decoy.get('chainID,resSeq,resName,name') # loop through the ref label # check if the atom is in the decoy # if yes -> add xyz to xyz_contact_decoy # if no -> remove the corresponding to xyz_contact_ref xyz_contact_decoy = [] index_contact_decoy = [] clean_ref = False for iat, atom in enumerate(data_contact_ref): try: index = data_decoy.index(atom) index_contact_decoy.append(index) xyz_contact_decoy.append(xyz_decoy[index]) except Exception: xyz_contact_ref[iat] = None index_contact_ref[iat] = None clean_ref = True # clean the xyz if clean_ref: xyz_contact_ref = [ xyz for xyz in xyz_contact_ref if xyz is not None] index_contact_ref = [ ind for ind in index_contact_ref if ind is not None] # check that we still have atoms in both chains chain_decoy = list( set(sql_decoy.get('chainID', rowID=index_contact_decoy))) chain_ref = list( set(sql_ref.get('chainID', rowID=index_contact_ref))) if len(chain_decoy) < 1 or len(chain_ref) < 1: raise ValueError( 'Error in i-rmsd: only one chain represented in one chain') # get the translation so that both A chains are centered tr_decoy = get_trans_vect(xyz_contact_decoy) tr_ref = get_trans_vect(xyz_contact_ref) # translate everything xyz_contact_decoy += tr_decoy xyz_contact_ref += tr_ref # get the ideql rotation matrix # to superimpose the A chains rot_mat = get_rotation_matrix( xyz_contact_decoy, xyz_contact_ref, method=method) # rotate the entire fragment xyz_contact_decoy = transform.rotate( xyz_contact_decoy, rot_mat, center=self.origin) # compute the RMSD irmsd = self.get_rmsd(xyz_contact_decoy, xyz_contact_ref) # export the pdb for verifiactions if exportpath is not None: # update the sql database sql_decoy.update_xyz( xyz_contact_decoy, rowID=index_contact_decoy) sql_ref.update_xyz( xyz_contact_ref, rowID=index_contact_ref) sql_decoy.exportpdb( exportpath + '/irmsd_decoy.pdb', rowID=index_contact_decoy) sql_ref.exportpdb( exportpath + '/irmsd_ref.pdb', rowID=index_contact_ref) # close the db sql_decoy._close() sql_ref._close() return irmsd # get the rowID of all the atoms def get_izone_rowID(self, sql, izone, return_only_backbone_atoms=True): """Compute the index of the izone atoms. Args: sql (pdb2sql): database of the conformation izone (str): filename to store the zone return_only_backbone_atoms (bool, optional): Returns only the backbone atoms Returns: lis(int): index of the atoms in the zone Raises: FileNotFoundError: if the izone file is not found """ # read the file if not os.path.isfile(izone): raise FileNotFoundError('i-zone file not found', izone) with open(izone, 'r') as f: data = f.readlines() # get the data out of it resData = {} for line in data: res = line.split()[1].split('-')[0] chainID, resSeq = res[0], int(res[1:]) if chainID not in resData.keys(): resData[chainID] = [] resData[chainID].append(resSeq) # get the rowID index_contact = [] for chainID, resSeq in resData.items(): if return_only_backbone_atoms: index_contact += sql.get('rowID', chainID=chainID, resSeq=resSeq, name=['C', 'CA', 'N', 'O']) else: index_contact += sql.get('rowID', chainID=chainID, resSeq=resSeq) return index_contact ########################################################################## # # ROUTINE TO COMPUTE THE fnat USING PDB2SQL # ########################################################################## def compute_fnat_pdb2sql(self, cutoff=5.0): """Slow method to compute the FNAT of the conformation. Fnat is the fraction of reference interface contacts preserved in the interface of decoy. The interface is defined as any pair of heavy atoms from two chains within 5Å of each other. Args: cutoff (int, optional): cutoff for the contact atoms Returns: float: FNAT value See also: :meth:`compute_fnat_fast` """ # create the sql sql_decoy = interface(self.decoy, fix_chainID=True) sql_ref = interface(self.ref, fix_chainID=True) chains = list(sql_ref.get_chains()) if len(chains) != 2: raise ValueError( 'exactly two chains are needed for irmsd calculation but we found %d' % len(chains), chains) # get the contact atoms residue_pairs_decoy = sql_decoy.get_contact_residues( cutoff=cutoff, return_contact_pairs=True, excludeH=True, chain1=chains[0], chain2=chains[1]) residue_pairs_ref = sql_ref.get_contact_residues( cutoff=cutoff, return_contact_pairs=True, excludeH=True, chain1=chains[0], chain2=chains[1]) # form the pair data data_pair_decoy = [] for resA, resB_list in residue_pairs_decoy.items(): data_pair_decoy += [(resA, resB) for resB in resB_list] # form the pair data data_pair_ref = [] for resA, resB_list in residue_pairs_ref.items(): data_pair_ref += [(resA, resB) for resB in resB_list] # find the umber of residue that ref and decoys hace in common nCommon = len( set(data_pair_ref).intersection(data_pair_decoy)) # normalize fnat = nCommon / len(data_pair_ref) sql_decoy._close() sql_ref._close() return round(fnat, 6) ########################################################################## # # HELPER ROUTINES TO HANDLE THE ZONE FILES # ########################################################################## @staticmethod def get_xyz_zone_backbone(pdb_file, resData, return_not_in_zone=False, name=['C', 'CA', 'N', 'O']): """Get the xyz of zone backbone atoms. Args: pdb_file (str): filename containing the pdb of the molecule resData (dict): information about the zone residues return_not_in_zone (bool, optional): Do we return the backbone atoms not in the zone and the chains used in the zone. Returns: list(float): XYZ of of backbone atoms in the zone. """ # read the ref file data = pdb2sql.read_pdb(pdb_file) # get the xyz of the xyz_in_zone = [] xyz_not_in_zone = [] for line in data: if line.startswith('ATOM'): chainID = line[21] if chainID == ' ': chainID = line[72] resSeq = int(line[22:26]) atname = line[12:16].strip() x = float(line[30:38]) y = float(line[38:46]) z = float(line[46:54]) if atname in name: if chainID in resData.keys(): if resSeq in resData[chainID]: xyz_in_zone.append([x, y, z]) else: xyz_not_in_zone.append([x, y, z]) if return_not_in_zone: return xyz_in_zone, xyz_not_in_zone else: return xyz_in_zone @staticmethod def get_data_zone_backbone(pdb_file, resData, return_not_in_zone=False, name=['C', 'CA', 'N', 'O']): """Get the data (chainID, resSeq, name) of backbone atoms in the zone. Args: pdb_file (str): filename containing the pdb of the molecule resData (dict): information about the zone residues return_not_in_zone (bool, optional): Do we return the atoms not in the zone and the chains used in the zone Returns: set(float): data of the backbone atoms in the zone """ # read the ref file data = pdb2sql.read_pdb(pdb_file) # get the xyz of the data_in_zone = [] data_not_in_zone = [] for line in data: if line.startswith('ATOM'): chainID = line[21] if chainID == ' ': chainID = line[72] resSeq = int(line[22:26]) atname = line[12:16].strip() if atname in name: if chainID in resData.keys(): if resSeq in resData[chainID]: data_in_zone.append((chainID, resSeq, atname)) else: data_not_in_zone.append((chainID, resSeq, atname)) if return_not_in_zone: return set(data_in_zone), set(data_not_in_zone) else: return set(data_in_zone) @staticmethod def read_zone(zone_file): """Read the zone file. Args: zone_file (str): name of the file Returns: dict: Info about the residues in the zone Raises: FileNotFoundError: if the zone file is not found """ # read the izone file if not os.path.isfile(zone_file): raise FileNotFoundError('zone file not found', zone_file) with open(zone_file, 'r') as f: data = f.readlines() # get the data out of it resData = {} for line in data: # line = zone A4-A4 for positive resNum # or line = zone A-4-A-4 for negative resNum # that happens for example in 2OUL # split the line res = line.split()[1].split('-') # if the resnum was positive # we have e.g res = [A4,A4] if len(res) == 2: res = res[0] chainID, resSeq = res[0], int(res[1:]) # if the resnum was negative was negtive # we have e.g res = [A,4,A,4] elif len(res) == 4: chainID, resSeq = res[0], -int(res[1]) if chainID not in resData.keys(): resData[chainID] = [] resData[chainID].append(resSeq) return resData @staticmethod def _get_xyz(pdb_file, index): """Get xyz using (chainID, resSeq, name) index. Args: pdb_file(file): pdb file or data index(set): set of index represeneted with (chainID, resSeq, name) Returns: list: list of xyz """ data = pdb2sql.read_pdb(pdb_file) xyz = [] for line in data: if line.startswith('ATOM'): chainID = line[21] if chainID == ' ': chainID = line[72] resSeq = int(line[22:26]) name = line[12:16].strip() x = float(line[30:38]) y = float(line[38:46]) z = float(line[46:54]) if (chainID, resSeq, name) in index: xyz.append([x, y, z]) return xyz ########################################################################## # # CAPRI categories and DockQ score # ########################################################################## @staticmethod def compute_CapriClass(fnat, lrmsd, irmsd, system='protein-protein'): """Compute CAPRI ranking classes. Note: Criteria of CAPRI classes: https://doi.org/10.1371/journal.pone.0161879 https://doi.org/10.1002/prot.21804 The protocol for classifying predicted model into the four CAPRI categories should start with those defining incorrect predictions. Args: fnat(float): fnat lrmsd(float): ligand rmsd irmsd(float ): interface rmsd system (str): the type of complex system. Defaults to 'protein-protein'. Returns: str: CAPRI rank class, i.e. high, medium, acceptable or incorrect. """ if system == 'protein-protein': if fnat < 0.1 or (lrmsd > 10.0 and irmsd > 4.0): label = 'incorrect' elif 0.1 <= fnat < 0.3 and (lrmsd <= 10.0 or irmsd <= 4.0) or \ (fnat >= 0.3 and lrmsd > 5.0 and irmsd > 2.0): label = 'acceptable' elif 0.3 <= fnat < 0.5 and (lrmsd <= 5.0 or irmsd <= 2.0) or \ (fnat >= 0.5 and lrmsd > 1.0 and irmsd > 1.0): label = 'medium' elif fnat >= 0.5 and (lrmsd <= 1.0 or irmsd <= 1.0): label = 'high' else: warnings.warn( f'Invalid complex type {system} for CAPRI class calculation') return label # compute the DockQ score from the different elements @staticmethod def compute_DockQScore(fnat, lrmsd, irmsd, d1=8.5, d2=1.5): """Compute the DockQ Score. Args: Fnat (float): Fnat value lrmsd (float): lrmsd value irmsd (float): irmsd value d1 (float, optional): first coefficient for the DockQ calculations d2 (float, optional): second coefficient for the DockQ calculations Returns: float: dockQ value """ def scale_rms(rms, d): return(1. / (1 + (rms / d)**2)) dockq = 1. / 3 * \ (fnat + scale_rms(lrmsd, d1) + scale_rms(irmsd, d2)) return round(dockq, 6) ########################################################################## # # clahses # ########################################################################## @staticmethod def compute_clashes(pdb, chain1='A', chain2='B'): """Compute number of atomic clashes. Note: Clashes were defined as contacts between nonhydrogen atoms separated by <3.0Å. Structural models where number of clashes was 2 SD away from the average are excluded for assessment in CAPRI. see ref: https://doi.org/10.1002/prot.10393 Args: pdb(file): pdb file or data chain1 (str): first chain ID. Defaults to 'A'. chain2 (str): second chain ID. Defaults to 'B'. Returns: int: number of atomic clashes. """ db = interface(pdb) atom_contact_pairs = db.get_contact_atoms( cutoff=3.0, excludeH=True, return_contact_pairs = True, chain1=chain1, chain2=chain2) db._close() nclash = 0 for v in atom_contact_pairs.values(): nclash += len(v) return nclash ########################################################################## # # ROUTINES TO ACTUALY SUPERPOSE THE MOLECULES # ########################################################################## # compute the RMSD of two sets of points @staticmethod def get_rmsd(P, Q): """compute the RMSD. Args: P (np.array(nx3)): position of the points in the first molecule Q (np.array(nx3)): position of the points in the second molecule Returns: float: RMSD value """ n = len(P) return round(np.sqrt(1. / n * np.sum((P - Q)**2)), 3)
34.709804
135
0.538199
import warnings import numpy as np from .pdb2sqlcore import pdb2sql from .interface import interface from .superpose import get_trans_vect, get_rotation_matrix, superpose_selection from . import transform import os import pickle class StructureSimilarity(object): def __init__(self, decoy, ref, verbose=False, enforce_residue_matching=True): self.decoy = decoy self.ref = ref self.verbose = verbose self.origin = [0., 0., 0.] self.enforce_residue_matching = enforce_residue_matching def __repr__(self): return f'{self.__module__}.{self.__class__.__name__}({self.decoy}, {self.ref}, {self.verbose})' def check_residues(self): res_ref = pdb2sql(self.ref).get_residues() res_dec = pdb2sql(self.decoy).get_residues() if res_ref != res_dec: print('Residues are different in the reference and decoy') print('Residues found in %s and not in %s' % (self.ref, self.decoy)) print(set(res_ref).difference(set(res_dec))) print('Residues found in %s and not in %s' % (self.decoy, self.ref)) print(set(res_dec).difference(set(res_ref))) if self.enforce_residue_matching == True: raise ValueError( 'Residue numbering not identical in ref and decoy\n Set enforce_residue_matching=False to bypass this error.') else: warns.Warning('Residue numbering not identical in ref and decoy.')
true
true
f725c56e6e6be2a0459699cdaa700720c868b2bf
1,319
py
Python
yad_uploader/loggers.py
RuzzyRullezz/yad_uploader
9a37e3b5f50365d6e105519043b71a6014ebef4f
[ "MIT" ]
null
null
null
yad_uploader/loggers.py
RuzzyRullezz/yad_uploader
9a37e3b5f50365d6e105519043b71a6014ebef4f
[ "MIT" ]
null
null
null
yad_uploader/loggers.py
RuzzyRullezz/yad_uploader
9a37e3b5f50365d6e105519043b71a6014ebef4f
[ "MIT" ]
null
null
null
import sys import logging import socket from typing import List import telegram_log.handler from yad_uploader.arguments import Arguments def configure_logger(logger: logging.Logger, tg_token: str, tg_chat_ids: List[str]): logger.setLevel(logging.DEBUG) host_name = socket.gethostname() log_format = '%(asctime)s [%(levelname)s] [{0} %(name)s:%(lineno)s] %(message)s'.format(host_name) formatter = logging.Formatter(log_format) if tg_token and tg_chat_ids: tg_handler = telegram_log.handler.TelegramHandler(token=tg_token, chat_ids=tg_chat_ids, err_log_name='') tg_handler.setLevel(logging.ERROR) tg_handler.setFormatter(formatter) logger.addHandler(tg_handler) stream_handler = logging.StreamHandler() stream_handler.setLevel(logging.DEBUG) stream_handler.setFormatter(formatter) logger.addHandler(stream_handler) def set_exception_hook(logger: logging.Logger): def excepthook(exctype, value, traceback): logger.exception('', exc_info=(exctype, value, traceback)) sys.excepthook = excepthook def setup(options: Arguments): assert options.tg_token assert options.tg_chats_id _logger = logging.getLogger(__name__) configure_logger(_logger, options.tg_token, options.tg_chats_id) set_exception_hook(_logger)
32.170732
112
0.751327
import sys import logging import socket from typing import List import telegram_log.handler from yad_uploader.arguments import Arguments def configure_logger(logger: logging.Logger, tg_token: str, tg_chat_ids: List[str]): logger.setLevel(logging.DEBUG) host_name = socket.gethostname() log_format = '%(asctime)s [%(levelname)s] [{0} %(name)s:%(lineno)s] %(message)s'.format(host_name) formatter = logging.Formatter(log_format) if tg_token and tg_chat_ids: tg_handler = telegram_log.handler.TelegramHandler(token=tg_token, chat_ids=tg_chat_ids, err_log_name='') tg_handler.setLevel(logging.ERROR) tg_handler.setFormatter(formatter) logger.addHandler(tg_handler) stream_handler = logging.StreamHandler() stream_handler.setLevel(logging.DEBUG) stream_handler.setFormatter(formatter) logger.addHandler(stream_handler) def set_exception_hook(logger: logging.Logger): def excepthook(exctype, value, traceback): logger.exception('', exc_info=(exctype, value, traceback)) sys.excepthook = excepthook def setup(options: Arguments): assert options.tg_token assert options.tg_chats_id _logger = logging.getLogger(__name__) configure_logger(_logger, options.tg_token, options.tg_chats_id) set_exception_hook(_logger)
true
true
f725c5e76c999a9a4e9b18abb24d8c6a364d2b89
33
py
Python
9-days-of-code/day-5/03 Spaces.py
jaredliw/mcc-python-solutions
f54b1d2a044788b2adc1eb19a490422eb92ffe77
[ "MIT" ]
2
2021-04-09T04:03:39.000Z
2021-04-09T04:18:28.000Z
9-days-of-code/day-5/03 Spaces.py
jaredliw/mcc-python-solutions
f54b1d2a044788b2adc1eb19a490422eb92ffe77
[ "MIT" ]
null
null
null
9-days-of-code/day-5/03 Spaces.py
jaredliw/mcc-python-solutions
f54b1d2a044788b2adc1eb19a490422eb92ffe77
[ "MIT" ]
null
null
null
print("second = hour * 60 * 60")
16.5
32
0.575758
print("second = hour * 60 * 60")
true
true
f725c62d71cda0c7e9a85c8d2794317378633651
2,261
py
Python
tests/test_uploads.py
Irdroid/httpie
ca36f1de04310de644857ebbea9c94984971ab7c
[ "BSD-3-Clause" ]
2
2015-06-27T05:40:27.000Z
2015-06-27T11:55:23.000Z
tests/test_uploads.py
915546302/httpie
ca36f1de04310de644857ebbea9c94984971ab7c
[ "BSD-3-Clause" ]
null
null
null
tests/test_uploads.py
915546302/httpie
ca36f1de04310de644857ebbea9c94984971ab7c
[ "BSD-3-Clause" ]
null
null
null
import os import pytest from httpie.input import ParseError from utils import TestEnvironment, http, HTTP_OK from fixtures import FILE_PATH_ARG, FILE_PATH, FILE_CONTENT class TestMultipartFormDataFileUpload: def test_non_existent_file_raises_parse_error(self, httpbin): with pytest.raises(ParseError): http('--form', 'POST', httpbin.url + '/post', 'foo@/__does_not_exist__') def test_upload_ok(self, httpbin): r = http('--form', '--verbose', 'POST', httpbin.url + '/post', 'test-file@%s' % FILE_PATH_ARG, 'foo=bar') assert HTTP_OK in r assert 'Content-Disposition: form-data; name="foo"' in r assert 'Content-Disposition: form-data; name="test-file";' \ ' filename="%s"' % os.path.basename(FILE_PATH) in r assert FILE_CONTENT in r assert '"foo": "bar"' in r class TestRequestBodyFromFilePath: """ `http URL @file' """ def test_request_body_from_file_by_path(self, httpbin): r = http('--verbose', 'POST', httpbin.url + '/post', '@' + FILE_PATH_ARG) assert HTTP_OK in r assert FILE_CONTENT in r, r assert '"Content-Type": "text/plain"' in r def test_request_body_from_file_by_path_with_explicit_content_type( self, httpbin): r = http('--verbose', 'POST', httpbin.url + '/post', '@' + FILE_PATH_ARG, 'Content-Type:text/plain; charset=utf8') assert HTTP_OK in r assert FILE_CONTENT in r assert 'Content-Type: text/plain; charset=utf8' in r def test_request_body_from_file_by_path_no_field_name_allowed( self, httpbin): env = TestEnvironment(stdin_isatty=True) r = http('POST', httpbin.url + '/post', 'field-name@' + FILE_PATH_ARG, env=env, error_exit_ok=True) assert 'perhaps you meant --form?' in r.stderr def test_request_body_from_file_by_path_no_data_items_allowed( self, httpbin): env = TestEnvironment(stdin_isatty=False) r = http('POST', httpbin.url + '/post', '@' + FILE_PATH_ARG, 'foo=bar', env=env, error_exit_ok=True) assert 'cannot be mixed' in r.stderr
35.888889
79
0.621849
import os import pytest from httpie.input import ParseError from utils import TestEnvironment, http, HTTP_OK from fixtures import FILE_PATH_ARG, FILE_PATH, FILE_CONTENT class TestMultipartFormDataFileUpload: def test_non_existent_file_raises_parse_error(self, httpbin): with pytest.raises(ParseError): http('--form', 'POST', httpbin.url + '/post', 'foo@/__does_not_exist__') def test_upload_ok(self, httpbin): r = http('--form', '--verbose', 'POST', httpbin.url + '/post', 'test-file@%s' % FILE_PATH_ARG, 'foo=bar') assert HTTP_OK in r assert 'Content-Disposition: form-data; name="foo"' in r assert 'Content-Disposition: form-data; name="test-file";' \ ' filename="%s"' % os.path.basename(FILE_PATH) in r assert FILE_CONTENT in r assert '"foo": "bar"' in r class TestRequestBodyFromFilePath: def test_request_body_from_file_by_path(self, httpbin): r = http('--verbose', 'POST', httpbin.url + '/post', '@' + FILE_PATH_ARG) assert HTTP_OK in r assert FILE_CONTENT in r, r assert '"Content-Type": "text/plain"' in r def test_request_body_from_file_by_path_with_explicit_content_type( self, httpbin): r = http('--verbose', 'POST', httpbin.url + '/post', '@' + FILE_PATH_ARG, 'Content-Type:text/plain; charset=utf8') assert HTTP_OK in r assert FILE_CONTENT in r assert 'Content-Type: text/plain; charset=utf8' in r def test_request_body_from_file_by_path_no_field_name_allowed( self, httpbin): env = TestEnvironment(stdin_isatty=True) r = http('POST', httpbin.url + '/post', 'field-name@' + FILE_PATH_ARG, env=env, error_exit_ok=True) assert 'perhaps you meant --form?' in r.stderr def test_request_body_from_file_by_path_no_data_items_allowed( self, httpbin): env = TestEnvironment(stdin_isatty=False) r = http('POST', httpbin.url + '/post', '@' + FILE_PATH_ARG, 'foo=bar', env=env, error_exit_ok=True) assert 'cannot be mixed' in r.stderr
true
true
f725c69d3932aaf715b9909a1b07cb3239f9f34f
62
py
Python
datasets/__init__.py
revsic/tf-speech-dataset
93a3ce2574616a3a52d2ac99af9826af680dda8f
[ "MIT" ]
1
2021-07-10T14:21:23.000Z
2021-07-10T14:21:23.000Z
datasets/__init__.py
revsic/tf-speech-dataset
93a3ce2574616a3a52d2ac99af9826af680dda8f
[ "MIT" ]
null
null
null
datasets/__init__.py
revsic/tf-speech-dataset
93a3ce2574616a3a52d2ac99af9826af680dda8f
[ "MIT" ]
null
null
null
from .ljspeech import LJSpeech from .reader import DataReader
20.666667
30
0.83871
from .ljspeech import LJSpeech from .reader import DataReader
true
true
f725c72c140425c7fa0f49c67ec4ca25c4dee0ad
816
py
Python
cli/polyaxon/proxies/schemas/robots.py
polyaxon/cli
3543c0220a8a7c06fc9573cd2a740f8ae4930641
[ "Apache-2.0" ]
null
null
null
cli/polyaxon/proxies/schemas/robots.py
polyaxon/cli
3543c0220a8a7c06fc9573cd2a740f8ae4930641
[ "Apache-2.0" ]
1
2022-01-24T11:26:47.000Z
2022-03-18T23:17:58.000Z
cli/polyaxon/proxies/schemas/robots.py
polyaxon/cli
3543c0220a8a7c06fc9573cd2a740f8ae4930641
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/python # # Copyright 2018-2022 Polyaxon, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from polyaxon.proxies.schemas.base import get_config OPTIONS = """ location = /robots.txt {{ rewrite ^ /static/robots.txt; }} """ def get_robots_config(): return get_config(options=OPTIONS, indent=0)
29.142857
74
0.741422
from polyaxon.proxies.schemas.base import get_config OPTIONS = """ location = /robots.txt {{ rewrite ^ /static/robots.txt; }} """ def get_robots_config(): return get_config(options=OPTIONS, indent=0)
true
true
f725c8ca4f1ea80a992f2dcedcd958469830ff26
4,170
py
Python
azure-mgmt-servicebus/azure/mgmt/servicebus/operations/premium_messaging_regions_operations.py
jmalobicky/azure-sdk-for-python
61234a3d83f8fb481d1dd2386e54e888864878fd
[ "MIT" ]
1
2018-07-23T08:59:24.000Z
2018-07-23T08:59:24.000Z
azure-mgmt-servicebus/azure/mgmt/servicebus/operations/premium_messaging_regions_operations.py
jmalobicky/azure-sdk-for-python
61234a3d83f8fb481d1dd2386e54e888864878fd
[ "MIT" ]
null
null
null
azure-mgmt-servicebus/azure/mgmt/servicebus/operations/premium_messaging_regions_operations.py
jmalobicky/azure-sdk-for-python
61234a3d83f8fb481d1dd2386e54e888864878fd
[ "MIT" ]
1
2018-08-28T14:36:47.000Z
2018-08-28T14:36:47.000Z
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- import uuid from msrest.pipeline import ClientRawResponse from .. import models class PremiumMessagingRegionsOperations(object): """PremiumMessagingRegionsOperations operations. :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. :ivar api_version: Client API version. Constant value: "2017-04-01". """ models = models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self.api_version = "2017-04-01" self.config = config def list( self, custom_headers=None, raw=False, **operation_config): """Gets the available premium messaging regions for servicebus . :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: An iterator like instance of PremiumMessagingRegions :rtype: ~azure.mgmt.servicebus.models.PremiumMessagingRegionsPaged[~azure.mgmt.servicebus.models.PremiumMessagingRegions] :raises: :class:`ErrorResponseException<azure.mgmt.servicebus.models.ErrorResponseException>` """ def internal_paging(next_link=None, raw=False): if not next_link: # Construct URL url = self.list.metadata['url'] path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') else: url = next_link query_parameters = {} # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.get(url, query_parameters) response = self._client.send( request, header_parameters, stream=False, **operation_config) if response.status_code not in [200]: raise models.ErrorResponseException(self._deserialize, response) return response # Deserialize response deserialized = models.PremiumMessagingRegionsPaged(internal_paging, self._deserialize.dependencies) if raw: header_dict = {} client_raw_response = models.PremiumMessagingRegionsPaged(internal_paging, self._deserialize.dependencies, header_dict) return client_raw_response return deserialized list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.ServiceBus/premiumMessagingRegions'}
40.882353
144
0.642446
import uuid from msrest.pipeline import ClientRawResponse from .. import models class PremiumMessagingRegionsOperations(object): models = models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self.api_version = "2017-04-01" self.config = config def list( self, custom_headers=None, raw=False, **operation_config): def internal_paging(next_link=None, raw=False): if not next_link: url = self.list.metadata['url'] path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') else: url = next_link query_parameters = {} header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') request = self._client.get(url, query_parameters) response = self._client.send( request, header_parameters, stream=False, **operation_config) if response.status_code not in [200]: raise models.ErrorResponseException(self._deserialize, response) return response deserialized = models.PremiumMessagingRegionsPaged(internal_paging, self._deserialize.dependencies) if raw: header_dict = {} client_raw_response = models.PremiumMessagingRegionsPaged(internal_paging, self._deserialize.dependencies, header_dict) return client_raw_response return deserialized list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.ServiceBus/premiumMessagingRegions'}
true
true
f725c9059a48acf58bb83c5eced787cdd333b41d
16,484
py
Python
python_modules/dagster-graphql/dagster_graphql_tests/graphql/snapshots/snap_test_environment_schema.py
Andrew-Crosby/dagster
e646625a687dc656bdd855d88b868de957b37b62
[ "Apache-2.0" ]
1
2021-07-03T09:05:58.000Z
2021-07-03T09:05:58.000Z
python_modules/dagster-graphql/dagster_graphql_tests/graphql/snapshots/snap_test_environment_schema.py
Andrew-Crosby/dagster
e646625a687dc656bdd855d88b868de957b37b62
[ "Apache-2.0" ]
null
null
null
python_modules/dagster-graphql/dagster_graphql_tests/graphql/snapshots/snap_test_environment_schema.py
Andrew-Crosby/dagster
e646625a687dc656bdd855d88b868de957b37b62
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # snapshottest: v1 - https://goo.gl/zC4yUc from __future__ import unicode_literals from snapshottest import Snapshot snapshots = Snapshot() snapshots['TestEnvironmentSchema.test_basic_invalid_config_on_run_config_schema[non_launchable_in_memory_instance_lazy_repository] 1'] = { 'runConfigSchemaOrError': { 'isRunConfigValid': { '__typename': 'PipelineConfigValidationInvalid', 'errors': [ { '__typename': 'FieldNotDefinedConfigError', 'fieldName': 'nope', 'message': 'Received unexpected config entry "nope" at the root. Expected: "{ execution?: { in_process?: { config?: { marker_to_close?: String retries?: { disabled?: { } enabled?: { } } } } multiprocess?: { config?: { max_concurrent?: Int retries?: { disabled?: { } enabled?: { } } } } } intermediate_storage?: { filesystem?: { config?: { base_dir?: String } } in_memory?: { config?: Any } } loggers?: { console?: { config?: { log_level?: String name?: String } } } resources?: { io_manager?: { config?: Any } } solids: { sum_solid: { config?: Any inputs: { num: String } outputs?: [{ result?: String }] } sum_sq_solid?: { config?: Any outputs?: [{ result?: String }] } } storage?: { filesystem?: { config?: { base_dir?: String } } in_memory?: { config?: Any } } }".', 'reason': 'FIELD_NOT_DEFINED', 'stack': { 'entries': [ ] } }, { '__typename': 'MissingFieldConfigError', 'field': { 'name': 'solids' }, 'message': 'Missing required config entry "solids" at the root. Sample config for missing entry: {\'solids\': {\'sum_solid\': {\'inputs\': {\'num\': \'...\'}}}}', 'reason': 'MISSING_REQUIRED_FIELD', 'stack': { 'entries': [ ] } } ], 'pipelineName': 'csv_hello_world' } } } snapshots['TestEnvironmentSchema.test_basic_invalid_config_on_run_config_schema[non_launchable_in_memory_instance_managed_grpc_env] 1'] = { 'runConfigSchemaOrError': { 'isRunConfigValid': { '__typename': 'PipelineConfigValidationInvalid', 'errors': [ { '__typename': 'FieldNotDefinedConfigError', 'fieldName': 'nope', 'message': 'Received unexpected config entry "nope" at the root. Expected: "{ execution?: { in_process?: { config?: { marker_to_close?: String retries?: { disabled?: { } enabled?: { } } } } multiprocess?: { config?: { max_concurrent?: Int retries?: { disabled?: { } enabled?: { } } } } } intermediate_storage?: { filesystem?: { config?: { base_dir?: String } } in_memory?: { config?: Any } } loggers?: { console?: { config?: { log_level?: String name?: String } } } resources?: { io_manager?: { config?: Any } } solids: { sum_solid: { config?: Any inputs: { num: String } outputs?: [{ result?: String }] } sum_sq_solid?: { config?: Any outputs?: [{ result?: String }] } } storage?: { filesystem?: { config?: { base_dir?: String } } in_memory?: { config?: Any } } }".', 'reason': 'FIELD_NOT_DEFINED', 'stack': { 'entries': [ ] } }, { '__typename': 'MissingFieldConfigError', 'field': { 'name': 'solids' }, 'message': 'Missing required config entry "solids" at the root. Sample config for missing entry: {\'solids\': {\'sum_solid\': {\'inputs\': {\'num\': \'...\'}}}}', 'reason': 'MISSING_REQUIRED_FIELD', 'stack': { 'entries': [ ] } } ], 'pipelineName': 'csv_hello_world' } } } snapshots['TestEnvironmentSchema.test_basic_invalid_config_on_run_config_schema[non_launchable_in_memory_instance_multi_location] 1'] = { 'runConfigSchemaOrError': { 'isRunConfigValid': { '__typename': 'PipelineConfigValidationInvalid', 'errors': [ { '__typename': 'FieldNotDefinedConfigError', 'fieldName': 'nope', 'message': 'Received unexpected config entry "nope" at the root. Expected: "{ execution?: { in_process?: { config?: { marker_to_close?: String retries?: { disabled?: { } enabled?: { } } } } multiprocess?: { config?: { max_concurrent?: Int retries?: { disabled?: { } enabled?: { } } } } } intermediate_storage?: { filesystem?: { config?: { base_dir?: String } } in_memory?: { config?: Any } } loggers?: { console?: { config?: { log_level?: String name?: String } } } resources?: { io_manager?: { config?: Any } } solids: { sum_solid: { config?: Any inputs: { num: String } outputs?: [{ result?: String }] } sum_sq_solid?: { config?: Any outputs?: [{ result?: String }] } } storage?: { filesystem?: { config?: { base_dir?: String } } in_memory?: { config?: Any } } }".', 'reason': 'FIELD_NOT_DEFINED', 'stack': { 'entries': [ ] } }, { '__typename': 'MissingFieldConfigError', 'field': { 'name': 'solids' }, 'message': 'Missing required config entry "solids" at the root. Sample config for missing entry: {\'solids\': {\'sum_solid\': {\'inputs\': {\'num\': \'...\'}}}}', 'reason': 'MISSING_REQUIRED_FIELD', 'stack': { 'entries': [ ] } } ], 'pipelineName': 'csv_hello_world' } } } snapshots['TestEnvironmentSchema.test_basic_invalid_config_on_run_config_schema[non_launchable_sqlite_instance_deployed_grpc_env] 1'] = { 'runConfigSchemaOrError': { 'isRunConfigValid': { '__typename': 'PipelineConfigValidationInvalid', 'errors': [ { '__typename': 'FieldNotDefinedConfigError', 'fieldName': 'nope', 'message': 'Received unexpected config entry "nope" at the root. Expected: "{ execution?: { in_process?: { config?: { marker_to_close?: String retries?: { disabled?: { } enabled?: { } } } } multiprocess?: { config?: { max_concurrent?: Int retries?: { disabled?: { } enabled?: { } } } } } intermediate_storage?: { filesystem?: { config?: { base_dir?: String } } in_memory?: { config?: Any } } loggers?: { console?: { config?: { log_level?: String name?: String } } } resources?: { io_manager?: { config?: Any } } solids: { sum_solid: { config?: Any inputs: { num: String } outputs?: [{ result?: String }] } sum_sq_solid?: { config?: Any outputs?: [{ result?: String }] } } storage?: { filesystem?: { config?: { base_dir?: String } } in_memory?: { config?: Any } } }".', 'reason': 'FIELD_NOT_DEFINED', 'stack': { 'entries': [ ] } }, { '__typename': 'MissingFieldConfigError', 'field': { 'name': 'solids' }, 'message': 'Missing required config entry "solids" at the root. Sample config for missing entry: {\'solids\': {\'sum_solid\': {\'inputs\': {\'num\': \'...\'}}}}', 'reason': 'MISSING_REQUIRED_FIELD', 'stack': { 'entries': [ ] } } ], 'pipelineName': 'csv_hello_world' } } } snapshots['TestEnvironmentSchema.test_basic_invalid_config_on_run_config_schema[non_launchable_sqlite_instance_lazy_repository] 1'] = { 'runConfigSchemaOrError': { 'isRunConfigValid': { '__typename': 'PipelineConfigValidationInvalid', 'errors': [ { '__typename': 'FieldNotDefinedConfigError', 'fieldName': 'nope', 'message': 'Received unexpected config entry "nope" at the root. Expected: "{ execution?: { in_process?: { config?: { marker_to_close?: String retries?: { disabled?: { } enabled?: { } } } } multiprocess?: { config?: { max_concurrent?: Int retries?: { disabled?: { } enabled?: { } } } } } intermediate_storage?: { filesystem?: { config?: { base_dir?: String } } in_memory?: { config?: Any } } loggers?: { console?: { config?: { log_level?: String name?: String } } } resources?: { io_manager?: { config?: Any } } solids: { sum_solid: { config?: Any inputs: { num: String } outputs?: [{ result?: String }] } sum_sq_solid?: { config?: Any outputs?: [{ result?: String }] } } storage?: { filesystem?: { config?: { base_dir?: String } } in_memory?: { config?: Any } } }".', 'reason': 'FIELD_NOT_DEFINED', 'stack': { 'entries': [ ] } }, { '__typename': 'MissingFieldConfigError', 'field': { 'name': 'solids' }, 'message': 'Missing required config entry "solids" at the root. Sample config for missing entry: {\'solids\': {\'sum_solid\': {\'inputs\': {\'num\': \'...\'}}}}', 'reason': 'MISSING_REQUIRED_FIELD', 'stack': { 'entries': [ ] } } ], 'pipelineName': 'csv_hello_world' } } } snapshots['TestEnvironmentSchema.test_basic_invalid_config_on_run_config_schema[non_launchable_sqlite_instance_managed_grpc_env] 1'] = { 'runConfigSchemaOrError': { 'isRunConfigValid': { '__typename': 'PipelineConfigValidationInvalid', 'errors': [ { '__typename': 'FieldNotDefinedConfigError', 'fieldName': 'nope', 'message': 'Received unexpected config entry "nope" at the root. Expected: "{ execution?: { in_process?: { config?: { marker_to_close?: String retries?: { disabled?: { } enabled?: { } } } } multiprocess?: { config?: { max_concurrent?: Int retries?: { disabled?: { } enabled?: { } } } } } intermediate_storage?: { filesystem?: { config?: { base_dir?: String } } in_memory?: { config?: Any } } loggers?: { console?: { config?: { log_level?: String name?: String } } } resources?: { io_manager?: { config?: Any } } solids: { sum_solid: { config?: Any inputs: { num: String } outputs?: [{ result?: String }] } sum_sq_solid?: { config?: Any outputs?: [{ result?: String }] } } storage?: { filesystem?: { config?: { base_dir?: String } } in_memory?: { config?: Any } } }".', 'reason': 'FIELD_NOT_DEFINED', 'stack': { 'entries': [ ] } }, { '__typename': 'MissingFieldConfigError', 'field': { 'name': 'solids' }, 'message': 'Missing required config entry "solids" at the root. Sample config for missing entry: {\'solids\': {\'sum_solid\': {\'inputs\': {\'num\': \'...\'}}}}', 'reason': 'MISSING_REQUIRED_FIELD', 'stack': { 'entries': [ ] } } ], 'pipelineName': 'csv_hello_world' } } } snapshots['TestEnvironmentSchema.test_basic_invalid_config_on_run_config_schema[non_launchable_sqlite_instance_multi_location] 1'] = { 'runConfigSchemaOrError': { 'isRunConfigValid': { '__typename': 'PipelineConfigValidationInvalid', 'errors': [ { '__typename': 'FieldNotDefinedConfigError', 'fieldName': 'nope', 'message': 'Received unexpected config entry "nope" at the root. Expected: "{ execution?: { in_process?: { config?: { marker_to_close?: String retries?: { disabled?: { } enabled?: { } } } } multiprocess?: { config?: { max_concurrent?: Int retries?: { disabled?: { } enabled?: { } } } } } intermediate_storage?: { filesystem?: { config?: { base_dir?: String } } in_memory?: { config?: Any } } loggers?: { console?: { config?: { log_level?: String name?: String } } } resources?: { io_manager?: { config?: Any } } solids: { sum_solid: { config?: Any inputs: { num: String } outputs?: [{ result?: String }] } sum_sq_solid?: { config?: Any outputs?: [{ result?: String }] } } storage?: { filesystem?: { config?: { base_dir?: String } } in_memory?: { config?: Any } } }".', 'reason': 'FIELD_NOT_DEFINED', 'stack': { 'entries': [ ] } }, { '__typename': 'MissingFieldConfigError', 'field': { 'name': 'solids' }, 'message': 'Missing required config entry "solids" at the root. Sample config for missing entry: {\'solids\': {\'sum_solid\': {\'inputs\': {\'num\': \'...\'}}}}', 'reason': 'MISSING_REQUIRED_FIELD', 'stack': { 'entries': [ ] } } ], 'pipelineName': 'csv_hello_world' } } } snapshots['TestEnvironmentSchema.test_basic_valid_config_on_run_config_schema[non_launchable_in_memory_instance_lazy_repository] 1'] = { 'runConfigSchemaOrError': { 'isRunConfigValid': { '__typename': 'PipelineConfigValidationValid', 'pipelineName': 'csv_hello_world' } } } snapshots['TestEnvironmentSchema.test_basic_valid_config_on_run_config_schema[non_launchable_in_memory_instance_managed_grpc_env] 1'] = { 'runConfigSchemaOrError': { 'isRunConfigValid': { '__typename': 'PipelineConfigValidationValid', 'pipelineName': 'csv_hello_world' } } } snapshots['TestEnvironmentSchema.test_basic_valid_config_on_run_config_schema[non_launchable_in_memory_instance_multi_location] 1'] = { 'runConfigSchemaOrError': { 'isRunConfigValid': { '__typename': 'PipelineConfigValidationValid', 'pipelineName': 'csv_hello_world' } } } snapshots['TestEnvironmentSchema.test_basic_valid_config_on_run_config_schema[non_launchable_sqlite_instance_deployed_grpc_env] 1'] = { 'runConfigSchemaOrError': { 'isRunConfigValid': { '__typename': 'PipelineConfigValidationValid', 'pipelineName': 'csv_hello_world' } } } snapshots['TestEnvironmentSchema.test_basic_valid_config_on_run_config_schema[non_launchable_sqlite_instance_lazy_repository] 1'] = { 'runConfigSchemaOrError': { 'isRunConfigValid': { '__typename': 'PipelineConfigValidationValid', 'pipelineName': 'csv_hello_world' } } } snapshots['TestEnvironmentSchema.test_basic_valid_config_on_run_config_schema[non_launchable_sqlite_instance_managed_grpc_env] 1'] = { 'runConfigSchemaOrError': { 'isRunConfigValid': { '__typename': 'PipelineConfigValidationValid', 'pipelineName': 'csv_hello_world' } } } snapshots['TestEnvironmentSchema.test_basic_valid_config_on_run_config_schema[non_launchable_sqlite_instance_multi_location] 1'] = { 'runConfigSchemaOrError': { 'isRunConfigValid': { '__typename': 'PipelineConfigValidationValid', 'pipelineName': 'csv_hello_world' } } }
54.582781
788
0.521354
from __future__ import unicode_literals from snapshottest import Snapshot snapshots = Snapshot() snapshots['TestEnvironmentSchema.test_basic_invalid_config_on_run_config_schema[non_launchable_in_memory_instance_lazy_repository] 1'] = { 'runConfigSchemaOrError': { 'isRunConfigValid': { '__typename': 'PipelineConfigValidationInvalid', 'errors': [ { '__typename': 'FieldNotDefinedConfigError', 'fieldName': 'nope', 'message': 'Received unexpected config entry "nope" at the root. Expected: "{ execution?: { in_process?: { config?: { marker_to_close?: String retries?: { disabled?: { } enabled?: { } } } } multiprocess?: { config?: { max_concurrent?: Int retries?: { disabled?: { } enabled?: { } } } } } intermediate_storage?: { filesystem?: { config?: { base_dir?: String } } in_memory?: { config?: Any } } loggers?: { console?: { config?: { log_level?: String name?: String } } } resources?: { io_manager?: { config?: Any } } solids: { sum_solid: { config?: Any inputs: { num: String } outputs?: [{ result?: String }] } sum_sq_solid?: { config?: Any outputs?: [{ result?: String }] } } storage?: { filesystem?: { config?: { base_dir?: String } } in_memory?: { config?: Any } } }".', 'reason': 'FIELD_NOT_DEFINED', 'stack': { 'entries': [ ] } }, { '__typename': 'MissingFieldConfigError', 'field': { 'name': 'solids' }, 'message': 'Missing required config entry "solids" at the root. Sample config for missing entry: {\'solids\': {\'sum_solid\': {\'inputs\': {\'num\': \'...\'}}}}', 'reason': 'MISSING_REQUIRED_FIELD', 'stack': { 'entries': [ ] } } ], 'pipelineName': 'csv_hello_world' } } } snapshots['TestEnvironmentSchema.test_basic_invalid_config_on_run_config_schema[non_launchable_in_memory_instance_managed_grpc_env] 1'] = { 'runConfigSchemaOrError': { 'isRunConfigValid': { '__typename': 'PipelineConfigValidationInvalid', 'errors': [ { '__typename': 'FieldNotDefinedConfigError', 'fieldName': 'nope', 'message': 'Received unexpected config entry "nope" at the root. Expected: "{ execution?: { in_process?: { config?: { marker_to_close?: String retries?: { disabled?: { } enabled?: { } } } } multiprocess?: { config?: { max_concurrent?: Int retries?: { disabled?: { } enabled?: { } } } } } intermediate_storage?: { filesystem?: { config?: { base_dir?: String } } in_memory?: { config?: Any } } loggers?: { console?: { config?: { log_level?: String name?: String } } } resources?: { io_manager?: { config?: Any } } solids: { sum_solid: { config?: Any inputs: { num: String } outputs?: [{ result?: String }] } sum_sq_solid?: { config?: Any outputs?: [{ result?: String }] } } storage?: { filesystem?: { config?: { base_dir?: String } } in_memory?: { config?: Any } } }".', 'reason': 'FIELD_NOT_DEFINED', 'stack': { 'entries': [ ] } }, { '__typename': 'MissingFieldConfigError', 'field': { 'name': 'solids' }, 'message': 'Missing required config entry "solids" at the root. Sample config for missing entry: {\'solids\': {\'sum_solid\': {\'inputs\': {\'num\': \'...\'}}}}', 'reason': 'MISSING_REQUIRED_FIELD', 'stack': { 'entries': [ ] } } ], 'pipelineName': 'csv_hello_world' } } } snapshots['TestEnvironmentSchema.test_basic_invalid_config_on_run_config_schema[non_launchable_in_memory_instance_multi_location] 1'] = { 'runConfigSchemaOrError': { 'isRunConfigValid': { '__typename': 'PipelineConfigValidationInvalid', 'errors': [ { '__typename': 'FieldNotDefinedConfigError', 'fieldName': 'nope', 'message': 'Received unexpected config entry "nope" at the root. Expected: "{ execution?: { in_process?: { config?: { marker_to_close?: String retries?: { disabled?: { } enabled?: { } } } } multiprocess?: { config?: { max_concurrent?: Int retries?: { disabled?: { } enabled?: { } } } } } intermediate_storage?: { filesystem?: { config?: { base_dir?: String } } in_memory?: { config?: Any } } loggers?: { console?: { config?: { log_level?: String name?: String } } } resources?: { io_manager?: { config?: Any } } solids: { sum_solid: { config?: Any inputs: { num: String } outputs?: [{ result?: String }] } sum_sq_solid?: { config?: Any outputs?: [{ result?: String }] } } storage?: { filesystem?: { config?: { base_dir?: String } } in_memory?: { config?: Any } } }".', 'reason': 'FIELD_NOT_DEFINED', 'stack': { 'entries': [ ] } }, { '__typename': 'MissingFieldConfigError', 'field': { 'name': 'solids' }, 'message': 'Missing required config entry "solids" at the root. Sample config for missing entry: {\'solids\': {\'sum_solid\': {\'inputs\': {\'num\': \'...\'}}}}', 'reason': 'MISSING_REQUIRED_FIELD', 'stack': { 'entries': [ ] } } ], 'pipelineName': 'csv_hello_world' } } } snapshots['TestEnvironmentSchema.test_basic_invalid_config_on_run_config_schema[non_launchable_sqlite_instance_deployed_grpc_env] 1'] = { 'runConfigSchemaOrError': { 'isRunConfigValid': { '__typename': 'PipelineConfigValidationInvalid', 'errors': [ { '__typename': 'FieldNotDefinedConfigError', 'fieldName': 'nope', 'message': 'Received unexpected config entry "nope" at the root. Expected: "{ execution?: { in_process?: { config?: { marker_to_close?: String retries?: { disabled?: { } enabled?: { } } } } multiprocess?: { config?: { max_concurrent?: Int retries?: { disabled?: { } enabled?: { } } } } } intermediate_storage?: { filesystem?: { config?: { base_dir?: String } } in_memory?: { config?: Any } } loggers?: { console?: { config?: { log_level?: String name?: String } } } resources?: { io_manager?: { config?: Any } } solids: { sum_solid: { config?: Any inputs: { num: String } outputs?: [{ result?: String }] } sum_sq_solid?: { config?: Any outputs?: [{ result?: String }] } } storage?: { filesystem?: { config?: { base_dir?: String } } in_memory?: { config?: Any } } }".', 'reason': 'FIELD_NOT_DEFINED', 'stack': { 'entries': [ ] } }, { '__typename': 'MissingFieldConfigError', 'field': { 'name': 'solids' }, 'message': 'Missing required config entry "solids" at the root. Sample config for missing entry: {\'solids\': {\'sum_solid\': {\'inputs\': {\'num\': \'...\'}}}}', 'reason': 'MISSING_REQUIRED_FIELD', 'stack': { 'entries': [ ] } } ], 'pipelineName': 'csv_hello_world' } } } snapshots['TestEnvironmentSchema.test_basic_invalid_config_on_run_config_schema[non_launchable_sqlite_instance_lazy_repository] 1'] = { 'runConfigSchemaOrError': { 'isRunConfigValid': { '__typename': 'PipelineConfigValidationInvalid', 'errors': [ { '__typename': 'FieldNotDefinedConfigError', 'fieldName': 'nope', 'message': 'Received unexpected config entry "nope" at the root. Expected: "{ execution?: { in_process?: { config?: { marker_to_close?: String retries?: { disabled?: { } enabled?: { } } } } multiprocess?: { config?: { max_concurrent?: Int retries?: { disabled?: { } enabled?: { } } } } } intermediate_storage?: { filesystem?: { config?: { base_dir?: String } } in_memory?: { config?: Any } } loggers?: { console?: { config?: { log_level?: String name?: String } } } resources?: { io_manager?: { config?: Any } } solids: { sum_solid: { config?: Any inputs: { num: String } outputs?: [{ result?: String }] } sum_sq_solid?: { config?: Any outputs?: [{ result?: String }] } } storage?: { filesystem?: { config?: { base_dir?: String } } in_memory?: { config?: Any } } }".', 'reason': 'FIELD_NOT_DEFINED', 'stack': { 'entries': [ ] } }, { '__typename': 'MissingFieldConfigError', 'field': { 'name': 'solids' }, 'message': 'Missing required config entry "solids" at the root. Sample config for missing entry: {\'solids\': {\'sum_solid\': {\'inputs\': {\'num\': \'...\'}}}}', 'reason': 'MISSING_REQUIRED_FIELD', 'stack': { 'entries': [ ] } } ], 'pipelineName': 'csv_hello_world' } } } snapshots['TestEnvironmentSchema.test_basic_invalid_config_on_run_config_schema[non_launchable_sqlite_instance_managed_grpc_env] 1'] = { 'runConfigSchemaOrError': { 'isRunConfigValid': { '__typename': 'PipelineConfigValidationInvalid', 'errors': [ { '__typename': 'FieldNotDefinedConfigError', 'fieldName': 'nope', 'message': 'Received unexpected config entry "nope" at the root. Expected: "{ execution?: { in_process?: { config?: { marker_to_close?: String retries?: { disabled?: { } enabled?: { } } } } multiprocess?: { config?: { max_concurrent?: Int retries?: { disabled?: { } enabled?: { } } } } } intermediate_storage?: { filesystem?: { config?: { base_dir?: String } } in_memory?: { config?: Any } } loggers?: { console?: { config?: { log_level?: String name?: String } } } resources?: { io_manager?: { config?: Any } } solids: { sum_solid: { config?: Any inputs: { num: String } outputs?: [{ result?: String }] } sum_sq_solid?: { config?: Any outputs?: [{ result?: String }] } } storage?: { filesystem?: { config?: { base_dir?: String } } in_memory?: { config?: Any } } }".', 'reason': 'FIELD_NOT_DEFINED', 'stack': { 'entries': [ ] } }, { '__typename': 'MissingFieldConfigError', 'field': { 'name': 'solids' }, 'message': 'Missing required config entry "solids" at the root. Sample config for missing entry: {\'solids\': {\'sum_solid\': {\'inputs\': {\'num\': \'...\'}}}}', 'reason': 'MISSING_REQUIRED_FIELD', 'stack': { 'entries': [ ] } } ], 'pipelineName': 'csv_hello_world' } } } snapshots['TestEnvironmentSchema.test_basic_invalid_config_on_run_config_schema[non_launchable_sqlite_instance_multi_location] 1'] = { 'runConfigSchemaOrError': { 'isRunConfigValid': { '__typename': 'PipelineConfigValidationInvalid', 'errors': [ { '__typename': 'FieldNotDefinedConfigError', 'fieldName': 'nope', 'message': 'Received unexpected config entry "nope" at the root. Expected: "{ execution?: { in_process?: { config?: { marker_to_close?: String retries?: { disabled?: { } enabled?: { } } } } multiprocess?: { config?: { max_concurrent?: Int retries?: { disabled?: { } enabled?: { } } } } } intermediate_storage?: { filesystem?: { config?: { base_dir?: String } } in_memory?: { config?: Any } } loggers?: { console?: { config?: { log_level?: String name?: String } } } resources?: { io_manager?: { config?: Any } } solids: { sum_solid: { config?: Any inputs: { num: String } outputs?: [{ result?: String }] } sum_sq_solid?: { config?: Any outputs?: [{ result?: String }] } } storage?: { filesystem?: { config?: { base_dir?: String } } in_memory?: { config?: Any } } }".', 'reason': 'FIELD_NOT_DEFINED', 'stack': { 'entries': [ ] } }, { '__typename': 'MissingFieldConfigError', 'field': { 'name': 'solids' }, 'message': 'Missing required config entry "solids" at the root. Sample config for missing entry: {\'solids\': {\'sum_solid\': {\'inputs\': {\'num\': \'...\'}}}}', 'reason': 'MISSING_REQUIRED_FIELD', 'stack': { 'entries': [ ] } } ], 'pipelineName': 'csv_hello_world' } } } snapshots['TestEnvironmentSchema.test_basic_valid_config_on_run_config_schema[non_launchable_in_memory_instance_lazy_repository] 1'] = { 'runConfigSchemaOrError': { 'isRunConfigValid': { '__typename': 'PipelineConfigValidationValid', 'pipelineName': 'csv_hello_world' } } } snapshots['TestEnvironmentSchema.test_basic_valid_config_on_run_config_schema[non_launchable_in_memory_instance_managed_grpc_env] 1'] = { 'runConfigSchemaOrError': { 'isRunConfigValid': { '__typename': 'PipelineConfigValidationValid', 'pipelineName': 'csv_hello_world' } } } snapshots['TestEnvironmentSchema.test_basic_valid_config_on_run_config_schema[non_launchable_in_memory_instance_multi_location] 1'] = { 'runConfigSchemaOrError': { 'isRunConfigValid': { '__typename': 'PipelineConfigValidationValid', 'pipelineName': 'csv_hello_world' } } } snapshots['TestEnvironmentSchema.test_basic_valid_config_on_run_config_schema[non_launchable_sqlite_instance_deployed_grpc_env] 1'] = { 'runConfigSchemaOrError': { 'isRunConfigValid': { '__typename': 'PipelineConfigValidationValid', 'pipelineName': 'csv_hello_world' } } } snapshots['TestEnvironmentSchema.test_basic_valid_config_on_run_config_schema[non_launchable_sqlite_instance_lazy_repository] 1'] = { 'runConfigSchemaOrError': { 'isRunConfigValid': { '__typename': 'PipelineConfigValidationValid', 'pipelineName': 'csv_hello_world' } } } snapshots['TestEnvironmentSchema.test_basic_valid_config_on_run_config_schema[non_launchable_sqlite_instance_managed_grpc_env] 1'] = { 'runConfigSchemaOrError': { 'isRunConfigValid': { '__typename': 'PipelineConfigValidationValid', 'pipelineName': 'csv_hello_world' } } } snapshots['TestEnvironmentSchema.test_basic_valid_config_on_run_config_schema[non_launchable_sqlite_instance_multi_location] 1'] = { 'runConfigSchemaOrError': { 'isRunConfigValid': { '__typename': 'PipelineConfigValidationValid', 'pipelineName': 'csv_hello_world' } } }
true
true
f725c97888414ba89b8b7dc7e429ef5d79ac764f
2,335
py
Python
lib/safe_python.py
AjaxVM/hiths-pyweek6
6661ddb8b7c75b0788ce41a411838bc28d59d284
[ "Unlicense" ]
null
null
null
lib/safe_python.py
AjaxVM/hiths-pyweek6
6661ddb8b7c75b0788ce41a411838bc28d59d284
[ "Unlicense" ]
null
null
null
lib/safe_python.py
AjaxVM/hiths-pyweek6
6661ddb8b7c75b0788ce41a411838bc28d59d284
[ "Unlicense" ]
null
null
null
def test_safe(filename, acceptable_functions=[]): """tests all the function calls in a file against a set of acceptable ones. this function also does not allow importing of other modules. returns True, [] if there are only acceptable function calls, returns False and a list of bad function calls, if the test fails. OR returns False, "import" if there is an import statement""" text = open(filename, "rU").read() text.replace("\r", "\n") while "#" in text: text = text[0:text.index("#")] +\ text[text.index("\n", text.index("#"))::] for i in text.split(): if i == "import" or\ i[-7::] == ":import" or\ i[-7::] == ";import": return False, "import" #split all the text new = [] cur = "" cur_string = False for i in text: if not cur_string: if i == "(": new.append(cur) cur = "" new.append("(") elif i == ")": new.append(cur) cur = "" new.append(")") else: if i == '"': cur_string = True else: cur += i else: if i == '"': cur_string = False cur += i else: cur += i if cur: new.append(cur) #remove anything that isn't a function call ok = [] for i in xrange(len(new)): if new[i] == "(": last = new[i-1].split()[-1].split(".")[-1] if len(new[i-1].split()) >= 2: before_that = new[i-1].split()[-2].split(".")[-1] else: before_that = None #remove a function/class declaration, and tuple declarations, they are different! if not before_that in ["def", "class"] and\ not last in ["print", "=", "in"]: ok.append(last) else: if before_that in ["def", "class"]: acceptable_functions.append(last) for i in ok: if i in acceptable_functions: continue else: return False, ok return True, ok
31.133333
94
0.443683
def test_safe(filename, acceptable_functions=[]): text = open(filename, "rU").read() text.replace("\r", "\n") while "#" in text: text = text[0:text.index("#")] +\ text[text.index("\n", text.index("#"))::] for i in text.split(): if i == "import" or\ i[-7::] == ":import" or\ i[-7::] == ";import": return False, "import" new = [] cur = "" cur_string = False for i in text: if not cur_string: if i == "(": new.append(cur) cur = "" new.append("(") elif i == ")": new.append(cur) cur = "" new.append(")") else: if i == '"': cur_string = True else: cur += i else: if i == '"': cur_string = False cur += i else: cur += i if cur: new.append(cur) ok = [] for i in xrange(len(new)): if new[i] == "(": last = new[i-1].split()[-1].split(".")[-1] if len(new[i-1].split()) >= 2: before_that = new[i-1].split()[-2].split(".")[-1] else: before_that = None #remove a function/class declaration, and tuple declarations, they are different! if not before_that in ["def", "class"] and\ not last in ["print", "=", "in"]: ok.append(last) else: if before_that in ["def", "class"]: acceptable_functions.append(last) for i in ok: if i in acceptable_functions: continue else: return False, ok return True, ok
true
true
f725c9a230b27d2955d04d1ff0959892b346bcb4
13,044
py
Python
insights/parsers/tests/test_sctp.py
pombredanne/insights-core
63d6510ce8b7b96c94fbd568369420ecf38cf2ae
[ "Apache-2.0" ]
121
2017-05-30T20:23:25.000Z
2022-03-23T12:52:15.000Z
insights/parsers/tests/test_sctp.py
ahitacat/insights-core
0ba58dbe5edceef0bd4a74c1caf6b826381ccda5
[ "Apache-2.0" ]
1,977
2017-05-26T14:36:03.000Z
2022-03-31T10:38:53.000Z
insights/parsers/tests/test_sctp.py
ahitacat/insights-core
0ba58dbe5edceef0bd4a74c1caf6b826381ccda5
[ "Apache-2.0" ]
244
2017-05-30T20:22:57.000Z
2022-03-26T10:09:39.000Z
import doctest import pytest from insights.parsers import ParseException, SkipException from insights.parsers import sctp from insights.parsers.sctp import SCTPEps from insights.parsers.sctp import SCTPAsc, SCTPAsc7 from insights.parsers.sctp import SCTPSnmp from insights.tests import context_wrap SCTP_EPS_DETAILS = """ ENDPT SOCK STY SST HBKT LPORT UID INODE LADDRS ffff88017e0a0200 ffff880299f7fa00 2 10 29 11165 200 299689357 10.0.0.102 10.0.0.70 ffff880612e81c00 ffff8803c28a1b00 2 10 30 11166 200 273361203 10.0.0.102 10.0.0.70 172.31.1.2 ffff88061fba9800 ffff88061f8a3180 2 10 31 11167 200 273361145 10.0.0.102 10.0.0.70 ffff88031e6f1a00 ffff88031dbdb180 2 10 32 11168 200 273365974 10.0.0.102 10.0.0.70 192.168.11.2 ffff88031e6f1a00 ffff88031dbdb180 2 10 32 11168 200 273365974 192.168.11.12 """.strip() SCTP_EPS_DETAILS_NO = """ ENDPT SOCK STY SST LPORT UID INODE LADDRS ffff88017e0a0200 ffff880299f7fa00 2 10 11165 200 299689357 10.0.0.102 10.0.0.70 ffff880612e81c00 ffff8803c28a1b00 2 10 11166 200 273361203 10.0.0.102 10.0.0.70 172.31.1.2 ffff88061fba9800 ffff88061f8a3180 2 10 11167 200 273361145 10.0.0.102 10.0.0.70 ffff88031e6f1a00 ffff88031dbdb180 2 10 11168 200 273365974 10.0.0.102 10.0.0.70 192.168.11.2 """.strip() SCTP_EPS_DETAILS_DOC = """ ENDPT SOCK STY SST HBKT LPORT UID INODE LADDRS ffff88017e0a0200 ffff880299f7fa00 2 10 29 11165 200 299689357 10.0.0.102 10.0.0.70 ffff880612e81c00 ffff8803c28a1b00 2 10 30 11166 200 273361203 10.0.0.102 10.0.0.70 172.31.1.2 """.strip() SCTP_EPS_DETAILS_NO_2 = """ """.strip() SCTP_ASSOC = """ ASSOC SOCK STY SST ST HBKT ASSOC-ID TX_QUEUE RX_QUEUE UID INODE LPORT RPORT LADDRS <-> RADDRS HBINT INS OUTS MAXRT T1X T2X RTXC ffff88045ac7e000 ffff88062077aa00 2 1 4 1205 963 0 0 200 273361167 11567 11166 10.0.0.102 10.0.0.70 <-> *10.0.0.109 10.0.0.77 1000 2 2 10 0 0 0 ffff88061fbf2000 ffff88060ff92500 2 1 4 1460 942 0 0 200 273360669 11566 11167 10.0.0.102 10.0.0.70 <-> *10.0.0.109 10.0.0.77 1000 2 2 10 0 0 0 ffff8803217b9000 ffff8801c6321580 2 1 4 1675 977 0 0 200 273361369 11565 11168 10.0.0.102 10.0.0.70 192.168.11.2 <-> *10.0.0.109 10.0.0.77 1000 2 2 10 0 0 0 ffff8803db908000 ffff88061e4a00c0 2 1 4 2229 967 0 0 200 273361177 12067 11166 10.0.0.102 10.0.0.70 <-> *10.0.0.110 10.0.0.78 1000 2 2 10 0 0 0 ffff88062258f000 ffff88060fffaa40 2 1 4 2485 953 0 0 200 273360681 12066 11166 10.0.0.102 10.0.0.70 <-> *10.0.0.103 10.0.0.71 1000 2 2 10 0 0 0 ffff8801ce686000 ffff8801c7083ac0 2 1 4 2741 982 0 0 200 273361381 12065 11166 10.0.0.102 10.0.0.70 <-> *10.0.0.112 10.0.0.80 1000 2 2 10 0 0 0 ffff88031e1f4000 ffff8801c6fd9b00 2 1 4 7092 1005 0 0 200 273366011 11567 11167 10.0.0.102 10.0.0.70 <-> *10.0.0.111 10.0.0.79 1000 2 2 10 0 0 0 """.strip() SCTP_ASSOC_2 = """ ASSOC SOCK STY SST ST HBKT ASSOC-ID TX_QUEUE RX_QUEUE UID INODE LPORT RPORT LADDRS <-> RADDRS HBINT INS OUTS MAXRT T1X T2X RTXC ffff8804239ca000 ffff8804238c6040 2 1 4 3091 1 0 0 500 90293 37379 3868 10.0.200.114 10.0.201.114 2010:0010:0000:0200:0000:0000:0000:0114 2010:0010:0000:0201:0000:0000:0000:0114 <-> *10.0.100.94 10.0.101.94 2010:0010:0000:0100:0000:0000:0000:0094 2010:0010:0000:0101:0000:0000:0000:0094 1000 5 5 10 0 0 0 """.strip() SCTP_ASSOC_DOC = """ ASSOC SOCK STY SST ST HBKT ASSOC-ID TX_QUEUE RX_QUEUE UID INODE LPORT RPORT LADDRS <-> RADDRS HBINT INS OUTS MAXRT T1X T2X RTXC ffff88045ac7e000 ffff88062077aa00 2 1 4 1205 963 0 0 200 273361167 11567 11166 10.0.0.102 10.0.0.70 <-> *10.0.0.109 10.0.0.77 1000 2 2 10 0 0 0 ffff88061fbf2000 ffff88060ff92500 2 1 4 1460 942 0 0 200 273360669 11566 11167 10.0.0.102 10.0.0.70 <-> *10.0.0.109 10.0.0.77 1000 2 2 10 0 0 0 """.strip() SCTP_ASSOC_NO = """ """.strip() SCTP_ASSOC_NO_2 = """ SOCK STY SST ST HBKT ASSOC-ID TX_QUEUE RX_QUEUE UID INODE LPORT RPORT LADDRS RADDRS HBINT INS OUTS MAXRT T1X T2X RTXC ffff88045ac7e000 ffff88062077aa00 2 1 4 1205 963 0 0 200 273361167 11567 11166 10.0.0.102 10.0.0.70 *10.0.0.109 10.0.0.77 1000 2 2 10 0 0 0 """.strip() SCTP_SNMP = """ SctpCurrEstab 5380 SctpActiveEstabs 12749 SctpPassiveEstabs 55 SctpAborteds 2142 SctpShutdowns 5295 SctpOutOfBlues 36786 SctpChecksumErrors 0 SctpOutCtrlChunks 1051492 SctpOutOrderChunks 17109 SctpOutUnorderChunks 0 SctpInCtrlChunks 1018398 SctpInOrderChunks 17033 SctpInUnorderChunks 0 SctpFragUsrMsgs 0 SctpReasmUsrMsgs 0 SctpOutSCTPPacks 1068678 """.strip() SCTP_SNMP_NO_1 = """ """.strip() SCTP_SNMP_NO_2 = """ SctpCurrEstab 5380 SctpActiveEstabs 12749 SctpPassiveEstabs 55 SctpAborteds 2142 SctpShutdowns 5295 SctpOutOfBlues 36786 SctpChecksumErrors 0 SctpOutCtrlChunks 1051492 SctpOutOrderChunks 17109 """.strip() SCTP_SNMP_DOC = """ SctpCurrEstab 5380 SctpActiveEstabs 12749 SctpPassiveEstabs 55 SctpAborteds 2142 SctpShutdowns 5295 SctpOutOfBlues 36786 SctpChecksumErrors 0 SctpOutCtrlChunks 1051492 """ SCTP_ASC_7 = """ ASSOC SOCK STY SST ST HBKT ASSOC-ID TX_QUEUE RX_QUEUE UID INODE LPORT RPORT LADDRS <-> RADDRS HBINT INS OUTS MAXRT T1X T2X RTXC wmema wmemq sndbuf rcvbuf ffff8805d36b3000 ffff880f8911f380 0 10 3 0 12754 0 0 0 496595 3868 3868 10.131.222.5 <-> *10.131.160.81 10.131.176.81 30000 17 10 10 0 0 0 11 12 1000000 2000000 ffff8805f17e1000 ffff881004aff380 0 10 3 0 12728 0 0 0 532396 3868 3868 10.131.222.3 <-> *10.131.160.81 10.131.176.81 30000 17 10 10 0 0 0 13 14 3000000 4000000 ffff8805f17e0000 ffff880f8a117380 0 10 3 0 12727 0 0 0 582963 3868 3868 10.131.222.8 <-> *10.131.160.81 10.131.176.81 30000 17 10 10 0 0 0 15 16 5000000 6000000 ffff88081d0bc000 ffff880f6fa66300 0 10 3 0 12726 0 0 0 582588 3868 3868 10.131.222.2 <-> *10.131.160.81 10.131.176.81 30000 17 10 10 0 0 0 17 18 7000000 8000000 ffff88081d0f5000 ffff880f00a99600 0 10 3 0 12725 0 0 0 578082 3868 3868 10.131.222.1 <-> *10.131.160.81 10.131.176.81 30000 17 10 10 0 0 0 19 20 9000000 10000000 """.strip() SCTP_ASSOC_RHEL_7_DOC = """ ASSOC SOCK STY SST ST HBKT ASSOC-ID TX_QUEUE RX_QUEUE UID INODE LPORT RPORT LADDRS <-> RADDRS HBINT INS OUTS MAXRT T1X T2X RTXC wmema wmemq sndbuf rcvbuf ffff8805d36b3000 ffff880f8911f380 0 10 3 0 12754 0 0 0 496595 3868 3868 10.131.222.5 <-> *10.131.160.81 10.131.176.81 30000 17 10 10 0 0 0 11 12 1000000 2000000 ffff8805f17e1000 ffff881004aff380 0 10 3 0 12728 0 0 0 532396 3868 3868 10.131.222.3 <-> *10.131.160.81 10.131.176.81 30000 17 10 10 0 0 0 13 14 3000000 4000000 """.strip() def test_sctp_eps(): sctp_info = SCTPEps(context_wrap(SCTP_EPS_DETAILS)) assert sorted(sctp_info.sctp_local_ports) == sorted(['11165', '11166', '11167', '11168']) assert sorted(sctp_info.sctp_local_ips) == sorted(['10.0.0.102', '10.0.0.70', '172.31.1.2', '192.168.11.2', '192.168.11.12']) assert sctp_info.sctp_eps_ips == {'ffff88017e0a0200': ['10.0.0.102', '10.0.0.70'], 'ffff880612e81c00': ['10.0.0.102', '10.0.0.70', '172.31.1.2'], 'ffff88061fba9800': ['10.0.0.102', '10.0.0.70'], 'ffff88031e6f1a00': ['10.0.0.102', '10.0.0.70', '192.168.11.2', '192.168.11.12']} assert len(sctp_info.search(local_port='11165')) == 1 def test_sctp_asc(): sctp_asc = SCTPAsc(context_wrap(SCTP_ASSOC)) assert sorted(sctp_asc.sctp_local_ports) == sorted(['11567', '11566', '11565', '12067', '12065', '12066']) assert sorted(sctp_asc.search(local_port='11565')) == sorted([{'init_chunks_send': '0', 'uid': '200', 'shutdown_chunks_send': '0', 'max_outstream': '2', 'tx_que': '0', 'inode': '273361369', 'hrtbt_intrvl': '1000', 'sk_type': '2', 'remote_addr': ['*10.0.0.109', '10.0.0.77'], 'data_chunks_retrans': '0', 'local_addr': ['10.0.0.102', '10.0.0.70', '192.168.11.2'], 'asc_id': '977', 'max_instream': '2', 'remote_port': '11168', 'asc_state': '4', 'max_retrans_atmpt': '10', 'sk_state': '1', 'socket': 'ffff8801c6321580', 'asc_struct': 'ffff8803217b9000', 'local_port': '11565', 'hash_bkt': '1675', 'rx_que': '0'}]) assert len(sctp_asc.search(local_port='11567')) == 2 assert sorted(sctp_asc.sctp_local_ips) == sorted(['10.0.0.102', '10.0.0.70', '192.168.11.2']) assert sorted(sctp_asc.sctp_remote_ips) == sorted(['*10.0.0.109', '10.0.0.77', '*10.0.0.110', '10.0.0.78', '*10.0.0.103', '10.0.0.71', '*10.0.0.112', '10.0.0.80', '*10.0.0.111', '10.0.0.79']) sctp_asc = SCTPAsc(context_wrap(SCTP_ASSOC_2)) assert sorted(sctp_asc.sctp_local_ips) == sorted(['10.0.200.114', '10.0.201.114', '2010:0010:0000:0200:0000:0000:0000:0114', '2010:0010:0000:0201:0000:0000:0000:0114']) assert sorted(sctp_asc.sctp_remote_ips) == sorted(['*10.0.100.94', '10.0.101.94', '2010:0010:0000:0100:0000:0000:0000:0094', '2010:0010:0000:0101:0000:0000:0000:0094']) sctp_asc = SCTPAsc7(context_wrap(SCTP_ASC_7)) assert sctp_asc.sctp_local_ips == sorted(['10.131.222.5', '10.131.222.3', '10.131.222.8', '10.131.222.2', '10.131.222.1']) assert sctp_asc.data[0]['rcvbuf'] == '2000000' assert sctp_asc.data[1]['wmemq'] == '14' assert sctp_asc.data[1]['rcvbuf'] == '4000000' def test_sctp_eps_exceptions(): with pytest.raises(ParseException) as exc: sctp_obj = SCTPEps(context_wrap(SCTP_EPS_DETAILS_NO)) assert sctp_obj is None # Just added to remove flake8 warnings assert 'The following line is not compatible with this parser' in str(exc) with pytest.raises(SkipException) as exc: sctp_obj = SCTPEps(context_wrap(SCTP_EPS_DETAILS_NO_2)) assert sctp_obj is None # Just added to remove flake8 warnings assert 'No Contents' in str(exc) def test_sctp_asc_exceptions(): with pytest.raises(ParseException) as exc: sctp_asc = SCTPAsc(context_wrap(SCTP_ASSOC_NO_2)) assert sctp_asc is None assert 'The following line is not compatible with this parser' in str(exc) with pytest.raises(SkipException) as exc: sctp_asc = SCTPAsc(context_wrap(SCTP_ASSOC_NO)) assert sctp_asc is None assert 'No Contents' in str(exc) def test_sctp_doc_examples(): env = { 'sctp_info': SCTPEps(context_wrap(SCTP_EPS_DETAILS_DOC)), 'sctp_asc': SCTPAsc(context_wrap(SCTP_ASSOC_DOC)), 'sctp_asc_7': SCTPAsc7(context_wrap(SCTP_ASSOC_RHEL_7_DOC)), 'sctp_snmp': SCTPSnmp(context_wrap(SCTP_SNMP_DOC)) } failed, total = doctest.testmod(sctp, globs=env) assert failed == 0 def test_sctp_snmp(): sctp_snmp = SCTPSnmp(context_wrap(SCTP_SNMP)) assert sorted(sctp_snmp) == sorted({'SctpCurrEstab': 5380, 'SctpActiveEstabs': 12749, 'SctpPassiveEstabs': 55, 'SctpAborteds': 2142, 'SctpShutdowns': 5295, 'SctpOutOfBlues': 36786, 'SctpChecksumErrors': 0, 'SctpOutCtrlChunks': 1051492, 'SctpOutOrderChunks': 17109, 'SctpOutUnorderChunks': 0, 'SctpInCtrlChunks': 1018398, 'SctpInOrderChunks': 17033, 'SctpInUnorderChunks': 0, 'SctpFragUsrMsgs': 0, 'SctpReasmUsrMsgs': 0, 'SctpOutSCTPPacks': 1068678}) assert sctp_snmp.get('SctpCurrEstab') == 5380 assert sctp_snmp.get('SctpReasmUsrMsgs') == 0 assert sctp_snmp.get('something_else') is None def test_sctp_snmp_exceptions(): with pytest.raises(SkipException) as exc: sctp_snmp = SCTPSnmp(context_wrap(SCTP_SNMP_NO_1)) assert sctp_snmp is None assert 'No Contents' in str(exc) with pytest.raises(ParseException) as exc: sctp_snmp = SCTPSnmp(context_wrap(SCTP_SNMP_NO_2)) assert sctp_snmp is None assert 'Contents are not compatible to this parser' in str(exc)
63.320388
613
0.627492
import doctest import pytest from insights.parsers import ParseException, SkipException from insights.parsers import sctp from insights.parsers.sctp import SCTPEps from insights.parsers.sctp import SCTPAsc, SCTPAsc7 from insights.parsers.sctp import SCTPSnmp from insights.tests import context_wrap SCTP_EPS_DETAILS = """ ENDPT SOCK STY SST HBKT LPORT UID INODE LADDRS ffff88017e0a0200 ffff880299f7fa00 2 10 29 11165 200 299689357 10.0.0.102 10.0.0.70 ffff880612e81c00 ffff8803c28a1b00 2 10 30 11166 200 273361203 10.0.0.102 10.0.0.70 172.31.1.2 ffff88061fba9800 ffff88061f8a3180 2 10 31 11167 200 273361145 10.0.0.102 10.0.0.70 ffff88031e6f1a00 ffff88031dbdb180 2 10 32 11168 200 273365974 10.0.0.102 10.0.0.70 192.168.11.2 ffff88031e6f1a00 ffff88031dbdb180 2 10 32 11168 200 273365974 192.168.11.12 """.strip() SCTP_EPS_DETAILS_NO = """ ENDPT SOCK STY SST LPORT UID INODE LADDRS ffff88017e0a0200 ffff880299f7fa00 2 10 11165 200 299689357 10.0.0.102 10.0.0.70 ffff880612e81c00 ffff8803c28a1b00 2 10 11166 200 273361203 10.0.0.102 10.0.0.70 172.31.1.2 ffff88061fba9800 ffff88061f8a3180 2 10 11167 200 273361145 10.0.0.102 10.0.0.70 ffff88031e6f1a00 ffff88031dbdb180 2 10 11168 200 273365974 10.0.0.102 10.0.0.70 192.168.11.2 """.strip() SCTP_EPS_DETAILS_DOC = """ ENDPT SOCK STY SST HBKT LPORT UID INODE LADDRS ffff88017e0a0200 ffff880299f7fa00 2 10 29 11165 200 299689357 10.0.0.102 10.0.0.70 ffff880612e81c00 ffff8803c28a1b00 2 10 30 11166 200 273361203 10.0.0.102 10.0.0.70 172.31.1.2 """.strip() SCTP_EPS_DETAILS_NO_2 = """ """.strip() SCTP_ASSOC = """ ASSOC SOCK STY SST ST HBKT ASSOC-ID TX_QUEUE RX_QUEUE UID INODE LPORT RPORT LADDRS <-> RADDRS HBINT INS OUTS MAXRT T1X T2X RTXC ffff88045ac7e000 ffff88062077aa00 2 1 4 1205 963 0 0 200 273361167 11567 11166 10.0.0.102 10.0.0.70 <-> *10.0.0.109 10.0.0.77 1000 2 2 10 0 0 0 ffff88061fbf2000 ffff88060ff92500 2 1 4 1460 942 0 0 200 273360669 11566 11167 10.0.0.102 10.0.0.70 <-> *10.0.0.109 10.0.0.77 1000 2 2 10 0 0 0 ffff8803217b9000 ffff8801c6321580 2 1 4 1675 977 0 0 200 273361369 11565 11168 10.0.0.102 10.0.0.70 192.168.11.2 <-> *10.0.0.109 10.0.0.77 1000 2 2 10 0 0 0 ffff8803db908000 ffff88061e4a00c0 2 1 4 2229 967 0 0 200 273361177 12067 11166 10.0.0.102 10.0.0.70 <-> *10.0.0.110 10.0.0.78 1000 2 2 10 0 0 0 ffff88062258f000 ffff88060fffaa40 2 1 4 2485 953 0 0 200 273360681 12066 11166 10.0.0.102 10.0.0.70 <-> *10.0.0.103 10.0.0.71 1000 2 2 10 0 0 0 ffff8801ce686000 ffff8801c7083ac0 2 1 4 2741 982 0 0 200 273361381 12065 11166 10.0.0.102 10.0.0.70 <-> *10.0.0.112 10.0.0.80 1000 2 2 10 0 0 0 ffff88031e1f4000 ffff8801c6fd9b00 2 1 4 7092 1005 0 0 200 273366011 11567 11167 10.0.0.102 10.0.0.70 <-> *10.0.0.111 10.0.0.79 1000 2 2 10 0 0 0 """.strip() SCTP_ASSOC_2 = """ ASSOC SOCK STY SST ST HBKT ASSOC-ID TX_QUEUE RX_QUEUE UID INODE LPORT RPORT LADDRS <-> RADDRS HBINT INS OUTS MAXRT T1X T2X RTXC ffff8804239ca000 ffff8804238c6040 2 1 4 3091 1 0 0 500 90293 37379 3868 10.0.200.114 10.0.201.114 2010:0010:0000:0200:0000:0000:0000:0114 2010:0010:0000:0201:0000:0000:0000:0114 <-> *10.0.100.94 10.0.101.94 2010:0010:0000:0100:0000:0000:0000:0094 2010:0010:0000:0101:0000:0000:0000:0094 1000 5 5 10 0 0 0 """.strip() SCTP_ASSOC_DOC = """ ASSOC SOCK STY SST ST HBKT ASSOC-ID TX_QUEUE RX_QUEUE UID INODE LPORT RPORT LADDRS <-> RADDRS HBINT INS OUTS MAXRT T1X T2X RTXC ffff88045ac7e000 ffff88062077aa00 2 1 4 1205 963 0 0 200 273361167 11567 11166 10.0.0.102 10.0.0.70 <-> *10.0.0.109 10.0.0.77 1000 2 2 10 0 0 0 ffff88061fbf2000 ffff88060ff92500 2 1 4 1460 942 0 0 200 273360669 11566 11167 10.0.0.102 10.0.0.70 <-> *10.0.0.109 10.0.0.77 1000 2 2 10 0 0 0 """.strip() SCTP_ASSOC_NO = """ """.strip() SCTP_ASSOC_NO_2 = """ SOCK STY SST ST HBKT ASSOC-ID TX_QUEUE RX_QUEUE UID INODE LPORT RPORT LADDRS RADDRS HBINT INS OUTS MAXRT T1X T2X RTXC ffff88045ac7e000 ffff88062077aa00 2 1 4 1205 963 0 0 200 273361167 11567 11166 10.0.0.102 10.0.0.70 *10.0.0.109 10.0.0.77 1000 2 2 10 0 0 0 """.strip() SCTP_SNMP = """ SctpCurrEstab 5380 SctpActiveEstabs 12749 SctpPassiveEstabs 55 SctpAborteds 2142 SctpShutdowns 5295 SctpOutOfBlues 36786 SctpChecksumErrors 0 SctpOutCtrlChunks 1051492 SctpOutOrderChunks 17109 SctpOutUnorderChunks 0 SctpInCtrlChunks 1018398 SctpInOrderChunks 17033 SctpInUnorderChunks 0 SctpFragUsrMsgs 0 SctpReasmUsrMsgs 0 SctpOutSCTPPacks 1068678 """.strip() SCTP_SNMP_NO_1 = """ """.strip() SCTP_SNMP_NO_2 = """ SctpCurrEstab 5380 SctpActiveEstabs 12749 SctpPassiveEstabs 55 SctpAborteds 2142 SctpShutdowns 5295 SctpOutOfBlues 36786 SctpChecksumErrors 0 SctpOutCtrlChunks 1051492 SctpOutOrderChunks 17109 """.strip() SCTP_SNMP_DOC = """ SctpCurrEstab 5380 SctpActiveEstabs 12749 SctpPassiveEstabs 55 SctpAborteds 2142 SctpShutdowns 5295 SctpOutOfBlues 36786 SctpChecksumErrors 0 SctpOutCtrlChunks 1051492 """ SCTP_ASC_7 = """ ASSOC SOCK STY SST ST HBKT ASSOC-ID TX_QUEUE RX_QUEUE UID INODE LPORT RPORT LADDRS <-> RADDRS HBINT INS OUTS MAXRT T1X T2X RTXC wmema wmemq sndbuf rcvbuf ffff8805d36b3000 ffff880f8911f380 0 10 3 0 12754 0 0 0 496595 3868 3868 10.131.222.5 <-> *10.131.160.81 10.131.176.81 30000 17 10 10 0 0 0 11 12 1000000 2000000 ffff8805f17e1000 ffff881004aff380 0 10 3 0 12728 0 0 0 532396 3868 3868 10.131.222.3 <-> *10.131.160.81 10.131.176.81 30000 17 10 10 0 0 0 13 14 3000000 4000000 ffff8805f17e0000 ffff880f8a117380 0 10 3 0 12727 0 0 0 582963 3868 3868 10.131.222.8 <-> *10.131.160.81 10.131.176.81 30000 17 10 10 0 0 0 15 16 5000000 6000000 ffff88081d0bc000 ffff880f6fa66300 0 10 3 0 12726 0 0 0 582588 3868 3868 10.131.222.2 <-> *10.131.160.81 10.131.176.81 30000 17 10 10 0 0 0 17 18 7000000 8000000 ffff88081d0f5000 ffff880f00a99600 0 10 3 0 12725 0 0 0 578082 3868 3868 10.131.222.1 <-> *10.131.160.81 10.131.176.81 30000 17 10 10 0 0 0 19 20 9000000 10000000 """.strip() SCTP_ASSOC_RHEL_7_DOC = """ ASSOC SOCK STY SST ST HBKT ASSOC-ID TX_QUEUE RX_QUEUE UID INODE LPORT RPORT LADDRS <-> RADDRS HBINT INS OUTS MAXRT T1X T2X RTXC wmema wmemq sndbuf rcvbuf ffff8805d36b3000 ffff880f8911f380 0 10 3 0 12754 0 0 0 496595 3868 3868 10.131.222.5 <-> *10.131.160.81 10.131.176.81 30000 17 10 10 0 0 0 11 12 1000000 2000000 ffff8805f17e1000 ffff881004aff380 0 10 3 0 12728 0 0 0 532396 3868 3868 10.131.222.3 <-> *10.131.160.81 10.131.176.81 30000 17 10 10 0 0 0 13 14 3000000 4000000 """.strip() def test_sctp_eps(): sctp_info = SCTPEps(context_wrap(SCTP_EPS_DETAILS)) assert sorted(sctp_info.sctp_local_ports) == sorted(['11165', '11166', '11167', '11168']) assert sorted(sctp_info.sctp_local_ips) == sorted(['10.0.0.102', '10.0.0.70', '172.31.1.2', '192.168.11.2', '192.168.11.12']) assert sctp_info.sctp_eps_ips == {'ffff88017e0a0200': ['10.0.0.102', '10.0.0.70'], 'ffff880612e81c00': ['10.0.0.102', '10.0.0.70', '172.31.1.2'], 'ffff88061fba9800': ['10.0.0.102', '10.0.0.70'], 'ffff88031e6f1a00': ['10.0.0.102', '10.0.0.70', '192.168.11.2', '192.168.11.12']} assert len(sctp_info.search(local_port='11165')) == 1 def test_sctp_asc(): sctp_asc = SCTPAsc(context_wrap(SCTP_ASSOC)) assert sorted(sctp_asc.sctp_local_ports) == sorted(['11567', '11566', '11565', '12067', '12065', '12066']) assert sorted(sctp_asc.search(local_port='11565')) == sorted([{'init_chunks_send': '0', 'uid': '200', 'shutdown_chunks_send': '0', 'max_outstream': '2', 'tx_que': '0', 'inode': '273361369', 'hrtbt_intrvl': '1000', 'sk_type': '2', 'remote_addr': ['*10.0.0.109', '10.0.0.77'], 'data_chunks_retrans': '0', 'local_addr': ['10.0.0.102', '10.0.0.70', '192.168.11.2'], 'asc_id': '977', 'max_instream': '2', 'remote_port': '11168', 'asc_state': '4', 'max_retrans_atmpt': '10', 'sk_state': '1', 'socket': 'ffff8801c6321580', 'asc_struct': 'ffff8803217b9000', 'local_port': '11565', 'hash_bkt': '1675', 'rx_que': '0'}]) assert len(sctp_asc.search(local_port='11567')) == 2 assert sorted(sctp_asc.sctp_local_ips) == sorted(['10.0.0.102', '10.0.0.70', '192.168.11.2']) assert sorted(sctp_asc.sctp_remote_ips) == sorted(['*10.0.0.109', '10.0.0.77', '*10.0.0.110', '10.0.0.78', '*10.0.0.103', '10.0.0.71', '*10.0.0.112', '10.0.0.80', '*10.0.0.111', '10.0.0.79']) sctp_asc = SCTPAsc(context_wrap(SCTP_ASSOC_2)) assert sorted(sctp_asc.sctp_local_ips) == sorted(['10.0.200.114', '10.0.201.114', '2010:0010:0000:0200:0000:0000:0000:0114', '2010:0010:0000:0201:0000:0000:0000:0114']) assert sorted(sctp_asc.sctp_remote_ips) == sorted(['*10.0.100.94', '10.0.101.94', '2010:0010:0000:0100:0000:0000:0000:0094', '2010:0010:0000:0101:0000:0000:0000:0094']) sctp_asc = SCTPAsc7(context_wrap(SCTP_ASC_7)) assert sctp_asc.sctp_local_ips == sorted(['10.131.222.5', '10.131.222.3', '10.131.222.8', '10.131.222.2', '10.131.222.1']) assert sctp_asc.data[0]['rcvbuf'] == '2000000' assert sctp_asc.data[1]['wmemq'] == '14' assert sctp_asc.data[1]['rcvbuf'] == '4000000' def test_sctp_eps_exceptions(): with pytest.raises(ParseException) as exc: sctp_obj = SCTPEps(context_wrap(SCTP_EPS_DETAILS_NO)) assert sctp_obj is None assert 'The following line is not compatible with this parser' in str(exc) with pytest.raises(SkipException) as exc: sctp_obj = SCTPEps(context_wrap(SCTP_EPS_DETAILS_NO_2)) assert sctp_obj is None assert 'No Contents' in str(exc) def test_sctp_asc_exceptions(): with pytest.raises(ParseException) as exc: sctp_asc = SCTPAsc(context_wrap(SCTP_ASSOC_NO_2)) assert sctp_asc is None assert 'The following line is not compatible with this parser' in str(exc) with pytest.raises(SkipException) as exc: sctp_asc = SCTPAsc(context_wrap(SCTP_ASSOC_NO)) assert sctp_asc is None assert 'No Contents' in str(exc) def test_sctp_doc_examples(): env = { 'sctp_info': SCTPEps(context_wrap(SCTP_EPS_DETAILS_DOC)), 'sctp_asc': SCTPAsc(context_wrap(SCTP_ASSOC_DOC)), 'sctp_asc_7': SCTPAsc7(context_wrap(SCTP_ASSOC_RHEL_7_DOC)), 'sctp_snmp': SCTPSnmp(context_wrap(SCTP_SNMP_DOC)) } failed, total = doctest.testmod(sctp, globs=env) assert failed == 0 def test_sctp_snmp(): sctp_snmp = SCTPSnmp(context_wrap(SCTP_SNMP)) assert sorted(sctp_snmp) == sorted({'SctpCurrEstab': 5380, 'SctpActiveEstabs': 12749, 'SctpPassiveEstabs': 55, 'SctpAborteds': 2142, 'SctpShutdowns': 5295, 'SctpOutOfBlues': 36786, 'SctpChecksumErrors': 0, 'SctpOutCtrlChunks': 1051492, 'SctpOutOrderChunks': 17109, 'SctpOutUnorderChunks': 0, 'SctpInCtrlChunks': 1018398, 'SctpInOrderChunks': 17033, 'SctpInUnorderChunks': 0, 'SctpFragUsrMsgs': 0, 'SctpReasmUsrMsgs': 0, 'SctpOutSCTPPacks': 1068678}) assert sctp_snmp.get('SctpCurrEstab') == 5380 assert sctp_snmp.get('SctpReasmUsrMsgs') == 0 assert sctp_snmp.get('something_else') is None def test_sctp_snmp_exceptions(): with pytest.raises(SkipException) as exc: sctp_snmp = SCTPSnmp(context_wrap(SCTP_SNMP_NO_1)) assert sctp_snmp is None assert 'No Contents' in str(exc) with pytest.raises(ParseException) as exc: sctp_snmp = SCTPSnmp(context_wrap(SCTP_SNMP_NO_2)) assert sctp_snmp is None assert 'Contents are not compatible to this parser' in str(exc)
true
true
f725cb42004704deff0df6e504fa3bb2b08c1cc3
3,786
py
Python
tfx/components/schema_gen/executor_test.py
romiosarkar6991/tfx-romio
0703c1dd037c676e1d438c2e5ce831decfc9eed9
[ "Apache-2.0" ]
1
2019-10-10T06:06:12.000Z
2019-10-10T06:06:12.000Z
tfx/components/schema_gen/executor_test.py
romiosarkar6991/tfx-romio
0703c1dd037c676e1d438c2e5ce831decfc9eed9
[ "Apache-2.0" ]
null
null
null
tfx/components/schema_gen/executor_test.py
romiosarkar6991/tfx-romio
0703c1dd037c676e1d438c2e5ce831decfc9eed9
[ "Apache-2.0" ]
1
2019-10-06T03:39:58.000Z
2019-10-06T03:39:58.000Z
# Copyright 2019 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for tfx.components.schema_gen.executor.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import tensorflow as tf from tfx.components.schema_gen import executor from tfx.types import standard_artifacts from tfx.utils import io_utils class ExecutorTest(tf.test.TestCase): def setUp(self): super(ExecutorTest, self).setUp() self.source_data_dir = os.path.join( os.path.dirname(os.path.dirname(__file__)), 'testdata') self.train_stats_artifact = standard_artifacts.ExampleStatistics( split='train') self.train_stats_artifact.uri = os.path.join(self.source_data_dir, 'statistics_gen/train/') self.output_data_dir = os.path.join( os.environ.get('TEST_UNDECLARED_OUTPUTS_DIR', self.get_temp_dir()), self._testMethodName) self.schema_output = standard_artifacts.Schema() self.schema_output.uri = os.path.join(self.output_data_dir, 'schema_output') self.schema = standard_artifacts.Schema() self.schema.uri = os.path.join(self.source_data_dir, 'fixed_schema/') self.expected_schema = standard_artifacts.Schema() self.expected_schema.uri = os.path.join(self.source_data_dir, 'schema_gen/') self.input_dict = { 'stats': [self.train_stats_artifact], 'schema': None } self.output_dict = { 'output': [self.schema_output], } self.exec_properties = {'infer_feature_shape': False} def _assertSchemaEqual(self, expected_schema, actual_schema): schema_reader = io_utils.SchemaReader() expected_schema_proto = schema_reader.read( os.path.join(expected_schema.uri, executor._DEFAULT_FILE_NAME)) actual_schema_proto = schema_reader.read( os.path.join(actual_schema.uri, executor._DEFAULT_FILE_NAME)) self.assertProtoEquals(expected_schema_proto, actual_schema_proto) def testDoWithStatistics(self): schema_gen_executor = executor.Executor() schema_gen_executor.Do(self.input_dict, self.output_dict, self.exec_properties) self.assertNotEqual(0, len(tf.gfile.ListDirectory(self.schema_output.uri))) self._assertSchemaEqual(self.expected_schema, self.schema_output) def testDoWithSchema(self): self.input_dict['schema'] = [self.schema] self.input_dict.pop('stats') schema_gen_executor = executor.Executor() schema_gen_executor.Do(self.input_dict, self.output_dict, self.exec_properties) self.assertNotEqual(0, len(tf.gfile.ListDirectory(self.schema_output.uri))) self._assertSchemaEqual(self.schema, self.schema_output) def testDoWithNonExistentSchema(self): non_existent_schema = standard_artifacts.Schema() non_existent_schema.uri = '/path/to/non_existent/schema' self.input_dict['schema'] = [non_existent_schema] self.input_dict.pop('stats') with self.assertRaises(ValueError): schema_gen_executor = executor.Executor() schema_gen_executor.Do(self.input_dict, self.output_dict, self.exec_properties) if __name__ == '__main__': tf.test.main()
37.485149
80
0.726889
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import tensorflow as tf from tfx.components.schema_gen import executor from tfx.types import standard_artifacts from tfx.utils import io_utils class ExecutorTest(tf.test.TestCase): def setUp(self): super(ExecutorTest, self).setUp() self.source_data_dir = os.path.join( os.path.dirname(os.path.dirname(__file__)), 'testdata') self.train_stats_artifact = standard_artifacts.ExampleStatistics( split='train') self.train_stats_artifact.uri = os.path.join(self.source_data_dir, 'statistics_gen/train/') self.output_data_dir = os.path.join( os.environ.get('TEST_UNDECLARED_OUTPUTS_DIR', self.get_temp_dir()), self._testMethodName) self.schema_output = standard_artifacts.Schema() self.schema_output.uri = os.path.join(self.output_data_dir, 'schema_output') self.schema = standard_artifacts.Schema() self.schema.uri = os.path.join(self.source_data_dir, 'fixed_schema/') self.expected_schema = standard_artifacts.Schema() self.expected_schema.uri = os.path.join(self.source_data_dir, 'schema_gen/') self.input_dict = { 'stats': [self.train_stats_artifact], 'schema': None } self.output_dict = { 'output': [self.schema_output], } self.exec_properties = {'infer_feature_shape': False} def _assertSchemaEqual(self, expected_schema, actual_schema): schema_reader = io_utils.SchemaReader() expected_schema_proto = schema_reader.read( os.path.join(expected_schema.uri, executor._DEFAULT_FILE_NAME)) actual_schema_proto = schema_reader.read( os.path.join(actual_schema.uri, executor._DEFAULT_FILE_NAME)) self.assertProtoEquals(expected_schema_proto, actual_schema_proto) def testDoWithStatistics(self): schema_gen_executor = executor.Executor() schema_gen_executor.Do(self.input_dict, self.output_dict, self.exec_properties) self.assertNotEqual(0, len(tf.gfile.ListDirectory(self.schema_output.uri))) self._assertSchemaEqual(self.expected_schema, self.schema_output) def testDoWithSchema(self): self.input_dict['schema'] = [self.schema] self.input_dict.pop('stats') schema_gen_executor = executor.Executor() schema_gen_executor.Do(self.input_dict, self.output_dict, self.exec_properties) self.assertNotEqual(0, len(tf.gfile.ListDirectory(self.schema_output.uri))) self._assertSchemaEqual(self.schema, self.schema_output) def testDoWithNonExistentSchema(self): non_existent_schema = standard_artifacts.Schema() non_existent_schema.uri = '/path/to/non_existent/schema' self.input_dict['schema'] = [non_existent_schema] self.input_dict.pop('stats') with self.assertRaises(ValueError): schema_gen_executor = executor.Executor() schema_gen_executor.Do(self.input_dict, self.output_dict, self.exec_properties) if __name__ == '__main__': tf.test.main()
true
true
f725cc0039395be7b59dace596d9541c0d6016db
4,406
py
Python
python_for_web/public/Lib/site-packages/jinja2/meta.py
ServerCetin/hello_python3
7cf0807e09c819c690f28ee30758f22355c79115
[ "MIT" ]
null
null
null
python_for_web/public/Lib/site-packages/jinja2/meta.py
ServerCetin/hello_python3
7cf0807e09c819c690f28ee30758f22355c79115
[ "MIT" ]
null
null
null
python_for_web/public/Lib/site-packages/jinja2/meta.py
ServerCetin/hello_python3
7cf0807e09c819c690f28ee30758f22355c79115
[ "MIT" ]
null
null
null
"""Functions that expose information about templates that might be interesting for introspection. """ import typing as t from . import nodes from .compiler import CodeGenerator from .compiler import Frame if t.TYPE_CHECKING: from .environment import Environment class TrackingCodeGenerator(CodeGenerator): """We abuse the code generator for introspection.""" def __init__(self, environment: "Environment") -> None: super().__init__(environment, "<introspection>", "<introspection>") self.undeclared_identifiers: t.Set[str] = set() def write(self, x: str) -> None: """Don't write.""" def enter_frame(self, frame: Frame) -> None: """Remember all undeclared identifiers.""" super().enter_frame(frame) for _, (action, param) in frame.symbols.loads.items(): if action == "resolve" and param not in self.environment.globals: self.undeclared_identifiers.add(param) def find_undeclared_variables(ast: nodes.Template) -> t.Set[str]: """Returns a set of all variables in the AST that will be looked up from the context at runtime. Because at compile time it's not known which variables will be used depending on the path the execution takes at runtime, all variables are returned. >>> from jinja2 import Environment, meta >>> env = Environment() >>> ast = env.parse('{% set foo = 42 %}{{ bar + foo }}') >>> meta.find_undeclared_variables(ast) == {'bar'} True .. admonition:: Implementation Internally the code generator is used for finding undeclared variables. This is good to know because the code generator might raise a :exc:`TemplateAssertionError` during compilation and as a matter of fact this function can currently raise that exception as well. """ codegen = TrackingCodeGenerator(ast.environment) # type: ignore codegen.visit(ast) return codegen.undeclared_identifiers _ref_types = (nodes.Extends, nodes.FromImport, nodes.Import, nodes.Include) _RefType = t.Union[nodes.Extends, nodes.FromImport, nodes.Import, nodes.Include] def find_referenced_templates(ast: nodes.Template) -> t.Iterator[t.Optional[str]]: """Finds all the referenced templates from the AST. This will return an iterator over all the hardcoded template extensions, inclusions and imports. If dynamic inheritance or inclusion is used, `None` will be yielded. >>> from jinja2 import Environment, meta >>> env = Environment() >>> ast = env.parse('{% extends "layout.templates" %}{% include helper %}') >>> list(meta.find_referenced_templates(ast)) ['layout.templates', None] This function is useful for dependency tracking. For example if you want to rebuild parts of the website after a layout template has changed. """ template_name: t.Any for node in ast.find_all(_ref_types): template: nodes.Expr = node.template # type: ignore if not isinstance(template, nodes.Const): # a tuple with some non consts in there if isinstance(template, (nodes.Tuple, nodes.List)): for template_name in template.items: # something const, only yield the strings and ignore # non-string consts that really just make no sense if isinstance(template_name, nodes.Const): if isinstance(template_name.value, str): yield template_name.value # something dynamic in there else: yield None # something dynamic we don't know about here else: yield None continue # constant is a basestring, direct template name if isinstance(template.value, str): yield template.value # a tuple or list (latter *should* not happen) made of consts, # yield the consts that are strings. We could warn here for # non string values elif isinstance(node, nodes.Include) and isinstance( template.value, (tuple, list) ): for template_name in template.value: if isinstance(template_name, str): yield template_name # something else we don't care about, we could warn here else: yield None
39.339286
82
0.648207
import typing as t from . import nodes from .compiler import CodeGenerator from .compiler import Frame if t.TYPE_CHECKING: from .environment import Environment class TrackingCodeGenerator(CodeGenerator): def __init__(self, environment: "Environment") -> None: super().__init__(environment, "<introspection>", "<introspection>") self.undeclared_identifiers: t.Set[str] = set() def write(self, x: str) -> None: def enter_frame(self, frame: Frame) -> None: super().enter_frame(frame) for _, (action, param) in frame.symbols.loads.items(): if action == "resolve" and param not in self.environment.globals: self.undeclared_identifiers.add(param) def find_undeclared_variables(ast: nodes.Template) -> t.Set[str]: codegen = TrackingCodeGenerator(ast.environment) codegen.visit(ast) return codegen.undeclared_identifiers _ref_types = (nodes.Extends, nodes.FromImport, nodes.Import, nodes.Include) _RefType = t.Union[nodes.Extends, nodes.FromImport, nodes.Import, nodes.Include] def find_referenced_templates(ast: nodes.Template) -> t.Iterator[t.Optional[str]]: template_name: t.Any for node in ast.find_all(_ref_types): template: nodes.Expr = node.template if not isinstance(template, nodes.Const): if isinstance(template, (nodes.Tuple, nodes.List)): for template_name in template.items: if isinstance(template_name, nodes.Const): if isinstance(template_name.value, str): yield template_name.value else: yield None else: yield None continue # constant is a basestring, direct template name if isinstance(template.value, str): yield template.value # a tuple or list (latter *should* not happen) made of consts, # yield the consts that are strings. We could warn here for # non string values elif isinstance(node, nodes.Include) and isinstance( template.value, (tuple, list) ): for template_name in template.value: if isinstance(template_name, str): yield template_name # something else we don't care about, we could warn here else: yield None
true
true
f725cc62788a18a8035e2f36032fa0d43ceb3487
45,696
py
Python
python/ccxt/coinbasepro.py
springrider/ccxt
39570694e5cfc9a315a0f05b2d06cf8b1d550c24
[ "MIT" ]
1
2021-03-31T18:35:43.000Z
2021-03-31T18:35:43.000Z
python/ccxt/coinbasepro.py
springrider/ccxt
39570694e5cfc9a315a0f05b2d06cf8b1d550c24
[ "MIT" ]
null
null
null
python/ccxt/coinbasepro.py
springrider/ccxt
39570694e5cfc9a315a0f05b2d06cf8b1d550c24
[ "MIT" ]
2
2021-05-08T04:01:00.000Z
2022-03-24T04:46:21.000Z
# -*- coding: utf-8 -*- # PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN: # https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code from ccxt.base.exchange import Exchange # ----------------------------------------------------------------------------- try: basestring # Python 3 except NameError: basestring = str # Python 2 import hashlib from ccxt.base.errors import ExchangeError from ccxt.base.errors import AuthenticationError from ccxt.base.errors import PermissionDenied from ccxt.base.errors import ArgumentsRequired from ccxt.base.errors import InsufficientFunds from ccxt.base.errors import InvalidAddress from ccxt.base.errors import InvalidOrder from ccxt.base.errors import OrderNotFound from ccxt.base.errors import NotSupported from ccxt.base.errors import RateLimitExceeded from ccxt.base.errors import OnMaintenance from ccxt.base.decimal_to_precision import TICK_SIZE from ccxt.base.precise import Precise class coinbasepro(Exchange): def describe(self): return self.deep_extend(super(coinbasepro, self).describe(), { 'id': 'coinbasepro', 'name': 'Coinbase Pro', 'countries': ['US'], 'rateLimit': 1000, 'userAgent': self.userAgents['chrome'], 'pro': True, 'has': { 'cancelAllOrders': True, 'cancelOrder': True, 'CORS': True, 'createDepositAddress': True, 'createOrder': True, 'deposit': True, 'fetchAccounts': True, 'fetchBalance': True, 'fetchCurrencies': True, 'fetchClosedOrders': True, 'fetchDepositAddress': False, # the exchange does not have self method, only createDepositAddress, see https://github.com/ccxt/ccxt/pull/7405 'fetchMarkets': True, 'fetchMyTrades': True, 'fetchOHLCV': True, 'fetchOpenOrders': True, 'fetchOrder': True, 'fetchOrderBook': True, 'fetchOrders': True, 'fetchOrderTrades': True, 'fetchTime': True, 'fetchTicker': True, 'fetchTrades': True, 'fetchTransactions': True, 'withdraw': True, 'fetchDeposits': True, 'fetchWithdrawals': True, }, 'timeframes': { '1m': 60, '5m': 300, '15m': 900, '1h': 3600, '6h': 21600, '1d': 86400, }, 'hostname': 'pro.coinbase.com', 'urls': { 'test': { 'public': 'https://api-public.sandbox.pro.coinbase.com', 'private': 'https://api-public.sandbox.pro.coinbase.com', }, 'logo': 'https://user-images.githubusercontent.com/1294454/41764625-63b7ffde-760a-11e8-996d-a6328fa9347a.jpg', 'api': { 'public': 'https://api.{hostname}', 'private': 'https://api.{hostname}', }, 'www': 'https://pro.coinbase.com/', 'doc': 'https://docs.pro.coinbase.com', 'fees': [ 'https://docs.pro.coinbase.com/#fees', 'https://support.pro.coinbase.com/customer/en/portal/articles/2945310-fees', ], }, 'requiredCredentials': { 'apiKey': True, 'secret': True, 'password': True, }, 'api': { 'public': { 'get': [ 'currencies', 'products', 'products/{id}', 'products/{id}/book', 'products/{id}/candles', 'products/{id}/stats', 'products/{id}/ticker', 'products/{id}/trades', 'time', ], }, 'private': { 'get': [ 'accounts', 'accounts/{id}', 'accounts/{id}/holds', 'accounts/{id}/ledger', 'accounts/{id}/transfers', 'coinbase-accounts', 'fills', 'funding', 'fees', 'margin/profile_information', 'margin/buying_power', 'margin/withdrawal_power', 'margin/withdrawal_power_all', 'margin/exit_plan', 'margin/liquidation_history', 'margin/position_refresh_amounts', 'margin/status', 'oracle', 'orders', 'orders/{id}', 'orders/client:{client_oid}', 'otc/orders', 'payment-methods', 'position', 'profiles', 'profiles/{id}', 'reports/{report_id}', 'transfers', 'transfers/{transfer_id}', 'users/self/exchange-limits', 'users/self/hold-balances', 'users/self/trailing-volume', 'withdrawals/fee-estimate', ], 'post': [ 'conversions', 'deposits/coinbase-account', 'deposits/payment-method', 'coinbase-accounts/{id}/addresses', 'funding/repay', 'orders', 'position/close', 'profiles/margin-transfer', 'profiles/transfer', 'reports', 'withdrawals/coinbase', 'withdrawals/coinbase-account', 'withdrawals/crypto', 'withdrawals/payment-method', ], 'delete': [ 'orders', 'orders/client:{client_oid}', 'orders/{id}', ], }, }, 'commonCurrencies': { 'CGLD': 'CELO', }, 'precisionMode': TICK_SIZE, 'fees': { 'trading': { 'tierBased': True, # complicated tier system per coin 'percentage': True, 'maker': 0.5 / 100, # highest fee of all tiers 'taker': 0.5 / 100, # highest fee of all tiers }, 'funding': { 'tierBased': False, 'percentage': False, 'withdraw': { 'BCH': 0, 'BTC': 0, 'LTC': 0, 'ETH': 0, 'EUR': 0.15, 'USD': 25, }, 'deposit': { 'BCH': 0, 'BTC': 0, 'LTC': 0, 'ETH': 0, 'EUR': 0.15, 'USD': 10, }, }, }, 'exceptions': { 'exact': { 'Insufficient funds': InsufficientFunds, 'NotFound': OrderNotFound, 'Invalid API Key': AuthenticationError, 'invalid signature': AuthenticationError, 'Invalid Passphrase': AuthenticationError, 'Invalid order id': InvalidOrder, 'Private rate limit exceeded': RateLimitExceeded, 'Trading pair not available': PermissionDenied, 'Product not found': InvalidOrder, }, 'broad': { 'Order already done': OrderNotFound, 'order not found': OrderNotFound, 'price too small': InvalidOrder, 'price too precise': InvalidOrder, 'under maintenance': OnMaintenance, 'size is too small': InvalidOrder, 'Cancel only mode': OnMaintenance, # https://github.com/ccxt/ccxt/issues/7690 }, }, }) def fetch_currencies(self, params={}): response = self.publicGetCurrencies(params) # # [ # { # id: 'XTZ', # name: 'Tezos', # min_size: '0.000001', # status: 'online', # message: '', # max_precision: '0.000001', # convertible_to: [], # details: { # type: 'crypto', # symbol: 'Τ', # network_confirmations: 60, # sort_order: 53, # crypto_address_link: 'https://tzstats.com/{{address}}', # crypto_transaction_link: 'https://tzstats.com/{{txId}}', # push_payment_methods: ['crypto'], # group_types: [], # display_name: '', # processing_time_seconds: 0, # min_withdrawal_amount: 1 # } # } # ] # result = {} for i in range(0, len(response)): currency = response[i] id = self.safe_string(currency, 'id') name = self.safe_string(currency, 'name') code = self.safe_currency_code(id) details = self.safe_value(currency, 'details', {}) precision = self.safe_number(currency, 'max_precision') status = self.safe_string(currency, 'status') active = (status == 'online') result[code] = { 'id': id, 'code': code, 'info': currency, 'type': self.safe_string(details, 'type'), 'name': name, 'active': active, 'fee': None, 'precision': precision, 'limits': { 'amount': { 'min': self.safe_number(details, 'min_size'), 'max': None, }, 'withdraw': { 'min': self.safe_number(details, 'min_withdrawal_amount'), 'max': None, }, }, } return result def fetch_markets(self, params={}): response = self.publicGetProducts(params) # # [ # { # "id":"ZEC-BTC", # "base_currency":"ZEC", # "quote_currency":"BTC", # "base_min_size":"0.01000000", # "base_max_size":"1500.00000000", # "quote_increment":"0.00000100", # "base_increment":"0.00010000", # "display_name":"ZEC/BTC", # "min_market_funds":"0.001", # "max_market_funds":"30", # "margin_enabled":false, # "post_only":false, # "limit_only":false, # "cancel_only":false, # "trading_disabled":false, # "status":"online", # "status_message":"" # } # ] # result = [] for i in range(0, len(response)): market = response[i] id = self.safe_string(market, 'id') baseId = self.safe_string(market, 'base_currency') quoteId = self.safe_string(market, 'quote_currency') base = self.safe_currency_code(baseId) quote = self.safe_currency_code(quoteId) symbol = base + '/' + quote priceLimits = { 'min': self.safe_number(market, 'quote_increment'), 'max': None, } precision = { 'amount': self.safe_number(market, 'base_increment'), 'price': self.safe_number(market, 'quote_increment'), } status = self.safe_string(market, 'status') active = (status == 'online') result.append(self.extend(self.fees['trading'], { 'id': id, 'symbol': symbol, 'baseId': baseId, 'quoteId': quoteId, 'base': base, 'quote': quote, 'precision': precision, 'limits': { 'amount': { 'min': self.safe_number(market, 'base_min_size'), 'max': self.safe_number(market, 'base_max_size'), }, 'price': priceLimits, 'cost': { 'min': self.safe_number(market, 'min_market_funds'), 'max': self.safe_number(market, 'max_market_funds'), }, }, 'active': active, 'info': market, })) return result def fetch_accounts(self, params={}): self.load_markets() response = self.privateGetAccounts(params) # # [ # { # id: '4aac9c60-cbda-4396-9da4-4aa71e95fba0', # currency: 'BTC', # balance: '0.0000000000000000', # available: '0', # hold: '0.0000000000000000', # profile_id: 'b709263e-f42a-4c7d-949a-a95c83d065da' # }, # { # id: 'f75fa69a-1ad1-4a80-bd61-ee7faa6135a3', # currency: 'USDC', # balance: '0.0000000000000000', # available: '0', # hold: '0.0000000000000000', # profile_id: 'b709263e-f42a-4c7d-949a-a95c83d065da' # }, # ] # result = [] for i in range(0, len(response)): account = response[i] accountId = self.safe_string(account, 'id') currencyId = self.safe_string(account, 'currency') code = self.safe_currency_code(currencyId) result.append({ 'id': accountId, 'type': None, 'currency': code, 'info': account, }) return result def fetch_balance(self, params={}): self.load_markets() response = self.privateGetAccounts(params) result = {'info': response} for i in range(0, len(response)): balance = response[i] currencyId = self.safe_string(balance, 'currency') code = self.safe_currency_code(currencyId) account = self.account() account['free'] = self.safe_string(balance, 'available') account['used'] = self.safe_string(balance, 'hold') account['total'] = self.safe_string(balance, 'balance') result[code] = account return self.parse_balance(result, False) def fetch_order_book(self, symbol, limit=None, params={}): self.load_markets() # level 1 - only the best bid and ask # level 2 - top 50 bids and asks(aggregated) # level 3 - full order book(non aggregated) request = { 'id': self.market_id(symbol), 'level': 2, # 1 best bidask, 2 aggregated, 3 full } response = self.publicGetProductsIdBook(self.extend(request, params)) # # { # "sequence":1924393896, # "bids":[ # ["0.01825","24.34811287",2], # ["0.01824","72.5463",3], # ["0.01823","424.54298049",6], # ], # "asks":[ # ["0.01826","171.10414904",4], # ["0.01827","22.60427028",1], # ["0.01828","397.46018784",7], # ] # } # orderbook = self.parse_order_book(response, symbol) orderbook['nonce'] = self.safe_integer(response, 'sequence') return orderbook def parse_ticker(self, ticker, market=None): # # publicGetProductsIdTicker # # { # "trade_id":843439, # "price":"0.997999", # "size":"80.29769", # "time":"2020-01-28T02:13:33.012523Z", # "bid":"0.997094", # "ask":"0.998", # "volume":"1903188.03750000" # } # # publicGetProductsIdStats # # { # "open": "34.19000000", # "high": "95.70000000", # "low": "7.06000000", # "volume": "2.41000000" # } # timestamp = self.parse8601(self.safe_value(ticker, 'time')) bid = self.safe_number(ticker, 'bid') ask = self.safe_number(ticker, 'ask') last = self.safe_number(ticker, 'price') symbol = None if (market is None) else market['symbol'] return { 'symbol': symbol, 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'high': self.safe_number(ticker, 'high'), 'low': self.safe_number(ticker, 'low'), 'bid': bid, 'bidVolume': None, 'ask': ask, 'askVolume': None, 'vwap': None, 'open': self.safe_number(ticker, 'open'), 'close': last, 'last': last, 'previousClose': None, 'change': None, 'percentage': None, 'average': None, 'baseVolume': self.safe_number(ticker, 'volume'), 'quoteVolume': None, 'info': ticker, } def fetch_ticker(self, symbol, params={}): self.load_markets() market = self.market(symbol) request = { 'id': market['id'], } # publicGetProductsIdTicker or publicGetProductsIdStats method = self.safe_string(self.options, 'fetchTickerMethod', 'publicGetProductsIdTicker') response = getattr(self, method)(self.extend(request, params)) # # publicGetProductsIdTicker # # { # "trade_id":843439, # "price":"0.997999", # "size":"80.29769", # "time":"2020-01-28T02:13:33.012523Z", # "bid":"0.997094", # "ask":"0.998", # "volume":"1903188.03750000" # } # # publicGetProductsIdStats # # { # "open": "34.19000000", # "high": "95.70000000", # "low": "7.06000000", # "volume": "2.41000000" # } # return self.parse_ticker(response, market) def parse_trade(self, trade, market=None): # # { # type: 'match', # trade_id: 82047307, # maker_order_id: '0f358725-2134-435e-be11-753912a326e0', # taker_order_id: '252b7002-87a3-425c-ac73-f5b9e23f3caf', # order_id: 'd50ec984-77a8-460a-b958-66f114b0de9b', # side: 'sell', # size: '0.00513192', # price: '9314.78', # product_id: 'BTC-USD', # profile_id: '6244401d-c078-40d9-b305-7ad3551bc3b0', # sequence: 12038915443, # time: '2020-01-31T20:03:41.158814Z' # created_at: '2014-11-07T22:19:28.578544Z', # liquidity: 'T', # fee: '0.00025', # settled: True, # usd_volume: '0.0924556000000000', # user_id: '595eb864313c2b02ddf2937d' # } # timestamp = self.parse8601(self.safe_string_2(trade, 'time', 'created_at')) marketId = self.safe_string(trade, 'product_id') symbol = self.safe_symbol(marketId, market, '-') feeRate = None feeCurrency = None takerOrMaker = None cost = None if market is not None: feeCurrencyId = self.safe_string_lower(market, 'quoteId') costField = feeCurrencyId + '_value' cost = self.safe_number(trade, costField) feeCurrency = market['quote'] liquidity = self.safe_string(trade, 'liquidity') if liquidity is not None: takerOrMaker = 'taker' if (liquidity == 'T') else 'maker' feeRate = market[takerOrMaker] feeCost = self.safe_number_2(trade, 'fill_fees', 'fee') fee = { 'cost': feeCost, 'currency': feeCurrency, 'rate': feeRate, } type = None id = self.safe_string(trade, 'trade_id') side = 'sell' if (trade['side'] == 'buy') else 'buy' orderId = self.safe_string(trade, 'order_id') # Coinbase Pro returns inverted side to fetchMyTrades vs fetchTrades makerOrderId = self.safe_string(trade, 'maker_order_id') takerOrderId = self.safe_string(trade, 'taker_order_id') if (orderId is not None) or ((makerOrderId is not None) and (takerOrderId is not None)): side = 'buy' if (trade['side'] == 'buy') else 'sell' priceString = self.safe_string(trade, 'price') amountString = self.safe_string(trade, 'size') price = self.parse_number(priceString) amount = self.parse_number(amountString) if cost is None: cost = self.parse_number(Precise.string_mul(priceString, amountString)) return { 'id': id, 'order': orderId, 'info': trade, 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'symbol': symbol, 'type': type, 'takerOrMaker': takerOrMaker, 'side': side, 'price': price, 'amount': amount, 'fee': fee, 'cost': cost, } def fetch_my_trades(self, symbol=None, since=None, limit=None, params={}): # as of 2018-08-23 if symbol is None: raise ArgumentsRequired(self.id + ' fetchMyTrades() requires a symbol argument') self.load_markets() market = self.market(symbol) request = { 'product_id': market['id'], } if limit is not None: request['limit'] = limit response = self.privateGetFills(self.extend(request, params)) return self.parse_trades(response, market, since, limit) def fetch_trades(self, symbol, since=None, limit=None, params={}): self.load_markets() market = self.market(symbol) request = { 'id': market['id'], # fixes issue #2 } if limit is not None: request['limit'] = limit # default 100 response = self.publicGetProductsIdTrades(self.extend(request, params)) return self.parse_trades(response, market, since, limit) def parse_ohlcv(self, ohlcv, market=None): # # [ # 1591514160, # 0.02507, # 0.02507, # 0.02507, # 0.02507, # 0.02816506 # ] # return [ self.safe_timestamp(ohlcv, 0), self.safe_number(ohlcv, 3), self.safe_number(ohlcv, 2), self.safe_number(ohlcv, 1), self.safe_number(ohlcv, 4), self.safe_number(ohlcv, 5), ] def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}): self.load_markets() market = self.market(symbol) granularity = self.timeframes[timeframe] request = { 'id': market['id'], 'granularity': granularity, } if since is not None: request['start'] = self.iso8601(since) if limit is None: # https://docs.pro.coinbase.com/#get-historic-rates limit = 300 # max = 300 else: limit = min(300, limit) request['end'] = self.iso8601(self.sum((limit - 1) * granularity * 1000, since)) response = self.publicGetProductsIdCandles(self.extend(request, params)) # # [ # [1591514160,0.02507,0.02507,0.02507,0.02507,0.02816506], # [1591514100,0.02507,0.02507,0.02507,0.02507,1.63830323], # [1591514040,0.02505,0.02507,0.02505,0.02507,0.19918178] # ] # return self.parse_ohlcvs(response, market, timeframe, since, limit) def fetch_time(self, params={}): response = self.publicGetTime(params) # # { # "iso":"2020-05-12T08:00:51.504Z", # "epoch":1589270451.504 # } # return self.safe_timestamp(response, 'epoch') def parse_order_status(self, status): statuses = { 'pending': 'open', 'active': 'open', 'open': 'open', 'done': 'closed', 'canceled': 'canceled', 'canceling': 'open', } return self.safe_string(statuses, status, status) def parse_order(self, order, market=None): # # createOrder # # { # "id": "d0c5340b-6d6c-49d9-b567-48c4bfca13d2", # "price": "0.10000000", # "size": "0.01000000", # "product_id": "BTC-USD", # "side": "buy", # "stp": "dc", # "type": "limit", # "time_in_force": "GTC", # "post_only": False, # "created_at": "2016-12-08T20:02:28.53864Z", # "fill_fees": "0.0000000000000000", # "filled_size": "0.00000000", # "executed_value": "0.0000000000000000", # "status": "pending", # "settled": False # } # timestamp = self.parse8601(self.safe_string(order, 'created_at')) marketId = self.safe_string(order, 'product_id') market = self.safe_market(marketId, market, '-') status = self.parse_order_status(self.safe_string(order, 'status')) price = self.safe_number(order, 'price') filled = self.safe_number(order, 'filled_size') amount = self.safe_number(order, 'size', filled) cost = self.safe_number(order, 'executed_value') feeCost = self.safe_number(order, 'fill_fees') fee = None if feeCost is not None: feeCurrencyCode = None if market is not None: feeCurrencyCode = market['quote'] fee = { 'cost': feeCost, 'currency': feeCurrencyCode, 'rate': None, } id = self.safe_string(order, 'id') type = self.safe_string(order, 'type') side = self.safe_string(order, 'side') timeInForce = self.safe_string(order, 'time_in_force') postOnly = self.safe_value(order, 'post_only') stopPrice = self.safe_number(order, 'stop_price') clientOrderId = self.safe_string(order, 'client_oid') return self.safe_order({ 'id': id, 'clientOrderId': clientOrderId, 'info': order, 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'lastTradeTimestamp': None, 'status': status, 'symbol': market['symbol'], 'type': type, 'timeInForce': timeInForce, 'postOnly': postOnly, 'side': side, 'price': price, 'stopPrice': stopPrice, 'cost': cost, 'amount': amount, 'filled': filled, 'remaining': None, 'fee': fee, 'average': None, 'trades': None, }) def fetch_order(self, id, symbol=None, params={}): self.load_markets() request = {} clientOrderId = self.safe_string_2(params, 'clientOrderId', 'client_oid') method = None if clientOrderId is None: method = 'privateGetOrdersId' request['id'] = id else: method = 'privateGetOrdersClientClientOid' request['client_oid'] = clientOrderId params = self.omit(params, ['clientOrderId', 'client_oid']) response = getattr(self, method)(self.extend(request, params)) return self.parse_order(response) def fetch_order_trades(self, id, symbol=None, since=None, limit=None, params={}): self.load_markets() market = None if symbol is not None: market = self.market(symbol) request = { 'order_id': id, } response = self.privateGetFills(self.extend(request, params)) return self.parse_trades(response, market, since, limit) def fetch_orders(self, symbol=None, since=None, limit=None, params={}): request = { 'status': 'all', } return self.fetch_open_orders(symbol, since, limit, self.extend(request, params)) def fetch_open_orders(self, symbol=None, since=None, limit=None, params={}): self.load_markets() request = {} market = None if symbol is not None: market = self.market(symbol) request['product_id'] = market['id'] if limit is not None: request['limit'] = limit # default 100 response = self.privateGetOrders(self.extend(request, params)) return self.parse_orders(response, market, since, limit) def fetch_closed_orders(self, symbol=None, since=None, limit=None, params={}): request = { 'status': 'done', } return self.fetch_open_orders(symbol, since, limit, self.extend(request, params)) def create_order(self, symbol, type, side, amount, price=None, params={}): self.load_markets() market = self.market(symbol) request = { # common params -------------------------------------------------- # 'client_oid': clientOrderId, 'type': type, 'side': side, 'product_id': market['id'], # 'size': self.amount_to_precision(symbol, amount), # 'stp': 'dc', # self-trade prevention, dc = decrease and cancel, co = cancel oldest, cn = cancel newest, cb = cancel both # 'stop': 'loss', # "loss" = stop loss below price, "entry" = take profit above price # 'stop_price': self.price_to_precision(symbol, price), # limit order params --------------------------------------------- # 'price': self.price_to_precision(symbol, price), # 'size': self.amount_to_precision(symbol, amount), # 'time_in_force': 'GTC', # GTC, GTT, IOC, or FOK # 'cancel_after' [optional]* min, hour, day, requires time_in_force to be GTT # 'post_only': False, # invalid when time_in_force is IOC or FOK # market order params -------------------------------------------- # 'size': self.amount_to_precision(symbol, amount), # 'funds': self.cost_to_precision(symbol, amount), } clientOrderId = self.safe_string_2(params, 'clientOrderId', 'client_oid') if clientOrderId is not None: request['client_oid'] = clientOrderId params = self.omit(params, ['clientOrderId', 'client_oid']) stopPrice = self.safe_number_2(params, 'stopPrice', 'stop_price') if stopPrice is not None: request['stop_price'] = self.price_to_precision(symbol, stopPrice) params = self.omit(params, ['stopPrice', 'stop_price']) timeInForce = self.safe_string_2(params, 'timeInForce', 'time_in_force') if timeInForce is not None: request['time_in_force'] = timeInForce params = self.omit(params, ['timeInForce', 'time_in_force']) if type == 'limit': request['price'] = self.price_to_precision(symbol, price) request['size'] = self.amount_to_precision(symbol, amount) elif type == 'market': cost = self.safe_number_2(params, 'cost', 'funds') if cost is None: if price is not None: cost = amount * price else: params = self.omit(params, ['cost', 'funds']) if cost is not None: request['funds'] = self.cost_to_precision(symbol, cost) else: request['size'] = self.amount_to_precision(symbol, amount) response = self.privatePostOrders(self.extend(request, params)) # # { # "id": "d0c5340b-6d6c-49d9-b567-48c4bfca13d2", # "price": "0.10000000", # "size": "0.01000000", # "product_id": "BTC-USD", # "side": "buy", # "stp": "dc", # "type": "limit", # "time_in_force": "GTC", # "post_only": False, # "created_at": "2016-12-08T20:02:28.53864Z", # "fill_fees": "0.0000000000000000", # "filled_size": "0.00000000", # "executed_value": "0.0000000000000000", # "status": "pending", # "settled": False # } # return self.parse_order(response, market) def cancel_order(self, id, symbol=None, params={}): self.load_markets() request = { # 'product_id': market['id'], # the request will be more performant if you include it } clientOrderId = self.safe_string_2(params, 'clientOrderId', 'client_oid') method = None if clientOrderId is None: method = 'privateDeleteOrdersId' request['id'] = id else: method = 'privateDeleteOrdersClientClientOid' request['client_oid'] = clientOrderId params = self.omit(params, ['clientOrderId', 'client_oid']) market = None if symbol is not None: market = self.market(symbol) request['product_id'] = market['symbol'] # the request will be more performant if you include it return getattr(self, method)(self.extend(request, params)) def cancel_all_orders(self, symbol=None, params={}): self.load_markets() request = {} market = None if symbol is not None: market = self.market(symbol) request['product_id'] = market['symbol'] # the request will be more performant if you include it return self.privateDeleteOrders(self.extend(request, params)) def fetch_payment_methods(self, params={}): return self.privateGetPaymentMethods(params) def deposit(self, code, amount, address, params={}): self.load_markets() currency = self.currency(code) request = { 'currency': currency['id'], 'amount': amount, } method = 'privatePostDeposits' if 'payment_method_id' in params: # deposit from a payment_method, like a bank account method += 'PaymentMethod' elif 'coinbase_account_id' in params: # deposit into Coinbase Pro account from a Coinbase account method += 'CoinbaseAccount' else: # deposit methodotherwise we did not receive a supported deposit location # relevant docs link for the Googlers # https://docs.pro.coinbase.com/#deposits raise NotSupported(self.id + ' deposit() requires one of `coinbase_account_id` or `payment_method_id` extra params') response = getattr(self, method)(self.extend(request, params)) if not response: raise ExchangeError(self.id + ' deposit() error: ' + self.json(response)) return { 'info': response, 'id': response['id'], } def withdraw(self, code, amount, address, tag=None, params={}): self.check_address(address) self.load_markets() currency = self.currency(code) request = { 'currency': currency['id'], 'amount': amount, } method = 'privatePostWithdrawals' if 'payment_method_id' in params: method += 'PaymentMethod' elif 'coinbase_account_id' in params: method += 'CoinbaseAccount' else: method += 'Crypto' request['crypto_address'] = address if tag is not None: request['destination_tag'] = tag response = getattr(self, method)(self.extend(request, params)) if not response: raise ExchangeError(self.id + ' withdraw() error: ' + self.json(response)) return { 'info': response, 'id': response['id'], } def fetch_transactions(self, code=None, since=None, limit=None, params={}): self.load_markets() self.load_accounts() currency = None id = self.safe_string(params, 'id') # account id if id is None: if code is not None: currency = self.currency(code) accountsByCurrencyCode = self.index_by(self.accounts, 'currency') account = self.safe_value(accountsByCurrencyCode, code) if account is None: raise ExchangeError(self.id + ' fetchTransactions() could not find account id for ' + code) id = account['id'] request = {} if id is not None: request['id'] = id if limit is not None: request['limit'] = limit response = None if id is None: response = self.privateGetTransfers(self.extend(request, params)) for i in range(0, len(response)): account_id = self.safe_string(response[i], 'account_id') account = self.safe_value(self.accountsById, account_id) code = self.safe_string(account, 'currency') response[i]['currency'] = code else: response = self.privateGetAccountsIdTransfers(self.extend(request, params)) for i in range(0, len(response)): response[i]['currency'] = code return self.parse_transactions(response, currency, since, limit) def fetch_deposits(self, code=None, since=None, limit=None, params={}): return self.fetch_transactions(code, since, limit, self.extend(params, {'type': 'deposit'})) def fetch_withdrawals(self, code=None, since=None, limit=None, params={}): return self.fetch_transactions(code, since, limit, self.extend(params, {'type': 'withdraw'})) def parse_transaction_status(self, transaction): canceled = self.safe_value(transaction, 'canceled_at') if canceled: return 'canceled' processed = self.safe_value(transaction, 'processed_at') completed = self.safe_value(transaction, 'completed_at') if completed: return 'ok' elif processed and not completed: return 'failed' else: return 'pending' def parse_transaction(self, transaction, currency=None): details = self.safe_value(transaction, 'details', {}) id = self.safe_string(transaction, 'id') txid = self.safe_string(details, 'crypto_transaction_hash') timestamp = self.parse8601(self.safe_string(transaction, 'created_at')) updated = self.parse8601(self.safe_string(transaction, 'processed_at')) currencyId = self.safe_string(transaction, 'currency') code = self.safe_currency_code(currencyId, currency) status = self.parse_transaction_status(transaction) amount = self.safe_number(transaction, 'amount') type = self.safe_string(transaction, 'type') address = self.safe_string(details, 'crypto_address') tag = self.safe_string(details, 'destination_tag') address = self.safe_string(transaction, 'crypto_address', address) fee = None if type == 'withdraw': type = 'withdrawal' address = self.safe_string(details, 'sent_to_address', address) feeCost = self.safe_number(details, 'fee') if feeCost is not None: if amount is not None: amount -= feeCost fee = { 'cost': feeCost, 'currency': code, } return { 'info': transaction, 'id': id, 'txid': txid, 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'address': address, 'tag': tag, 'type': type, 'amount': amount, 'currency': code, 'status': status, 'updated': updated, 'fee': fee, } def create_deposit_address(self, code, params={}): self.load_markets() currency = self.currency(code) accounts = self.safe_value(self.options, 'coinbaseAccounts') if accounts is None: accounts = self.privateGetCoinbaseAccounts() self.options['coinbaseAccounts'] = accounts # cache it self.options['coinbaseAccountsByCurrencyId'] = self.index_by(accounts, 'currency') currencyId = currency['id'] account = self.safe_value(self.options['coinbaseAccountsByCurrencyId'], currencyId) if account is None: # eslint-disable-next-line quotes raise InvalidAddress(self.id + " fetchDepositAddress() could not find currency code " + code + " with id = " + currencyId + " in self.options['coinbaseAccountsByCurrencyId']") request = { 'id': account['id'], } response = self.privatePostCoinbaseAccountsIdAddresses(self.extend(request, params)) address = self.safe_string(response, 'address') tag = self.safe_string(response, 'destination_tag') return { 'currency': code, 'address': self.check_address(address), 'tag': tag, 'info': response, } def sign(self, path, api='public', method='GET', params={}, headers=None, body=None): request = '/' + self.implode_params(path, params) query = self.omit(params, self.extract_params(path)) if method == 'GET': if query: request += '?' + self.urlencode(query) url = self.implode_params(self.urls['api'][api], {'hostname': self.hostname}) + request if api == 'private': self.check_required_credentials() nonce = str(self.nonce()) payload = '' if method != 'GET': if query: body = self.json(query) payload = body what = nonce + method + request + payload secret = self.base64_to_binary(self.secret) signature = self.hmac(self.encode(what), secret, hashlib.sha256, 'base64') headers = { 'CB-ACCESS-KEY': self.apiKey, 'CB-ACCESS-SIGN': signature, 'CB-ACCESS-TIMESTAMP': nonce, 'CB-ACCESS-PASSPHRASE': self.password, 'Content-Type': 'application/json', } return {'url': url, 'method': method, 'body': body, 'headers': headers} def handle_errors(self, code, reason, url, method, headers, body, response, requestHeaders, requestBody): if (code == 400) or (code == 404): if body[0] == '{': message = self.safe_string(response, 'message') feedback = self.id + ' ' + message self.throw_exactly_matched_exception(self.exceptions['exact'], message, feedback) self.throw_broadly_matched_exception(self.exceptions['broad'], message, feedback) raise ExchangeError(feedback) # unknown message raise ExchangeError(self.id + ' ' + body) def request(self, path, api='public', method='GET', params={}, headers=None, body=None): response = self.fetch2(path, api, method, params, headers, body) if not isinstance(response, basestring): if 'message' in response: raise ExchangeError(self.id + ' ' + self.json(response)) return response
40.474756
187
0.494573
ge import Exchange try: basestring except NameError: basestring = str import hashlib from ccxt.base.errors import ExchangeError from ccxt.base.errors import AuthenticationError from ccxt.base.errors import PermissionDenied from ccxt.base.errors import ArgumentsRequired from ccxt.base.errors import InsufficientFunds from ccxt.base.errors import InvalidAddress from ccxt.base.errors import InvalidOrder from ccxt.base.errors import OrderNotFound from ccxt.base.errors import NotSupported from ccxt.base.errors import RateLimitExceeded from ccxt.base.errors import OnMaintenance from ccxt.base.decimal_to_precision import TICK_SIZE from ccxt.base.precise import Precise class coinbasepro(Exchange): def describe(self): return self.deep_extend(super(coinbasepro, self).describe(), { 'id': 'coinbasepro', 'name': 'Coinbase Pro', 'countries': ['US'], 'rateLimit': 1000, 'userAgent': self.userAgents['chrome'], 'pro': True, 'has': { 'cancelAllOrders': True, 'cancelOrder': True, 'CORS': True, 'createDepositAddress': True, 'createOrder': True, 'deposit': True, 'fetchAccounts': True, 'fetchBalance': True, 'fetchCurrencies': True, 'fetchClosedOrders': True, 'fetchDepositAddress': False, 'fetchMarkets': True, 'fetchMyTrades': True, 'fetchOHLCV': True, 'fetchOpenOrders': True, 'fetchOrder': True, 'fetchOrderBook': True, 'fetchOrders': True, 'fetchOrderTrades': True, 'fetchTime': True, 'fetchTicker': True, 'fetchTrades': True, 'fetchTransactions': True, 'withdraw': True, 'fetchDeposits': True, 'fetchWithdrawals': True, }, 'timeframes': { '1m': 60, '5m': 300, '15m': 900, '1h': 3600, '6h': 21600, '1d': 86400, }, 'hostname': 'pro.coinbase.com', 'urls': { 'test': { 'public': 'https://api-public.sandbox.pro.coinbase.com', 'private': 'https://api-public.sandbox.pro.coinbase.com', }, 'logo': 'https://user-images.githubusercontent.com/1294454/41764625-63b7ffde-760a-11e8-996d-a6328fa9347a.jpg', 'api': { 'public': 'https://api.{hostname}', 'private': 'https://api.{hostname}', }, 'www': 'https://pro.coinbase.com/', 'doc': 'https://docs.pro.coinbase.com', 'fees': [ 'https://docs.pro.coinbase.com/#fees', 'https://support.pro.coinbase.com/customer/en/portal/articles/2945310-fees', ], }, 'requiredCredentials': { 'apiKey': True, 'secret': True, 'password': True, }, 'api': { 'public': { 'get': [ 'currencies', 'products', 'products/{id}', 'products/{id}/book', 'products/{id}/candles', 'products/{id}/stats', 'products/{id}/ticker', 'products/{id}/trades', 'time', ], }, 'private': { 'get': [ 'accounts', 'accounts/{id}', 'accounts/{id}/holds', 'accounts/{id}/ledger', 'accounts/{id}/transfers', 'coinbase-accounts', 'fills', 'funding', 'fees', 'margin/profile_information', 'margin/buying_power', 'margin/withdrawal_power', 'margin/withdrawal_power_all', 'margin/exit_plan', 'margin/liquidation_history', 'margin/position_refresh_amounts', 'margin/status', 'oracle', 'orders', 'orders/{id}', 'orders/client:{client_oid}', 'otc/orders', 'payment-methods', 'position', 'profiles', 'profiles/{id}', 'reports/{report_id}', 'transfers', 'transfers/{transfer_id}', 'users/self/exchange-limits', 'users/self/hold-balances', 'users/self/trailing-volume', 'withdrawals/fee-estimate', ], 'post': [ 'conversions', 'deposits/coinbase-account', 'deposits/payment-method', 'coinbase-accounts/{id}/addresses', 'funding/repay', 'orders', 'position/close', 'profiles/margin-transfer', 'profiles/transfer', 'reports', 'withdrawals/coinbase', 'withdrawals/coinbase-account', 'withdrawals/crypto', 'withdrawals/payment-method', ], 'delete': [ 'orders', 'orders/client:{client_oid}', 'orders/{id}', ], }, }, 'commonCurrencies': { 'CGLD': 'CELO', }, 'precisionMode': TICK_SIZE, 'fees': { 'trading': { 'tierBased': True, 'percentage': True, 'maker': 0.5 / 100, 'taker': 0.5 / 100, }, 'funding': { 'tierBased': False, 'percentage': False, 'withdraw': { 'BCH': 0, 'BTC': 0, 'LTC': 0, 'ETH': 0, 'EUR': 0.15, 'USD': 25, }, 'deposit': { 'BCH': 0, 'BTC': 0, 'LTC': 0, 'ETH': 0, 'EUR': 0.15, 'USD': 10, }, }, }, 'exceptions': { 'exact': { 'Insufficient funds': InsufficientFunds, 'NotFound': OrderNotFound, 'Invalid API Key': AuthenticationError, 'invalid signature': AuthenticationError, 'Invalid Passphrase': AuthenticationError, 'Invalid order id': InvalidOrder, 'Private rate limit exceeded': RateLimitExceeded, 'Trading pair not available': PermissionDenied, 'Product not found': InvalidOrder, }, 'broad': { 'Order already done': OrderNotFound, 'order not found': OrderNotFound, 'price too small': InvalidOrder, 'price too precise': InvalidOrder, 'under maintenance': OnMaintenance, 'size is too small': InvalidOrder, 'Cancel only mode': OnMaintenance, }, }, }) def fetch_currencies(self, params={}): response = self.publicGetCurrencies(params) result = {} for i in range(0, len(response)): currency = response[i] id = self.safe_string(currency, 'id') name = self.safe_string(currency, 'name') code = self.safe_currency_code(id) details = self.safe_value(currency, 'details', {}) precision = self.safe_number(currency, 'max_precision') status = self.safe_string(currency, 'status') active = (status == 'online') result[code] = { 'id': id, 'code': code, 'info': currency, 'type': self.safe_string(details, 'type'), 'name': name, 'active': active, 'fee': None, 'precision': precision, 'limits': { 'amount': { 'min': self.safe_number(details, 'min_size'), 'max': None, }, 'withdraw': { 'min': self.safe_number(details, 'min_withdrawal_amount'), 'max': None, }, }, } return result def fetch_markets(self, params={}): response = self.publicGetProducts(params) result = [] for i in range(0, len(response)): market = response[i] id = self.safe_string(market, 'id') baseId = self.safe_string(market, 'base_currency') quoteId = self.safe_string(market, 'quote_currency') base = self.safe_currency_code(baseId) quote = self.safe_currency_code(quoteId) symbol = base + '/' + quote priceLimits = { 'min': self.safe_number(market, 'quote_increment'), 'max': None, } precision = { 'amount': self.safe_number(market, 'base_increment'), 'price': self.safe_number(market, 'quote_increment'), } status = self.safe_string(market, 'status') active = (status == 'online') result.append(self.extend(self.fees['trading'], { 'id': id, 'symbol': symbol, 'baseId': baseId, 'quoteId': quoteId, 'base': base, 'quote': quote, 'precision': precision, 'limits': { 'amount': { 'min': self.safe_number(market, 'base_min_size'), 'max': self.safe_number(market, 'base_max_size'), }, 'price': priceLimits, 'cost': { 'min': self.safe_number(market, 'min_market_funds'), 'max': self.safe_number(market, 'max_market_funds'), }, }, 'active': active, 'info': market, })) return result def fetch_accounts(self, params={}): self.load_markets() response = self.privateGetAccounts(params) result = [] for i in range(0, len(response)): account = response[i] accountId = self.safe_string(account, 'id') currencyId = self.safe_string(account, 'currency') code = self.safe_currency_code(currencyId) result.append({ 'id': accountId, 'type': None, 'currency': code, 'info': account, }) return result def fetch_balance(self, params={}): self.load_markets() response = self.privateGetAccounts(params) result = {'info': response} for i in range(0, len(response)): balance = response[i] currencyId = self.safe_string(balance, 'currency') code = self.safe_currency_code(currencyId) account = self.account() account['free'] = self.safe_string(balance, 'available') account['used'] = self.safe_string(balance, 'hold') account['total'] = self.safe_string(balance, 'balance') result[code] = account return self.parse_balance(result, False) def fetch_order_book(self, symbol, limit=None, params={}): self.load_markets() request = { 'id': self.market_id(symbol), 'level': 2, } response = self.publicGetProductsIdBook(self.extend(request, params)) orderbook = self.parse_order_book(response, symbol) orderbook['nonce'] = self.safe_integer(response, 'sequence') return orderbook def parse_ticker(self, ticker, market=None): timestamp = self.parse8601(self.safe_value(ticker, 'time')) bid = self.safe_number(ticker, 'bid') ask = self.safe_number(ticker, 'ask') last = self.safe_number(ticker, 'price') symbol = None if (market is None) else market['symbol'] return { 'symbol': symbol, 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'high': self.safe_number(ticker, 'high'), 'low': self.safe_number(ticker, 'low'), 'bid': bid, 'bidVolume': None, 'ask': ask, 'askVolume': None, 'vwap': None, 'open': self.safe_number(ticker, 'open'), 'close': last, 'last': last, 'previousClose': None, 'change': None, 'percentage': None, 'average': None, 'baseVolume': self.safe_number(ticker, 'volume'), 'quoteVolume': None, 'info': ticker, } def fetch_ticker(self, symbol, params={}): self.load_markets() market = self.market(symbol) request = { 'id': market['id'], } method = self.safe_string(self.options, 'fetchTickerMethod', 'publicGetProductsIdTicker') response = getattr(self, method)(self.extend(request, params)) return self.parse_ticker(response, market) def parse_trade(self, trade, market=None): timestamp = self.parse8601(self.safe_string_2(trade, 'time', 'created_at')) marketId = self.safe_string(trade, 'product_id') symbol = self.safe_symbol(marketId, market, '-') feeRate = None feeCurrency = None takerOrMaker = None cost = None if market is not None: feeCurrencyId = self.safe_string_lower(market, 'quoteId') costField = feeCurrencyId + '_value' cost = self.safe_number(trade, costField) feeCurrency = market['quote'] liquidity = self.safe_string(trade, 'liquidity') if liquidity is not None: takerOrMaker = 'taker' if (liquidity == 'T') else 'maker' feeRate = market[takerOrMaker] feeCost = self.safe_number_2(trade, 'fill_fees', 'fee') fee = { 'cost': feeCost, 'currency': feeCurrency, 'rate': feeRate, } type = None id = self.safe_string(trade, 'trade_id') side = 'sell' if (trade['side'] == 'buy') else 'buy' orderId = self.safe_string(trade, 'order_id') makerOrderId = self.safe_string(trade, 'maker_order_id') takerOrderId = self.safe_string(trade, 'taker_order_id') if (orderId is not None) or ((makerOrderId is not None) and (takerOrderId is not None)): side = 'buy' if (trade['side'] == 'buy') else 'sell' priceString = self.safe_string(trade, 'price') amountString = self.safe_string(trade, 'size') price = self.parse_number(priceString) amount = self.parse_number(amountString) if cost is None: cost = self.parse_number(Precise.string_mul(priceString, amountString)) return { 'id': id, 'order': orderId, 'info': trade, 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'symbol': symbol, 'type': type, 'takerOrMaker': takerOrMaker, 'side': side, 'price': price, 'amount': amount, 'fee': fee, 'cost': cost, } def fetch_my_trades(self, symbol=None, since=None, limit=None, params={}): if symbol is None: raise ArgumentsRequired(self.id + ' fetchMyTrades() requires a symbol argument') self.load_markets() market = self.market(symbol) request = { 'product_id': market['id'], } if limit is not None: request['limit'] = limit response = self.privateGetFills(self.extend(request, params)) return self.parse_trades(response, market, since, limit) def fetch_trades(self, symbol, since=None, limit=None, params={}): self.load_markets() market = self.market(symbol) request = { 'id': market['id'], } if limit is not None: request['limit'] = limit response = self.publicGetProductsIdTrades(self.extend(request, params)) return self.parse_trades(response, market, since, limit) def parse_ohlcv(self, ohlcv, market=None): return [ self.safe_timestamp(ohlcv, 0), self.safe_number(ohlcv, 3), self.safe_number(ohlcv, 2), self.safe_number(ohlcv, 1), self.safe_number(ohlcv, 4), self.safe_number(ohlcv, 5), ] def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}): self.load_markets() market = self.market(symbol) granularity = self.timeframes[timeframe] request = { 'id': market['id'], 'granularity': granularity, } if since is not None: request['start'] = self.iso8601(since) if limit is None: mit = 300 else: limit = min(300, limit) request['end'] = self.iso8601(self.sum((limit - 1) * granularity * 1000, since)) response = self.publicGetProductsIdCandles(self.extend(request, params)) return self.parse_ohlcvs(response, market, timeframe, since, limit) def fetch_time(self, params={}): response = self.publicGetTime(params) return self.safe_timestamp(response, 'epoch') def parse_order_status(self, status): statuses = { 'pending': 'open', 'active': 'open', 'open': 'open', 'done': 'closed', 'canceled': 'canceled', 'canceling': 'open', } return self.safe_string(statuses, status, status) def parse_order(self, order, market=None): timestamp = self.parse8601(self.safe_string(order, 'created_at')) marketId = self.safe_string(order, 'product_id') market = self.safe_market(marketId, market, '-') status = self.parse_order_status(self.safe_string(order, 'status')) price = self.safe_number(order, 'price') filled = self.safe_number(order, 'filled_size') amount = self.safe_number(order, 'size', filled) cost = self.safe_number(order, 'executed_value') feeCost = self.safe_number(order, 'fill_fees') fee = None if feeCost is not None: feeCurrencyCode = None if market is not None: feeCurrencyCode = market['quote'] fee = { 'cost': feeCost, 'currency': feeCurrencyCode, 'rate': None, } id = self.safe_string(order, 'id') type = self.safe_string(order, 'type') side = self.safe_string(order, 'side') timeInForce = self.safe_string(order, 'time_in_force') postOnly = self.safe_value(order, 'post_only') stopPrice = self.safe_number(order, 'stop_price') clientOrderId = self.safe_string(order, 'client_oid') return self.safe_order({ 'id': id, 'clientOrderId': clientOrderId, 'info': order, 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'lastTradeTimestamp': None, 'status': status, 'symbol': market['symbol'], 'type': type, 'timeInForce': timeInForce, 'postOnly': postOnly, 'side': side, 'price': price, 'stopPrice': stopPrice, 'cost': cost, 'amount': amount, 'filled': filled, 'remaining': None, 'fee': fee, 'average': None, 'trades': None, }) def fetch_order(self, id, symbol=None, params={}): self.load_markets() request = {} clientOrderId = self.safe_string_2(params, 'clientOrderId', 'client_oid') method = None if clientOrderId is None: method = 'privateGetOrdersId' request['id'] = id else: method = 'privateGetOrdersClientClientOid' request['client_oid'] = clientOrderId params = self.omit(params, ['clientOrderId', 'client_oid']) response = getattr(self, method)(self.extend(request, params)) return self.parse_order(response) def fetch_order_trades(self, id, symbol=None, since=None, limit=None, params={}): self.load_markets() market = None if symbol is not None: market = self.market(symbol) request = { 'order_id': id, } response = self.privateGetFills(self.extend(request, params)) return self.parse_trades(response, market, since, limit) def fetch_orders(self, symbol=None, since=None, limit=None, params={}): request = { 'status': 'all', } return self.fetch_open_orders(symbol, since, limit, self.extend(request, params)) def fetch_open_orders(self, symbol=None, since=None, limit=None, params={}): self.load_markets() request = {} market = None if symbol is not None: market = self.market(symbol) request['product_id'] = market['id'] if limit is not None: request['limit'] = limit response = self.privateGetOrders(self.extend(request, params)) return self.parse_orders(response, market, since, limit) def fetch_closed_orders(self, symbol=None, since=None, limit=None, params={}): request = { 'status': 'done', } return self.fetch_open_orders(symbol, since, limit, self.extend(request, params)) def create_order(self, symbol, type, side, amount, price=None, params={}): self.load_markets() market = self.market(symbol) request = { 'type': type, 'side': side, 'product_id': market['id'], if clientOrderId is not None: request['client_oid'] = clientOrderId params = self.omit(params, ['clientOrderId', 'client_oid']) stopPrice = self.safe_number_2(params, 'stopPrice', 'stop_price') if stopPrice is not None: request['stop_price'] = self.price_to_precision(symbol, stopPrice) params = self.omit(params, ['stopPrice', 'stop_price']) timeInForce = self.safe_string_2(params, 'timeInForce', 'time_in_force') if timeInForce is not None: request['time_in_force'] = timeInForce params = self.omit(params, ['timeInForce', 'time_in_force']) if type == 'limit': request['price'] = self.price_to_precision(symbol, price) request['size'] = self.amount_to_precision(symbol, amount) elif type == 'market': cost = self.safe_number_2(params, 'cost', 'funds') if cost is None: if price is not None: cost = amount * price else: params = self.omit(params, ['cost', 'funds']) if cost is not None: request['funds'] = self.cost_to_precision(symbol, cost) else: request['size'] = self.amount_to_precision(symbol, amount) response = self.privatePostOrders(self.extend(request, params)) return self.parse_order(response, market) def cancel_order(self, id, symbol=None, params={}): self.load_markets() request = { arams, 'clientOrderId', 'client_oid') method = None if clientOrderId is None: method = 'privateDeleteOrdersId' request['id'] = id else: method = 'privateDeleteOrdersClientClientOid' request['client_oid'] = clientOrderId params = self.omit(params, ['clientOrderId', 'client_oid']) market = None if symbol is not None: market = self.market(symbol) request['product_id'] = market['symbol'] return getattr(self, method)(self.extend(request, params)) def cancel_all_orders(self, symbol=None, params={}): self.load_markets() request = {} market = None if symbol is not None: market = self.market(symbol) request['product_id'] = market['symbol'] return self.privateDeleteOrders(self.extend(request, params)) def fetch_payment_methods(self, params={}): return self.privateGetPaymentMethods(params) def deposit(self, code, amount, address, params={}): self.load_markets() currency = self.currency(code) request = { 'currency': currency['id'], 'amount': amount, } method = 'privatePostDeposits' if 'payment_method_id' in params: method += 'PaymentMethod' elif 'coinbase_account_id' in params: method += 'CoinbaseAccount' else: raise NotSupported(self.id + ' deposit() requires one of `coinbase_account_id` or `payment_method_id` extra params') response = getattr(self, method)(self.extend(request, params)) if not response: raise ExchangeError(self.id + ' deposit() error: ' + self.json(response)) return { 'info': response, 'id': response['id'], } def withdraw(self, code, amount, address, tag=None, params={}): self.check_address(address) self.load_markets() currency = self.currency(code) request = { 'currency': currency['id'], 'amount': amount, } method = 'privatePostWithdrawals' if 'payment_method_id' in params: method += 'PaymentMethod' elif 'coinbase_account_id' in params: method += 'CoinbaseAccount' else: method += 'Crypto' request['crypto_address'] = address if tag is not None: request['destination_tag'] = tag response = getattr(self, method)(self.extend(request, params)) if not response: raise ExchangeError(self.id + ' withdraw() error: ' + self.json(response)) return { 'info': response, 'id': response['id'], } def fetch_transactions(self, code=None, since=None, limit=None, params={}): self.load_markets() self.load_accounts() currency = None id = self.safe_string(params, 'id') if id is None: if code is not None: currency = self.currency(code) accountsByCurrencyCode = self.index_by(self.accounts, 'currency') account = self.safe_value(accountsByCurrencyCode, code) if account is None: raise ExchangeError(self.id + ' fetchTransactions() could not find account id for ' + code) id = account['id'] request = {} if id is not None: request['id'] = id if limit is not None: request['limit'] = limit response = None if id is None: response = self.privateGetTransfers(self.extend(request, params)) for i in range(0, len(response)): account_id = self.safe_string(response[i], 'account_id') account = self.safe_value(self.accountsById, account_id) code = self.safe_string(account, 'currency') response[i]['currency'] = code else: response = self.privateGetAccountsIdTransfers(self.extend(request, params)) for i in range(0, len(response)): response[i]['currency'] = code return self.parse_transactions(response, currency, since, limit) def fetch_deposits(self, code=None, since=None, limit=None, params={}): return self.fetch_transactions(code, since, limit, self.extend(params, {'type': 'deposit'})) def fetch_withdrawals(self, code=None, since=None, limit=None, params={}): return self.fetch_transactions(code, since, limit, self.extend(params, {'type': 'withdraw'})) def parse_transaction_status(self, transaction): canceled = self.safe_value(transaction, 'canceled_at') if canceled: return 'canceled' processed = self.safe_value(transaction, 'processed_at') completed = self.safe_value(transaction, 'completed_at') if completed: return 'ok' elif processed and not completed: return 'failed' else: return 'pending' def parse_transaction(self, transaction, currency=None): details = self.safe_value(transaction, 'details', {}) id = self.safe_string(transaction, 'id') txid = self.safe_string(details, 'crypto_transaction_hash') timestamp = self.parse8601(self.safe_string(transaction, 'created_at')) updated = self.parse8601(self.safe_string(transaction, 'processed_at')) currencyId = self.safe_string(transaction, 'currency') code = self.safe_currency_code(currencyId, currency) status = self.parse_transaction_status(transaction) amount = self.safe_number(transaction, 'amount') type = self.safe_string(transaction, 'type') address = self.safe_string(details, 'crypto_address') tag = self.safe_string(details, 'destination_tag') address = self.safe_string(transaction, 'crypto_address', address) fee = None if type == 'withdraw': type = 'withdrawal' address = self.safe_string(details, 'sent_to_address', address) feeCost = self.safe_number(details, 'fee') if feeCost is not None: if amount is not None: amount -= feeCost fee = { 'cost': feeCost, 'currency': code, } return { 'info': transaction, 'id': id, 'txid': txid, 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'address': address, 'tag': tag, 'type': type, 'amount': amount, 'currency': code, 'status': status, 'updated': updated, 'fee': fee, } def create_deposit_address(self, code, params={}): self.load_markets() currency = self.currency(code) accounts = self.safe_value(self.options, 'coinbaseAccounts') if accounts is None: accounts = self.privateGetCoinbaseAccounts() self.options['coinbaseAccounts'] = accounts self.options['coinbaseAccountsByCurrencyId'] = self.index_by(accounts, 'currency') currencyId = currency['id'] account = self.safe_value(self.options['coinbaseAccountsByCurrencyId'], currencyId) if account is None: raise InvalidAddress(self.id + " fetchDepositAddress() could not find currency code " + code + " with id = " + currencyId + " in self.options['coinbaseAccountsByCurrencyId']") request = { 'id': account['id'], } response = self.privatePostCoinbaseAccountsIdAddresses(self.extend(request, params)) address = self.safe_string(response, 'address') tag = self.safe_string(response, 'destination_tag') return { 'currency': code, 'address': self.check_address(address), 'tag': tag, 'info': response, } def sign(self, path, api='public', method='GET', params={}, headers=None, body=None): request = '/' + self.implode_params(path, params) query = self.omit(params, self.extract_params(path)) if method == 'GET': if query: request += '?' + self.urlencode(query) url = self.implode_params(self.urls['api'][api], {'hostname': self.hostname}) + request if api == 'private': self.check_required_credentials() nonce = str(self.nonce()) payload = '' if method != 'GET': if query: body = self.json(query) payload = body what = nonce + method + request + payload secret = self.base64_to_binary(self.secret) signature = self.hmac(self.encode(what), secret, hashlib.sha256, 'base64') headers = { 'CB-ACCESS-KEY': self.apiKey, 'CB-ACCESS-SIGN': signature, 'CB-ACCESS-TIMESTAMP': nonce, 'CB-ACCESS-PASSPHRASE': self.password, 'Content-Type': 'application/json', } return {'url': url, 'method': method, 'body': body, 'headers': headers} def handle_errors(self, code, reason, url, method, headers, body, response, requestHeaders, requestBody): if (code == 400) or (code == 404): if body[0] == '{': message = self.safe_string(response, 'message') feedback = self.id + ' ' + message self.throw_exactly_matched_exception(self.exceptions['exact'], message, feedback) self.throw_broadly_matched_exception(self.exceptions['broad'], message, feedback) raise ExchangeError(feedback) raise ExchangeError(self.id + ' ' + body) def request(self, path, api='public', method='GET', params={}, headers=None, body=None): response = self.fetch2(path, api, method, params, headers, body) if not isinstance(response, basestring): if 'message' in response: raise ExchangeError(self.id + ' ' + self.json(response)) return response
true
true
f725cc9a4bba65ddba8bae99ff1a3dc410b16b3a
558
py
Python
test/functional/test_framework/validaterawtransaction.py
hackverket/bitcoin-abc-bitcore
cc70c0a66b640a1ac59024bac9a314256ed386b2
[ "MIT" ]
5
2019-07-29T04:12:38.000Z
2020-07-26T12:02:30.000Z
test/functional/test_framework/validaterawtransaction.py
hackverket/bitcoin-abc-bitcore
cc70c0a66b640a1ac59024bac9a314256ed386b2
[ "MIT" ]
5
2019-03-04T13:26:23.000Z
2019-11-15T16:44:19.000Z
test/functional/test_framework/validaterawtransaction.py
hackverket/bitcoin-abc-bitcore
cc70c0a66b640a1ac59024bac9a314256ed386b2
[ "MIT" ]
4
2019-03-22T04:18:50.000Z
2019-10-30T20:37:36.000Z
from test_framework.messages import ToHex from test_framework.util import assert_equal def check_validaterawtx(node, tx, has_valid_inputs = True, is_minable = True, enough_fee = True, num_errors = 0): res = node.validaterawtransaction(ToHex(tx)) if enough_fee: assert(res["txfee"] >= res["txfeeneeded"]) else: assert(res["txfee"] <= res["txfeeneeded"]) assert_equal(res["minable"], is_minable) assert_equal(res["inputscheck"]["valid"], has_valid_inputs) assert_equal(num_errors, len(res["errors"]))
29.368421
63
0.689964
from test_framework.messages import ToHex from test_framework.util import assert_equal def check_validaterawtx(node, tx, has_valid_inputs = True, is_minable = True, enough_fee = True, num_errors = 0): res = node.validaterawtransaction(ToHex(tx)) if enough_fee: assert(res["txfee"] >= res["txfeeneeded"]) else: assert(res["txfee"] <= res["txfeeneeded"]) assert_equal(res["minable"], is_minable) assert_equal(res["inputscheck"]["valid"], has_valid_inputs) assert_equal(num_errors, len(res["errors"]))
true
true
f725ccb31e4440e6e4c660392d8237cb3fafb886
341
py
Python
src/box.py
Flantropy/my_pygame_template
ab30f3ac5c11866c0bb7c32dff177d6fb47a6753
[ "MIT" ]
null
null
null
src/box.py
Flantropy/my_pygame_template
ab30f3ac5c11866c0bb7c32dff177d6fb47a6753
[ "MIT" ]
null
null
null
src/box.py
Flantropy/my_pygame_template
ab30f3ac5c11866c0bb7c32dff177d6fb47a6753
[ "MIT" ]
null
null
null
from pygame import Surface from pygame.sprite import Sprite class Box(Sprite): def __init__(self, color, x=0, y=0): super().__init__() self.image = Surface((50, 50)) self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y self.color = color self.image.fill(self.color)
24.357143
41
0.595308
from pygame import Surface from pygame.sprite import Sprite class Box(Sprite): def __init__(self, color, x=0, y=0): super().__init__() self.image = Surface((50, 50)) self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y self.color = color self.image.fill(self.color)
true
true
f725cd04c52b8ddabf80aed6a0fab88870068c97
507
py
Python
lamdba_caller.py
Diontsoumas/book-discount-tracker
19f54a65b388e3d01516b16c6bdbd407bed24327
[ "MIT" ]
1
2019-04-04T20:48:59.000Z
2019-04-04T20:48:59.000Z
lamdba_caller.py
Diontsoumas/book-discount-tracker
19f54a65b388e3d01516b16c6bdbd407bed24327
[ "MIT" ]
null
null
null
lamdba_caller.py
Diontsoumas/book-discount-tracker
19f54a65b388e3d01516b16c6bdbd407bed24327
[ "MIT" ]
null
null
null
import boto3 import json s3 = boto3.resource('s3') def lambda_handler(event, context): bucket = s3.Bucket("diotsoumas-book-tracker-config-files") sns_client = boto3.client('sns') arn = "arn:aws:sns:eu-west-1:169367514751:Lamdba-caller" for obj in bucket.objects.filter(): message = {"s3_key": obj.key} response = sns_client.publish( TargetArn=arn, Message=json.dumps({'default': json.dumps(message)}), MessageStructure='json' )
28.166667
65
0.635108
import boto3 import json s3 = boto3.resource('s3') def lambda_handler(event, context): bucket = s3.Bucket("diotsoumas-book-tracker-config-files") sns_client = boto3.client('sns') arn = "arn:aws:sns:eu-west-1:169367514751:Lamdba-caller" for obj in bucket.objects.filter(): message = {"s3_key": obj.key} response = sns_client.publish( TargetArn=arn, Message=json.dumps({'default': json.dumps(message)}), MessageStructure='json' )
true
true
f725ce2222bf3ae065c946c1c55958e57ddb15fb
405
py
Python
sra_django_api/sra_django_api/wsgi.py
tflati/ncbi-search
2f31c57ffb95c2c874b65c03c58edd96eb822dfb
[ "MIT" ]
null
null
null
sra_django_api/sra_django_api/wsgi.py
tflati/ncbi-search
2f31c57ffb95c2c874b65c03c58edd96eb822dfb
[ "MIT" ]
null
null
null
sra_django_api/sra_django_api/wsgi.py
tflati/ncbi-search
2f31c57ffb95c2c874b65c03c58edd96eb822dfb
[ "MIT" ]
null
null
null
""" WSGI config for sra_django_api project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sra_django_api.settings") application = get_wsgi_application()
23.823529
78
0.792593
import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sra_django_api.settings") application = get_wsgi_application()
true
true
f725cea5e00aa2c09ec45c55521fcde13e1cb507
427
py
Python
healthcareai/__init__.py
vijayphugat/Practice
7d8560d62a5d6bfa9488526da318973295a25255
[ "MIT" ]
null
null
null
healthcareai/__init__.py
vijayphugat/Practice
7d8560d62a5d6bfa9488526da318973295a25255
[ "MIT" ]
null
null
null
healthcareai/__init__.py
vijayphugat/Practice
7d8560d62a5d6bfa9488526da318973295a25255
[ "MIT" ]
null
null
null
from .advanced_supvervised_model_trainer import AdvancedSupervisedModelTrainer from .supervised_model_trainer import SupervisedModelTrainer from .datasets import load_diabetes from .common.csv_loader import load_csv from .common.file_io_utilities import load_saved_model __all__ = [ 'AdvancedSupervisedModelTrainer', 'SupervisedModelTrainer', 'load_csv', 'load_diabetes', 'load_saved_model' ]
30.5
79
0.796253
from .advanced_supvervised_model_trainer import AdvancedSupervisedModelTrainer from .supervised_model_trainer import SupervisedModelTrainer from .datasets import load_diabetes from .common.csv_loader import load_csv from .common.file_io_utilities import load_saved_model __all__ = [ 'AdvancedSupervisedModelTrainer', 'SupervisedModelTrainer', 'load_csv', 'load_diabetes', 'load_saved_model' ]
true
true
f725d0c8c26e20e7b4d0e58db66301a09c122ff9
1,670
py
Python
models/model_facebook.py
xyla-io/almacen
7b7f235dc7939777f971f1b5eadd5621e980c15e
[ "MIT" ]
2
2020-10-15T22:12:17.000Z
2020-10-26T07:17:17.000Z
models/model_facebook.py
xyla-io/almacen
7b7f235dc7939777f971f1b5eadd5621e980c15e
[ "MIT" ]
null
null
null
models/model_facebook.py
xyla-io/almacen
7b7f235dc7939777f971f1b5eadd5621e980c15e
[ "MIT" ]
null
null
null
import sqlalchemy as alchemy from . import base from typing import Optional class FacebookReportTableModel(base.ReportTableModel): @property def date_column_name(self) -> str: return 'date_start' class FacebookCampaignReportTableModel(FacebookReportTableModel): @property def table_name(self) -> str: return base.ReportTaskType.fetch_facebook_campaigns.value def define_table(self): alchemy.Table( self.table_name, self.declarative_base.metadata, alchemy.Column(self.date_column_name, alchemy.Date), alchemy.Column(self.crystallized_column_name, alchemy.Boolean), alchemy.Column('account_id', alchemy.Text), schema=self.schema_name ) class FacebookAdSetReportTableModel(FacebookReportTableModel): @property def table_name(self) -> str: return base.ReportTaskType.fetch_facebook_adsets.value def define_table(self): alchemy.Table( self.table_name, self.declarative_base.metadata, alchemy.Column(self.date_column_name, alchemy.Date), alchemy.Column(self.crystallized_column_name, alchemy.Boolean), alchemy.Column('account_id', alchemy.Text), schema=self.schema_name ) class FacebookAdReportTableModel(FacebookReportTableModel): @property def table_name(self) -> str: return base.ReportTaskType.fetch_facebook_ads.value def define_table(self): alchemy.Table( self.table_name, self.declarative_base.metadata, alchemy.Column(self.date_column_name, alchemy.Date), alchemy.Column(self.crystallized_column_name, alchemy.Boolean), alchemy.Column('account_id', alchemy.Text), schema=self.schema_name )
30.363636
69
0.749102
import sqlalchemy as alchemy from . import base from typing import Optional class FacebookReportTableModel(base.ReportTableModel): @property def date_column_name(self) -> str: return 'date_start' class FacebookCampaignReportTableModel(FacebookReportTableModel): @property def table_name(self) -> str: return base.ReportTaskType.fetch_facebook_campaigns.value def define_table(self): alchemy.Table( self.table_name, self.declarative_base.metadata, alchemy.Column(self.date_column_name, alchemy.Date), alchemy.Column(self.crystallized_column_name, alchemy.Boolean), alchemy.Column('account_id', alchemy.Text), schema=self.schema_name ) class FacebookAdSetReportTableModel(FacebookReportTableModel): @property def table_name(self) -> str: return base.ReportTaskType.fetch_facebook_adsets.value def define_table(self): alchemy.Table( self.table_name, self.declarative_base.metadata, alchemy.Column(self.date_column_name, alchemy.Date), alchemy.Column(self.crystallized_column_name, alchemy.Boolean), alchemy.Column('account_id', alchemy.Text), schema=self.schema_name ) class FacebookAdReportTableModel(FacebookReportTableModel): @property def table_name(self) -> str: return base.ReportTaskType.fetch_facebook_ads.value def define_table(self): alchemy.Table( self.table_name, self.declarative_base.metadata, alchemy.Column(self.date_column_name, alchemy.Date), alchemy.Column(self.crystallized_column_name, alchemy.Boolean), alchemy.Column('account_id', alchemy.Text), schema=self.schema_name )
true
true
f725d10ada02b65b1f2ceb1eb17fac036e84be42
766
py
Python
auto_auto_archive.py
fairhopeweb/auto-archiver
67e41b80ceec38b81bd43345a2024a726e1983f0
[ "MIT" ]
45
2021-02-27T21:52:58.000Z
2022-03-30T20:13:03.000Z
auto_auto_archive.py
fairhopeweb/auto-archiver
67e41b80ceec38b81bd43345a2024a726e1983f0
[ "MIT" ]
18
2021-02-10T15:04:30.000Z
2022-03-30T09:15:05.000Z
auto_auto_archive.py
fairhopeweb/auto-archiver
67e41b80ceec38b81bd43345a2024a726e1983f0
[ "MIT" ]
15
2021-06-12T16:37:46.000Z
2022-03-29T11:36:03.000Z
import gspread import subprocess import argparse import auto_archive import datetime def main(): parser = argparse.ArgumentParser( description="Automatically use youtube-dl to download media from a Google Sheet") parser.add_argument("--sheet", action="store", dest="sheet") args = parser.parse_args() print(datetime.datetime.now()) print("Opening document " + args.sheet) gc = gspread.service_account(filename='service_account.json') sh = gc.open(args.sheet) wks = sh.get_worksheet(0) values = wks.get_all_values() for i in range(11, len(values)): sheet_name = values[i][0] print("Processing " + sheet_name) auto_archive.process_sheet(sheet_name) if __name__ == "__main__": main()
23.9375
89
0.685379
import gspread import subprocess import argparse import auto_archive import datetime def main(): parser = argparse.ArgumentParser( description="Automatically use youtube-dl to download media from a Google Sheet") parser.add_argument("--sheet", action="store", dest="sheet") args = parser.parse_args() print(datetime.datetime.now()) print("Opening document " + args.sheet) gc = gspread.service_account(filename='service_account.json') sh = gc.open(args.sheet) wks = sh.get_worksheet(0) values = wks.get_all_values() for i in range(11, len(values)): sheet_name = values[i][0] print("Processing " + sheet_name) auto_archive.process_sheet(sheet_name) if __name__ == "__main__": main()
true
true
f725d191d7ee26a6a4fe4a6ea65ea74b004d9957
531
py
Python
contest/pythonist3/validating-credit-card-number/validating-credit-card-number.py
zeyuanxy/HackerRank
5194a4af780ece396501c215996685d1be529e73
[ "MIT" ]
4
2017-01-18T17:51:58.000Z
2019-10-20T12:14:37.000Z
contest/pythonist3/validating-credit-card-number/validating-credit-card-number.py
zeyuanxy/HackerRank
5194a4af780ece396501c215996685d1be529e73
[ "MIT" ]
null
null
null
contest/pythonist3/validating-credit-card-number/validating-credit-card-number.py
zeyuanxy/HackerRank
5194a4af780ece396501c215996685d1be529e73
[ "MIT" ]
8
2016-03-14T17:16:59.000Z
2021-06-26T10:11:33.000Z
# -*- coding: utf-8 -*- # @Author: Zeyuan Shang # @Date: 2016-05-13 12:50:43 # @Last Modified by: Zeyuan Shang # @Last Modified time: 2016-05-13 12:50:54 import re for i in range(int(raw_input())): S = raw_input().strip() pre_match = re.search(r'^[456]\d{3}(-?)\d{4}\1\d{4}\1\d{4}$',S) if pre_match: processed_string = "".join(pre_match.group(0).split('-')) final_match = re.search(r'(\d)\1{3,}',processed_string) print 'Invalid' if final_match else 'Valid' else: print 'Invalid'
35.4
67
0.59887
import re for i in range(int(raw_input())): S = raw_input().strip() pre_match = re.search(r'^[456]\d{3}(-?)\d{4}\1\d{4}\1\d{4}$',S) if pre_match: processed_string = "".join(pre_match.group(0).split('-')) final_match = re.search(r'(\d)\1{3,}',processed_string) print 'Invalid' if final_match else 'Valid' else: print 'Invalid'
false
true
f725d1cbbda0c0bbbabb83ea57b921c1c1a3b239
64,981
py
Python
scripts/category.py
framawiki/pywikibot
9835260ef5f38ac83d3ce214c7d1abd594bea934
[ "MIT" ]
null
null
null
scripts/category.py
framawiki/pywikibot
9835260ef5f38ac83d3ce214c7d1abd594bea934
[ "MIT" ]
null
null
null
scripts/category.py
framawiki/pywikibot
9835260ef5f38ac83d3ce214c7d1abd594bea934
[ "MIT" ]
null
null
null
#!/usr/bin/python # -*- coding: utf-8 -*- """ Script to manage categories. Syntax: python pwb.py category action [-option] where action can be one of these * add - mass-add a category to a list of pages. * remove - remove category tag from all pages in a category. * move - move all pages in a category to another category. * tidy - tidy up a category by moving its pages into subcategories. * tree - show a tree of subcategories of a given category. * listify - make a list of all of the articles that are in a category. and option can be one of these Options for "add" action: -person - Sort persons by their last name. -create - If a page doesn't exist, do not skip it, create it instead. -redirect - Follow redirects. If action is "add", the following options are supported: &params; Options for "listify" action: -append - This appends the list to the current page that is already existing (appending to the bottom by default). -overwrite - This overwrites the current page with the list even if something is already there. -showimages - This displays images rather than linking them in the list. -talkpages - This outputs the links to talk pages of the pages to be listified in addition to the pages themselves. -prefix:# - You may specify a list prefix like "#" for a numbered list or any other prefix. Default is a bullet list with prefix "*". Options for "remove" action: -nodelsum - This specifies not to use the custom edit summary as the deletion reason. Instead, it uses the default deletion reason for the language, which is "Category was disbanded" in English. Options for "move" action: -hist - Creates a nice wikitable on the talk page of target category that contains detailed page history of the source category. -nodelete - Don't delete the old category after move. -nowb - Don't update the wikibase repository. -allowsplit - If that option is not set, it only moves the talk and main page together. -mvtogether - Only move the pages/subcategories of a category, if the target page (and talk page, if -allowsplit is not set) doesn't exist. -keepsortkey - Use sortKey of the old category also for the new category. If not specified, sortKey is removed. An alternative method to keep sortKey is to use -inplace option. Options for "tidy" action: -namespaces Filter the arcitles in the specified namespaces. Separate -namespace multiple namespace numbers or names with commas. Examples: -ns -ns:0,2,4 -ns:Help,MediaWiki Options for several actions: -rebuild - Reset the database. -from: - The category to move from (for the move option) Also, the category to remove from in the remove option Also, the category to make a list of in the listify option. -to: - The category to move to (for the move option). - Also, the name of the list to make in the listify option. NOTE: If the category names have spaces in them you may need to use a special syntax in your shell so that the names aren't treated as separate parameters. For instance, in BASH, use single quotes, e.g. -from:'Polar bears'. -batch - Don't prompt to delete emptied categories (do it automatically). -summary: - Pick a custom edit summary for the bot. -inplace - Use this flag to change categories in place rather than rearranging them. -recurse - Recurse through all subcategories of categories. -pagesonly - While removing pages from a category, keep the subpage links and do not remove them. -match - Only work on pages whose titles match the given regex (for move and remove actions). -depth: - The max depth limit beyond which no subcategories will be listed. For the actions tidy and tree, the bot will store the category structure locally in category.dump. This saves time and server load, but if it uses these data later, they may be outdated; use the -rebuild parameter in this case. For example, to create a new category from a list of persons, type: python pwb.py category add -person and follow the on-screen instructions. Or to do it all from the command-line, use the following syntax: python pwb.py category move -from:US -to:"United States" This will move all pages in the category US to the category United States. """ # # (C) Pywikibot team, 2004-2020 # # Distributed under the terms of the MIT license. # import codecs import math import os import pickle import re from operator import methodcaller from typing import Optional, Set import pywikibot from pywikibot import config, pagegenerators from pywikibot import i18n, textlib from pywikibot.bot import ( suggest_help, IntegerOption, StandardOption, ContextOption, BaseBot, Bot, MultipleSitesBot, ) from pywikibot.cosmetic_changes import moved_links from pywikibot.tools import ( deprecated_args, deprecated, ModuleDeprecationWrapper, open_archive, ) from pywikibot.tools.formatter import color_format # This is required for the text that is shown when you run this script # with the parameter -help. docuReplacements = {'&params;': pagegenerators.parameterHelp} # noqa: N816 cfd_templates = { 'wikipedia': { 'cs': ['přesunout', 'přejmenovat', 'přejmenovat kategorii', 'přesunout kategorii', 'přejmenování kategorie'], 'en': ['cfd', 'cfr', 'cfru', 'cfr-speedy', 'cfm', 'cfdu'], 'fi': ['roskaa', 'poistettava', 'korjattava/nimi', 'yhdistettäväLuokka'], 'fr': ['renommage de catégorie demandé'], 'he': ['הצבעת מחיקה', 'למחוק'], 'nl': ['categorieweg', 'catweg', 'wegcat', 'weg2'], # For testing purposes 'test': ['delete'] }, 'commons': { 'commons': ['cfd', 'move'] } } class CategoryPreprocess(BaseBot): """A class to prepare a list of pages for robots.""" def __init__(self, follow_redirects=False, edit_redirects=False, create=False, **kwargs): """Initializer.""" super(CategoryPreprocess, self).__init__(**kwargs) self.follow_redirects = follow_redirects self.edit_redirects = edit_redirects self.create = create def determine_type_target(self, page) -> Optional[pywikibot.Page]: """ Return page to be categorized by type. @param page: Existing, missing or redirect page to be processed. @type page: pywikibot.Page @return: Page to be categorized. """ if page.exists(): if page.isRedirectPage(): # if it is a redirect, use the redirect target instead redir_target = page.getRedirectTarget() if self.follow_redirects: if redir_target.exists(): return redir_target if self.create: redir_target.text = '' pywikibot.output('Redirect target {} does not exist ' 'yet; creating.'.format( redir_target.title(as_link=True))) return redir_target if self.edit_redirects: return page pywikibot.warning('Redirect target {} can not ' 'be modified; skipping.'.format( redir_target.title(as_link=True))) return None if self.edit_redirects: return page pywikibot.warning('Page {} is a redirect to {}; skipping.' .format(page.title(as_link=True), redir_target.title(as_link=True))) return None return page if self.create: page.text = '' pywikibot.output('Page {} does not exist yet; creating.' .format(page.title(as_link=True))) return page pywikibot.warning('Page {} does not exist; skipping.' .format(page.title(as_link=True))) return None def determine_template_target(self, page) -> pywikibot.Page: """ Return template page to be categorized. Categories for templates can be included in <includeonly> section of template doc page. Also the doc page can be changed by doc template parameter. TODO: decide if/how to enable/disable this feature. @param page: Page to be processed. @type page: pywikibot.Page @return: Page to be categorized. """ includeonly = [] if page.namespace() == page.site.namespaces.TEMPLATE: try: tmpl, loc = moved_links[page.site.code] except KeyError: tmpl = [] if not isinstance(tmpl, list): tmpl = [tmpl] if tmpl != []: templates = page.templatesWithParams() for template, params in templates: if (template.title(with_ns=False).lower() in tmpl and params): doc_page = pywikibot.Page(page.site, params[0]) if doc_page.exists(): page = doc_page includeonly = ['includeonly'] break if includeonly == []: docs = page.site.doc_subpage # return tuple for doc in docs: doc_page = pywikibot.Page(page.site, page.title() + doc) if doc_page.exists(): page = doc_page includeonly = ['includeonly'] break self.includeonly = includeonly return page class CategoryDatabase: """Temporary database saving pages and subcategories for each category. This prevents loading the category pages over and over again. """ def __init__(self, rebuild=False, filename='category.dump.bz2') -> None: """Initializer.""" if not os.path.isabs(filename): filename = config.datafilepath(filename) self.filename = filename if rebuild: self.rebuild() @property def is_loaded(self) -> bool: """Return whether the contents have been loaded.""" return hasattr(self, 'catContentDB') and hasattr(self, 'superclassDB') def _load(self) -> None: if not self.is_loaded: try: if config.verbose_output: pywikibot.output('Reading dump from ' + config.shortpath(self.filename)) with open_archive(self.filename, 'rb') as f: databases = pickle.load(f) # keys are categories, values are 2-tuples with lists as # entries. self.catContentDB = databases['catContentDB'] # like the above, but for supercategories self.superclassDB = databases['superclassDB'] del databases except Exception: # If something goes wrong, just rebuild the database self.rebuild() def rebuild(self) -> None: """Rebuild the dabatase.""" self.catContentDB = {} self.superclassDB = {} def getSubcats(self, supercat) -> Set[pywikibot.Category]: """Return the list of subcategories for a given supercategory. Saves this list in a temporary database so that it won't be loaded from the server next time it's required. """ self._load() # if we already know which subcategories exist here if supercat in self.catContentDB: return self.catContentDB[supercat][0] else: subcatset = set(supercat.subcategories()) articleset = set(supercat.articles()) # add to dictionary self.catContentDB[supercat] = (subcatset, articleset) return subcatset def getArticles(self, cat) -> Set[pywikibot.Page]: """Return the list of pages for a given category. Saves this list in a temporary database so that it won't be loaded from the server next time it's required. """ self._load() # if we already know which articles exist here. if cat in self.catContentDB: return self.catContentDB[cat][1] else: subcatset = set(cat.subcategories()) articleset = set(cat.articles()) # add to dictionary self.catContentDB[cat] = (subcatset, articleset) return articleset def getSupercats(self, subcat) -> Set[pywikibot.Category]: """Return the supercategory (or a set of) for a given subcategory.""" self._load() # if we already know which subcategories exist here. if subcat in self.superclassDB: return self.superclassDB[subcat] else: supercatset = set(subcat.categories()) # add to dictionary self.superclassDB[subcat] = supercatset return supercatset def dump(self, filename=None) -> None: """Save the dictionaries to disk if not empty. Pickle the contents of the dictionaries superclassDB and catContentDB if at least one is not empty. If both are empty, removes the file from the disk. If the filename is None, it'll use the filename determined in __init__. """ if filename is None: filename = self.filename elif not os.path.isabs(filename): filename = config.datafilepath(filename) if self.is_loaded and (self.catContentDB or self.superclassDB): pywikibot.output('Dumping to {}, please wait...' .format(config.shortpath(filename))) databases = { 'catContentDB': self.catContentDB, 'superclassDB': self.superclassDB } # store dump to disk in binary format with open_archive(filename, 'wb') as f: try: pickle.dump(databases, f, protocol=config.pickle_protocol) except pickle.PicklingError: pass else: try: os.remove(filename) except EnvironmentError: pass else: pywikibot.output('Database is empty. {} removed' .format(config.shortpath(filename))) class CategoryAddBot(MultipleSitesBot, CategoryPreprocess): """A robot to mass-add a category to a list of pages.""" @deprecated_args(editSummary='comment', dry=None) def __init__(self, generator, newcat=None, sort_by_last_name=False, create=False, comment='', follow_redirects=False) -> None: """Initializer.""" super().__init__() self.generator = generator self.newcat = newcat self.sort = sort_by_last_name self.create = create self.follow_redirects = follow_redirects self.always = False self.comment = comment def sorted_by_last_name(self, catlink, pagelink) -> pywikibot.Page: """Return a Category with key that sorts persons by their last name. Parameters: catlink - The Category to be linked. pagelink - the Page to be placed in the category. Trailing words in brackets will be removed. Example: If category_name is 'Author' and pl is a Page to [[Alexandre Dumas (senior)]], this function will return this Category: [[Category:Author|Dumas, Alexandre]]. """ page_name = pagelink.title() site = pagelink.site # regular expression that matches a name followed by a space and # disambiguation brackets. Group 1 is the name without the rest. bracketsR = re.compile(r'(.*) \(.+?\)') match_object = bracketsR.match(page_name) if match_object: page_name = match_object.group(1) split_string = page_name.rsplit(' ', 1) if len(split_string) > 1: # pull last part of the name to the beginning, and append the # rest after a comma; e.g., "John von Neumann" becomes # "Neumann, John von" sorted_key = split_string[1] + ', ' + split_string[0] # give explicit sort key return pywikibot.Page(site, catlink.title() + '|' + sorted_key) else: return pywikibot.Page(site, catlink.title()) def treat(self, page) -> None: """Process one page.""" # find correct categorization target page = self.determine_type_target(page) if not page: return self.current_page = self.determine_template_target(page) # load the page text = self.current_page.text # store old text, so we don't have reload it every time old_text = text cats = textlib.getCategoryLinks( text, self.current_page.site, include=self.includeonly) pywikibot.output('Current categories:') for cat in cats: pywikibot.output('* ' + cat.title()) catpl = pywikibot.Category(self.current_page.site, self.newcat) if catpl in cats: pywikibot.output('{} is already in {}.' .format(self.current_page.title(), catpl.title())) else: if self.sort: catpl = self.sorted_by_last_name(catpl, self.current_page) pywikibot.output('Adding %s' % catpl.title(as_link=True)) if page.namespace() == page.site.namespaces.TEMPLATE: tagname = 'noinclude' if self.includeonly == ['includeonly']: tagname = 'includeonly' tagnameregexp = re.compile(r'(.*)(<\/{0}>)'.format(tagname), re.I | re.DOTALL) categorytitle = catpl.title( as_link=True, allow_interwiki=False) if tagnameregexp.search(text): # add category into the <includeonly> tag in the # template document page or the <noinclude> tag # in the template page text = textlib.replaceExcept( text, tagnameregexp, r'\1{0}\n\2'.format(categorytitle), ['nowiki', 'comment', 'math', 'pre', 'source'], site=self.current_page.site) else: if self.includeonly == ['includeonly']: text += '\n\n' text += '<{0}>\n{1}\n</{0}>'.format( tagname, categorytitle) else: cats.append(catpl) text = textlib.replaceCategoryLinks( text, cats, site=self.current_page.site) comment = self.comment if not comment: comment = i18n.twtranslate(self.current_page.site, 'category-adding', {'newcat': catpl.title( with_ns=False)}) try: self.userPut(self.current_page, old_text, text, summary=comment) except pywikibot.PageSaveRelatedError as error: pywikibot.output('Page {} not saved: {}' .format(self.current_page.title(as_link=True), error)) class CategoryMoveRobot(CategoryPreprocess): """Change or remove the category from the pages. If the new category is given changes the category from the old to the new one. Otherwise remove the category from the page and the category if it's empty. Per default the operation applies to pages and subcategories. """ DELETION_COMMENT_AUTOMATIC = 0 DELETION_COMMENT_SAME_AS_EDIT_COMMENT = 1 @deprecated_args(oldCatTitle='oldcat', newCatTitle='newcat', batchMode='batch', editSummary='comment', inPlace='inplace', moveCatPage='move_oldcat', deleteEmptySourceCat='delete_oldcat', titleRegex='title_regex', withHistory='history') def __init__(self, oldcat, newcat=None, batch=False, comment='', inplace=False, move_oldcat=True, delete_oldcat=True, title_regex=None, history=False, pagesonly=False, deletion_comment=DELETION_COMMENT_AUTOMATIC, move_comment=None, wikibase=True, allow_split=False, move_together=False, keep_sortkey=None) -> None: """Store all given parameters in the objects attributes. @param oldcat: The move source. @param newcat: The move target. @param batch: If True the user has not to confirm the deletion. @param comment: The edit summary for all pages where the category is changed, and also for moves and deletions if not overridden. @param inplace: If True the categories are not reordered. @param move_oldcat: If True the category page (and talkpage) is copied to the new category. @param delete_oldcat: If True the oldcat page and talkpage are deleted (or nominated for deletion) if it is empty. @param title_regex: Only pages (and subcats) with a title that matches the regex are moved. @param history: If True the history of the oldcat is posted on the talkpage of newcat. @param pagesonly: If True only move pages, not subcategories. @param deletion_comment: Either string or special value: DELETION_COMMENT_AUTOMATIC: use a generated message, DELETION_COMMENT_SAME_AS_EDIT_COMMENT: use the same message for delete that is used for the edit summary of the pages whose category was changed (see the comment param above). If the value is not recognized, it's interpreted as DELETION_COMMENT_AUTOMATIC. @param move_comment: If set, uses this as the edit summary on the actual move of the category page. Otherwise, defaults to the value of the comment parameter. @param wikibase: If True, update the Wikibase item of the old category. @param allow_split: If False only moves page and talk page together. @param move_together: If True moves the pages/subcategories only if page and talk page could be moved or both source page and target page don't exist. """ self.site = pywikibot.Site() self.can_move_cats = self.site.has_right('move-categorypages') self.noredirect = delete_oldcat \ and self.site.has_right('suppressredirect') # Create attributes for the categories and their talk pages. self.oldcat = self._makecat(oldcat) self.oldtalk = self.oldcat.toggleTalkPage() if newcat: self.newcat = self._makecat(newcat) self.newtalk = self.newcat.toggleTalkPage() else: self.newcat = None self.newtalk = None # Set boolean settings. self.inplace = inplace self.move_oldcat = move_oldcat self.delete_oldcat = delete_oldcat self.batch = batch self.title_regex = title_regex self.history = history self.pagesonly = pagesonly # if that page doesn't has a wikibase self.wikibase = wikibase and self.site.has_data_repository self.allow_split = allow_split self.move_together = move_together self.keep_sortkey = keep_sortkey if not self.can_move_cats: repo = self.site.data_repository() if self.wikibase and repo.username() is None: # The bot can't move categories nor update the Wikibase repo raise pywikibot.NoUsername( "The 'wikibase' option is turned on and {0} has no " 'registered username.'.format(repo)) template_vars = {'oldcat': self.oldcat.title(with_ns=False)} if self.newcat: template_vars.update({ 'newcat': self.newcat.title( with_ns=False, as_link=True, textlink=True ), 'title': self.newcat.title(with_ns=False)}) # Set edit summary for changed pages. if comment: self.comment = comment elif self.newcat: self.comment = i18n.twtranslate(self.site, 'category-replacing', template_vars) else: self.comment = i18n.twtranslate(self.site, 'category-removing', template_vars) # Set deletion reason for category page and talkpage. if isinstance(deletion_comment, str): # Deletion comment is set to given string. self.deletion_comment = deletion_comment elif deletion_comment == self.DELETION_COMMENT_SAME_AS_EDIT_COMMENT: # Use the edit comment as the deletion comment. self.deletion_comment = self.comment else: # Deletion comment is set to internationalized default. if self.newcat: # Category is moved. self.deletion_comment = i18n.twtranslate(self.site, 'category-was-moved', template_vars) else: # Category is deleted. self.deletion_comment = i18n.twtranslate( self.site, 'category-was-disbanded') self.move_comment = move_comment if move_comment else self.comment def run(self) -> None: """ The main bot function that does all the work. For readability it is split into several helper functions: - _movecat() - _movetalk() - _hist() - _change() - _delete() """ # can_move_* determines if the page can be moved safely (target # doesn't exist but source does), move_items determines if the # items (pages/subcategories) of the category could be moved into # a new (non existent) category. can_move_page = CategoryMoveRobot.check_move( 'category page', self.oldcat, self.newcat) can_move_talk = CategoryMoveRobot.check_move( 'category talk page', self.oldtalk, self.newtalk) if not self.newcat: # delete move_items = True else: move_items = not self.newcat.exists() or not self.move_together if not self.allow_split: can_move_page = can_move_page and move_items can_move_talk = can_move_talk and move_items if self.newcat and self.move_oldcat: if self.can_move_cats: if can_move_page: old_cat_title = self.oldcat.title() old_cat_text = self.oldcat.text self.newcat = self.oldcat.move(self.newcat.title(), reason=self.move_comment, movetalk=can_move_talk, noredirect=self.noredirect) # Copy over the article text so it can be stripped of # CFD templates and re-saved. This is faster than # reloading the article in place. self.newcat.text = old_cat_text self._strip_cfd_templates() self.oldcat = pywikibot.Category(self.oldcat.site, old_cat_title) else: if can_move_page: self._movecat() if can_move_talk: self._movetalk() if self.wikibase: self._update_wikibase_item() if self.history and can_move_page: self._hist() if move_items: self._change(pagegenerators.CategorizedPageGenerator(self.oldcat)) if not self.pagesonly: self._change( pagegenerators.SubCategoriesPageGenerator(self.oldcat)) else: pywikibot.log("Didn't move pages/subcategories, because the " "category page hasn't been moved.") if self.oldcat.isEmptyCategory() and self.delete_oldcat and \ ((self.newcat and self.move_oldcat) or not self.newcat): self._delete(can_move_page, can_move_talk) def _delete(self, moved_page, moved_talk) -> None: """Private function to delete the category page and its talk page. Do not use this function from outside the class. Automatically marks the pages if they can't be removed due to missing permissions. @param moved_page: Category page to delete @param moved_talk: Talk page to delete @type moved_page: pywikibot.page.BasePage @type moved_talk: pywikibot.page.BasePage """ if moved_page and self.oldcat.exists(): self.oldcat.delete(self.deletion_comment, not self.batch, mark=True) if moved_talk and self.oldtalk.exists(): self.oldtalk.delete(self.deletion_comment, not self.batch, mark=True) def _change(self, gen) -> None: """ Private function to move category contents. Do not use this function from outside the class. @param gen: Generator containing pages or categories. """ for page in pagegenerators.PreloadingGenerator(gen): if not self.title_regex or re.search(self.title_regex, page.title()): page.change_category(self.oldcat, self.newcat, summary=self.comment, in_place=self.inplace, sort_key=self.keep_sortkey) doc_page = self.determine_template_target(page) if doc_page != page and (not self.title_regex or re.search(self.title_regex, doc_page.title())): doc_page.change_category(self.oldcat, self.newcat, summary=self.comment, in_place=self.inplace, include=self.includeonly, sort_key=self.keep_sortkey) @staticmethod def check_move(name, old_page, new_page) -> bool: """Return if the old page can be safely moved to the new page. @param name: Title of the new page @type name: str @param old_page: Page to be moved @type old_page: pywikibot.page.BasePage @param new_page: Page to be moved to @type new_page: pywikibot.page.BasePage @return: True if possible to move page, False if not page move not possible """ move_possible = True if new_page and new_page.exists(): pywikibot.warning("The {0} target '{1}' already exists." .format(name, new_page.title())) move_possible = False if not old_page.exists(): # only warn if not a talk page log = (pywikibot.log if old_page.namespace() % 2 else pywikibot.warning) log("Moving {0} '{1}' requested, but the page doesn't exist." .format(name, old_page.title())) move_possible = False return move_possible def _movecat(self) -> None: """Private function to move the category page by copying its contents. Note that this method of moving category pages by copying over the raw text been deprecated by the addition of true category moving (analogous to page moving) in MediaWiki, and so the raw text method is no longer the default. Do not use this function from outside the class. """ # Some preparing pywikibot.output('Moving text from {} to {}.'.format( self.oldcat.title(), self.newcat.title())) comma = self.site.mediawiki_message('comma-separator') authors = comma.join(self.oldcat.contributingUsers()) template_vars = {'oldcat': self.oldcat.title(), 'authors': authors} summary = i18n.twtranslate(self.site, 'category-renamed', template_vars) self.newcat.text = self.oldcat.text self._strip_cfd_templates(summary) def _strip_cfd_templates(self, summary=None, commit=True) -> None: """Private function to strip out CFD templates from the new category. The new category is saved. Do not use this function from outside the class. """ # Remove all substed CFD templates REGEX = (r'<!--\s*BEGIN CFD TEMPLATE\s*-->.*?' r'<!--\s*END CFD TEMPLATE\s*-->\n?') match = re.compile(REGEX, re.IGNORECASE | re.MULTILINE | re.DOTALL) self.newcat.text = match.sub('', self.newcat.text) # Remove all language-specified, non substed CFD templates site_templates = i18n.translate(self.site, cfd_templates) or () for template_name in site_templates: match = re.compile(r'{{%s.*?}}' % template_name, re.IGNORECASE) self.newcat.text = match.sub('', self.newcat.text) # Remove leading whitespace self.newcat.text = self.newcat.text.lstrip() if not summary: summary = i18n.twtranslate(self.site, 'category-strip-cfd-templates') if commit: self.newcat.save(summary=summary) def _movetalk(self) -> None: """Private function to move the category talk page. Do not use this function from outside the class. """ cat_name_only = self.newcat.title(with_ns=False) comment = i18n.twtranslate(self.site, 'category-was-moved', {'newcat': cat_name_only, 'title': cat_name_only}) self.oldtalk.move(self.newtalk.title(), comment) def _update_wikibase_item(self) -> None: """Private function to update the Wikibase item for the category. Do not use this function from outside the class. """ if self.oldcat.exists(): try: item = pywikibot.ItemPage.fromPage(self.oldcat) except pywikibot.NoPage: item = None if item and item.exists(): cat_name_only = self.newcat.title(with_ns=False) comment = i18n.twtranslate(self.site, 'category-was-moved', {'newcat': cat_name_only, 'title': cat_name_only}) item.setSitelink(self.newcat, summary=comment) def _hist(self) -> None: """Private function to copy the history of the to-be-deleted category. Do not use this function from outside the class. It adds a table with the history of the old category on the new talk page. """ history = self.oldcat.getVersionHistoryTable() title = i18n.twtranslate(self.site, 'category-section-title', {'oldcat': self.oldcat.title()}) self.newtalk.text = '{}\n== {} ==\n{}'.format(self.newtalk.text, title, history) comment = i18n.twtranslate(self.site, 'category-version-history', {'oldcat': self.oldcat.title()}) self.newtalk.save(comment) def _makecat(self, var) -> pywikibot.Category: """Private helper function to get a Category object. Checks if the instance given is a Category object and returns it. Otherwise creates a new object using the value as the title (for backwards compatibility). @param var: Either the title as a string or a Category object. """ if not isinstance(var, pywikibot.Category): var = pywikibot.Category(self.site, var) return var class CategoryRemoveRobot(CategoryMoveRobot): """Removes the category tag for a given category. It always removes the category tag for all pages in that given category. If pagesonly parameter is False it removes also the category from all subcategories, without prompting. If the category is empty, it will be tagged for deleting. Does not remove category tags pointing at subcategories. @deprecated: Using CategoryRemoveRobot is deprecated, use CategoryMoveRobot without newcat param instead. """ @deprecated('CategoryMoveRobot without newcat parameter', since='20140416', future_warning=True) def __init__( self, catTitle, batchMode=False, editSummary='', useSummaryForDeletion=CategoryMoveRobot.DELETION_COMMENT_AUTOMATIC, titleRegex=None, inPlace=False, pagesonly=False) -> None: """Initializer.""" super().__init__( oldcat=catTitle, batch=batchMode, comment=editSummary, deletion_comment=useSummaryForDeletion, title_regex=titleRegex, inplace=inPlace, pagesonly=pagesonly) class CategoryListifyRobot: """Create a list containing all of the members in a category.""" def __init__(self, catTitle, listTitle, editSummary, append=False, overwrite=False, showImages=False, subCats=False, talkPages=False, recurse=False, prefix='*') -> None: """Initializer.""" self.editSummary = editSummary self.append = append self.overwrite = overwrite self.showImages = showImages self.site = pywikibot.Site() self.cat = pywikibot.Category(self.site, catTitle) self.list = pywikibot.Page(self.site, listTitle) self.subCats = subCats self.talkPages = talkPages self.recurse = recurse self.prefix = prefix def run(self) -> None: """Start bot.""" setOfArticles = set(self.cat.articles(recurse=self.recurse)) if self.subCats: setOfArticles = setOfArticles.union(set(self.cat.subcategories())) if not self.editSummary: self.editSummary = i18n.twtranslate(self.site, 'category-listifying', {'fromcat': self.cat.title(), 'num': len(setOfArticles)}) listString = '' for article in setOfArticles: if (not article.is_filepage() or self.showImages) and not article.is_categorypage(): if self.talkPages and not article.isTalkPage(): listString += '{0} [[{1}]] -- [[{2}|talk]]\n'.format( self.prefix, article.title(), article.toggleTalkPage().title()) else: listString += '{0} [[{1}]]\n'.format(self.prefix, article.title()) else: if self.talkPages and not article.isTalkPage(): listString += '{0} [[:{1}]] -- [[{2}|talk]]\n'.format( self.prefix, article.title(), article.toggleTalkPage().title()) else: listString += '{0} [[:{1}]]\n'.format(self.prefix, article.title()) if self.list.exists(): if self.append: # append content by default at the bottom listString = self.list.text + '\n' + listString pywikibot.output('Category list appending...') elif not self.overwrite: pywikibot.output( 'Page {} already exists, aborting.\n' 'Use -overwrite option to overwrite the output page.' .format(self.list.title())) return self.list.put(listString, summary=self.editSummary) class CategoryTidyRobot(Bot, CategoryPreprocess): """ Robot to move members of a category into sub- or super-categories. Specify the category title on the command line. The robot will pick up the page, look for all sub- and super-categories, and show them listed as possibilities to move page into with an assigned number. It will ask you to type number of the appropriate replacement, and performs the change robotically. It will then automatically loop over all pages in the category. If you don't want to move the member to a sub- or super-category, but to another category, you can use the 'j' (jump) command. By typing 's' you can leave the complete page unchanged. By typing 'm' you can show more content of the current page, helping you to find out what the page is about and in which other categories it currently is. @param cat_title: a title of the category to process. @type: str @param cat_db: a CategoryDatabase object. @type: CategoryDatabase object @param namespaces: namespaces to focus on. @type: iterable of pywikibot.Namespace @param comment: a custom summary for edits. @type: str """ def __init__(self, cat_title, cat_db, namespaces=None, comment=None ) -> None: """Initializer.""" self.cat_title = cat_title self.cat_db = cat_db self.edit_summary = comment if not comment: self.template_vars = {'oldcat': cat_title} site = pywikibot.Site() self.cat = pywikibot.Category(site, cat_title) super(CategoryTidyRobot, self).__init__( generator=pagegenerators.PreloadingGenerator( self.cat.articles(namespaces=namespaces))) @deprecated_args(article='member') def move_to_category(self, member, original_cat, current_cat) -> None: """ Ask whether to move it to one of the sub- or super-categories. Given a page in the original_cat category, ask the user whether to move it to one of original_cat's sub- or super-categories. Recursively run through subcategories' subcategories. NOTE: current_cat is only used for internal recursion. You should always use current_cat = original_cat. @param member: a page to process. @type: pywikibot.Page @param original_cat: original category to replace. @type: pywikibot.Category @param current_cat: a category which is questioned. @type: pywikibot.Category """ class CatContextOption(ContextOption): """An option to show more and more context and categories.""" def output_range(self, start, end) -> None: """Output a section and categories from the text.""" pywikibot.output(self.text[start:end] + '...') # if categories weren't visible, show them additionally if len(self.text) > end: for cat in member.categories(): if cat != original_cat: pywikibot.output(cat.title(as_link=True)) else: pywikibot.output(color_format( '{lightpurple}{0}{default}', current_cat.title(as_link=True))) class CatIntegerOption(IntegerOption): """An option allowing a range of integers.""" def list_categories(self, cat_list, prefix='') -> None: """ Output categories in one or two columns. Determine whether the list contains long or short category titles and output category titles as enumerated options. @param cat_list: sorted iterable of category titles to output. @type: iterable of str @param prefix: a prefix to assigned number index. @type: str """ # can we can output in two columns? count = len(cat_list) if count > 1 and len(max(cat_list, key=len)) <= 31: new_column = int(math.ceil(count / 2.0)) else: new_column = 0 # determine number format if count > 9: index = '%2d' else: index = '%d' lines = [] for i, cat in enumerate(cat_list): if new_column: if i == new_column: break # columnify i2 = i + new_column if i2 < count: lines.append('[{}{}] {:35}[{}{}] {}'.format( prefix, index % i, cat, prefix, index % i2, cat_list[i2])) else: lines.append('[{}{}] {}'.format( prefix, index % i, cat)) else: lines.append('[{}{}] {}'.format( prefix, index % i, cat)) # output the result for line in lines: pywikibot.output(line) # show the title of the page where the link was found. pywikibot.output('') pywikibot.output(color_format( '>>> {lightpurple}{0}{default} <<<', member.title())) # determine a reasonable amount of context. try: full_text = member.get() except pywikibot.NoPage: pywikibot.output('Page {} not found.'.format(member.title())) return # skip initial templates, images and comments for articles. if member.namespace() == member.site.namespaces.MAIN: excludes = ('template', 'file', 'comment') regexes = textlib._get_regexes(excludes, member.site) i = 0 while i < 3: i = 0 for reg in regexes: if reg.match(full_text): full_text = reg.sub(r'', full_text, count=1).lstrip() else: i += 1 # output context context_option = CatContextOption('show more context', 'm', full_text, 500, 500) context_option.output() # get super- and sub-categories # sort them to assign expectable numbers supercatlist = sorted(self.cat_db.getSupercats(current_cat), key=methodcaller('title')) subcatlist = sorted(self.cat_db.getSubcats(current_cat), key=methodcaller('title')) # show categories as possible choices with numbers pywikibot.output('') supercat_option = CatIntegerOption(0, len(supercatlist), 'u') if not supercatlist: pywikibot.output('This category has no supercategories.') else: pywikibot.output('Move up to category:') cat_list = [cat.title( with_ns=False) for cat in supercatlist] supercat_option.list_categories(cat_list, 'u') subcat_option = CatIntegerOption(0, len(subcatlist)) if not subcatlist: pywikibot.output('This category has no subcategories.') else: pywikibot.output('Move down to category:') cat_list = [cat.title(with_ns=False) for cat in subcatlist] subcat_option.list_categories(cat_list) # show possible options for the user pywikibot.output('') options = (supercat_option, subcat_option, StandardOption(color_format( 'save page to category {lightpurple}{0}{default}', current_cat.title(with_ns=False)), 'c'), StandardOption('remove the category from page', 'r'), StandardOption('skip page', 's'), context_option, StandardOption('jump to custom category', 'j'), ) choice = pywikibot.input_choice(color_format( 'Choice for page {lightpurple}{0}{default}:', member.title()), options, default='c') if choice == 'c': pywikibot.output('Saving page to {}'.format(current_cat.title())) if current_cat == original_cat: pywikibot.output('No changes necessary.') else: if not self.edit_summary: self.template_vars.update({ 'newcat': current_cat.title( as_link=True, textlink=True) }) self.edit_summary = i18n.twtranslate(self.site, 'category-replacing', self.template_vars) # change the category tag member.change_category(original_cat, current_cat, summary=self.edit_summary) doc_page = self.determine_template_target(member) if doc_page != member: doc_page.change_category(original_cat, current_cat, include=self.includeonly, summary=self.edit_summary) elif choice == 'j': new_cat_title = pywikibot.input('Please enter the category ' 'the page should be moved to:', default=None) # require an answer new_cat = pywikibot.Category(pywikibot.Link('Category:' + new_cat_title)) # recurse into chosen category self.move_to_category(member, original_cat, new_cat) elif choice == 'r': if not self.edit_summary: self.edit_summary = i18n.twtranslate(self.site, 'category-removing', self.template_vars) # remove the category tag member.change_category(original_cat, None, summary=self.edit_summary) doc_page = self.determine_template_target(member) if doc_page != member: doc_page.change_category(original_cat, None, include=self.includeonly, summary=self.edit_summary) elif choice != 's': if choice[0] == 'u': # recurse into supercategory self.move_to_category(member, original_cat, supercatlist[choice[1]]) elif choice[0] == '': # recurse into subcategory self.move_to_category(member, original_cat, subcatlist[choice[1]]) def teardown(self) -> None: """Cleanups after run operation.""" if self._generator_completed and not self._treat_counter: pywikibot.output('There are no pages or files in category {}.' .format(self.cat_title)) def treat(self, page) -> None: """Process page.""" pywikibot.output('') self.move_to_category(page, self.cat, self.cat) class CategoryTreeRobot: """Robot to create tree overviews of the category structure. Parameters: * catTitle - The category which will be the tree's root. * catDB - A CategoryDatabase object. * maxDepth - The limit beyond which no subcategories will be listed. This also guarantees that loops in the category structure won't be a problem. * filename - The textfile where the tree should be saved; None to print the tree to stdout. """ def __init__(self, catTitle, catDB, filename=None, maxDepth=10) -> None: """Initializer.""" self.catTitle = catTitle self.catDB = catDB if filename and not os.path.isabs(filename): filename = config.datafilepath(filename) self.filename = filename self.maxDepth = maxDepth self.site = pywikibot.Site() def treeview(self, cat, currentDepth=0, parent=None) -> str: """Return a tree view of all subcategories of cat. The multi-line string contains a tree view of all subcategories of cat, up to level maxDepth. Recursively calls itself. Parameters: * cat - the Category of the node we're currently opening. * currentDepth - the current level in the tree (for recursion). * parent - the Category of the category we're coming from. """ result = '#' * currentDepth if currentDepth > 0: result += ' ' result += cat.title(as_link=True, textlink=True, with_ns=False) result += ' (%d)' % cat.categoryinfo['pages'] if currentDepth < self.maxDepth // 2: # noisy dots pywikibot.output('.', newline=False) # Create a list of other cats which are supercats of the current cat supercat_names = [super_cat.title(as_link=True, textlink=True, with_ns=False) for super_cat in self.catDB.getSupercats(cat) if super_cat != parent] if supercat_names: # print this list, separated with commas, using translations # given in 'category-also-in' comma = self.site.mediawiki_message('comma-separator') result += ' ' + i18n.twtranslate(self.site, 'category-also-in', {'alsocat': comma.join( supercat_names)}) del supercat_names result += '\n' if currentDepth < self.maxDepth: for subcat in self.catDB.getSubcats(cat): # recurse into subdirectories result += self.treeview(subcat, currentDepth + 1, parent=cat) elif self.catDB.getSubcats(cat): # show that there are more categories beyond the depth limit result += '#' * (currentDepth + 1) + ' [...]\n' return result def run(self) -> None: """Handle the multi-line string generated by treeview. After string was generated by treeview it is either printed to the console or saved it to a file. """ cat = pywikibot.Category(self.site, self.catTitle) pywikibot.output('Generating tree...', newline=False) tree = self.treeview(cat) pywikibot.output('') if self.filename: pywikibot.output('Saving results in ' + self.filename) with codecs.open(self.filename, 'a', 'utf-8') as f: f.write(tree) else: pywikibot.stdout(tree) def main(*args) -> None: """ Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. @param args: command line arguments. @type args: str """ from_given = False to_given = False batch = False summary = '' inplace = False append = False overwrite = False showimages = False talkpages = False recurse = False title_regex = None pagesonly = False wikibase = True history = False rebuild = False allow_split = False move_together = False keep_sortkey = None depth = 5 prefix = '*' # Process global args and prepare generator args parser local_args = pywikibot.handle_args(args) gen_factory = pagegenerators.GeneratorFactory() # When this is True then the custom edit summary given for removing # categories from articles will also be used as the deletion reason. # Otherwise it will generate deletion specific comments. use_deletion_summary = True action = None sort_by_last_name = False create_pages = False follow_redirects = False delete_empty_cat = True unknown = [] for arg in local_args: if arg in ('add', 'remove', 'move', 'tidy', 'tree', 'listify'): action = arg continue if arg[0] != '-': unknown.append(arg) continue option, _, value = arg[1:].partition(':') if option == 'nodelete': delete_empty_cat = False elif option == 'person': sort_by_last_name = True elif option == 'rebuild': rebuild = True elif option == 'from': old_cat_title = value.replace('_', ' ') from_given = True elif option == 'to': new_cat_title = value.replace('_', ' ') to_given = True elif option == 'batch': batch = True elif option == 'inplace': inplace = True elif option == 'nodelsum': use_deletion_summary = False elif option == 'append': append = True elif option == 'overwrite': overwrite = True elif option == 'showimages': showimages = True elif option == 'summary': summary = value elif option == '-match': title_regex = value or pywikibot.input( 'Which regular expression should affected objects match?') elif option == 'talkpages': talkpages = True elif option == 'recurse': recurse = True elif option == 'pagesonly': pagesonly = True elif option == 'nowb': wikibase = False elif option == 'allowsplit': allow_split = True elif option == 'mvtogether': move_together = True elif option == 'create': create_pages = True elif option == 'redirect': follow_redirects = True elif option == 'hist': history = True elif option == 'depth': depth = int(value) elif option == 'keepsortkey': keep_sortkey = True elif option == 'prefix': prefix = value else: gen_factory.handleArg(arg) bot = None cat_db = CategoryDatabase(rebuild=rebuild) gen = gen_factory.getCombinedGenerator() if action == 'add': if not to_given: new_cat_title = pywikibot.input( 'Category to add (do not give namespace):') if not gen: # default for backwards compatibility gen_factory.handleArg('-links') gen = gen_factory.getCombinedGenerator() # The preloading generator is responsible for downloading multiple # pages from the wiki simultaneously. gen = pagegenerators.PreloadingGenerator(gen) bot = CategoryAddBot(gen, newcat=new_cat_title, sort_by_last_name=sort_by_last_name, create=create_pages, comment=summary, follow_redirects=follow_redirects) elif action == 'remove': if not from_given: old_cat_title = pywikibot.input('Please enter the name of the ' 'category that should be removed:') bot = CategoryMoveRobot(oldcat=old_cat_title, batch=batch, comment=summary, inplace=inplace, delete_oldcat=delete_empty_cat, title_regex=title_regex, history=history, pagesonly=pagesonly, deletion_comment=use_deletion_summary) elif action == 'move': if not from_given: old_cat_title = pywikibot.input( 'Please enter the old name of the category:') if not to_given: new_cat_title = pywikibot.input( 'Please enter the new name of the category:') if use_deletion_summary: deletion_comment = \ CategoryMoveRobot.DELETION_COMMENT_SAME_AS_EDIT_COMMENT else: deletion_comment = CategoryMoveRobot.DELETION_COMMENT_AUTOMATIC bot = CategoryMoveRobot(oldcat=old_cat_title, newcat=new_cat_title, batch=batch, comment=summary, inplace=inplace, delete_oldcat=delete_empty_cat, title_regex=title_regex, history=history, pagesonly=pagesonly, deletion_comment=deletion_comment, wikibase=wikibase, allow_split=allow_split, move_together=move_together, keep_sortkey=keep_sortkey) elif action == 'tidy': cat_title = pywikibot.input('Which category do you want to tidy up?') bot = CategoryTidyRobot(cat_title, cat_db, gen_factory.namespaces, summary) elif action == 'tree': catTitle = pywikibot.input( 'For which category do you want to create a tree view?') filename = pywikibot.input( 'Please enter the name of the file where the tree should be saved,' '\nor press enter to simply show the tree:') bot = CategoryTreeRobot(catTitle, cat_db, filename, depth) elif action == 'listify': if not from_given: old_cat_title = pywikibot.input( 'Please enter the name of the category to listify:') if not to_given: new_cat_title = pywikibot.input( 'Please enter the name of the list to create:') bot = CategoryListifyRobot(old_cat_title, new_cat_title, summary, append, overwrite, showimages, subCats=True, talkPages=talkpages, recurse=recurse, prefix=prefix) if bot: pywikibot.Site().login() suggest_help(unknown_parameters=unknown) try: bot.run() except pywikibot.Error: pywikibot.error('Fatal error:', exc_info=True) finally: if cat_db: cat_db.dump() else: suggest_help(missing_action=True, unknown_parameters=unknown) if __name__ == '__main__': main() wrapper = ModuleDeprecationWrapper(__name__) wrapper._add_deprecated_attr('AddCategory', CategoryAddBot, since='20140918', future_warning=True)
41.815315
79
0.559256
import codecs import math import os import pickle import re from operator import methodcaller from typing import Optional, Set import pywikibot from pywikibot import config, pagegenerators from pywikibot import i18n, textlib from pywikibot.bot import ( suggest_help, IntegerOption, StandardOption, ContextOption, BaseBot, Bot, MultipleSitesBot, ) from pywikibot.cosmetic_changes import moved_links from pywikibot.tools import ( deprecated_args, deprecated, ModuleDeprecationWrapper, open_archive, ) from pywikibot.tools.formatter import color_format docuReplacements = {'&params;': pagegenerators.parameterHelp} cfd_templates = { 'wikipedia': { 'cs': ['přesunout', 'přejmenovat', 'přejmenovat kategorii', 'přesunout kategorii', 'přejmenování kategorie'], 'en': ['cfd', 'cfr', 'cfru', 'cfr-speedy', 'cfm', 'cfdu'], 'fi': ['roskaa', 'poistettava', 'korjattava/nimi', 'yhdistettäväLuokka'], 'fr': ['renommage de catégorie demandé'], 'he': ['הצבעת מחיקה', 'למחוק'], 'nl': ['categorieweg', 'catweg', 'wegcat', 'weg2'], 'test': ['delete'] }, 'commons': { 'commons': ['cfd', 'move'] } } class CategoryPreprocess(BaseBot): def __init__(self, follow_redirects=False, edit_redirects=False, create=False, **kwargs): super(CategoryPreprocess, self).__init__(**kwargs) self.follow_redirects = follow_redirects self.edit_redirects = edit_redirects self.create = create def determine_type_target(self, page) -> Optional[pywikibot.Page]: if page.exists(): if page.isRedirectPage(): redir_target = page.getRedirectTarget() if self.follow_redirects: if redir_target.exists(): return redir_target if self.create: redir_target.text = '' pywikibot.output('Redirect target {} does not exist ' 'yet; creating.'.format( redir_target.title(as_link=True))) return redir_target if self.edit_redirects: return page pywikibot.warning('Redirect target {} can not ' 'be modified; skipping.'.format( redir_target.title(as_link=True))) return None if self.edit_redirects: return page pywikibot.warning('Page {} is a redirect to {}; skipping.' .format(page.title(as_link=True), redir_target.title(as_link=True))) return None return page if self.create: page.text = '' pywikibot.output('Page {} does not exist yet; creating.' .format(page.title(as_link=True))) return page pywikibot.warning('Page {} does not exist; skipping.' .format(page.title(as_link=True))) return None def determine_template_target(self, page) -> pywikibot.Page: includeonly = [] if page.namespace() == page.site.namespaces.TEMPLATE: try: tmpl, loc = moved_links[page.site.code] except KeyError: tmpl = [] if not isinstance(tmpl, list): tmpl = [tmpl] if tmpl != []: templates = page.templatesWithParams() for template, params in templates: if (template.title(with_ns=False).lower() in tmpl and params): doc_page = pywikibot.Page(page.site, params[0]) if doc_page.exists(): page = doc_page includeonly = ['includeonly'] break if includeonly == []: docs = page.site.doc_subpage for doc in docs: doc_page = pywikibot.Page(page.site, page.title() + doc) if doc_page.exists(): page = doc_page includeonly = ['includeonly'] break self.includeonly = includeonly return page class CategoryDatabase: def __init__(self, rebuild=False, filename='category.dump.bz2') -> None: if not os.path.isabs(filename): filename = config.datafilepath(filename) self.filename = filename if rebuild: self.rebuild() @property def is_loaded(self) -> bool: return hasattr(self, 'catContentDB') and hasattr(self, 'superclassDB') def _load(self) -> None: if not self.is_loaded: try: if config.verbose_output: pywikibot.output('Reading dump from ' + config.shortpath(self.filename)) with open_archive(self.filename, 'rb') as f: databases = pickle.load(f) self.catContentDB = databases['catContentDB'] self.superclassDB = databases['superclassDB'] del databases except Exception: self.rebuild() def rebuild(self) -> None: self.catContentDB = {} self.superclassDB = {} def getSubcats(self, supercat) -> Set[pywikibot.Category]: self._load() if supercat in self.catContentDB: return self.catContentDB[supercat][0] else: subcatset = set(supercat.subcategories()) articleset = set(supercat.articles()) self.catContentDB[supercat] = (subcatset, articleset) return subcatset def getArticles(self, cat) -> Set[pywikibot.Page]: self._load() if cat in self.catContentDB: return self.catContentDB[cat][1] else: subcatset = set(cat.subcategories()) articleset = set(cat.articles()) self.catContentDB[cat] = (subcatset, articleset) return articleset def getSupercats(self, subcat) -> Set[pywikibot.Category]: self._load() if subcat in self.superclassDB: return self.superclassDB[subcat] else: supercatset = set(subcat.categories()) self.superclassDB[subcat] = supercatset return supercatset def dump(self, filename=None) -> None: if filename is None: filename = self.filename elif not os.path.isabs(filename): filename = config.datafilepath(filename) if self.is_loaded and (self.catContentDB or self.superclassDB): pywikibot.output('Dumping to {}, please wait...' .format(config.shortpath(filename))) databases = { 'catContentDB': self.catContentDB, 'superclassDB': self.superclassDB } with open_archive(filename, 'wb') as f: try: pickle.dump(databases, f, protocol=config.pickle_protocol) except pickle.PicklingError: pass else: try: os.remove(filename) except EnvironmentError: pass else: pywikibot.output('Database is empty. {} removed' .format(config.shortpath(filename))) class CategoryAddBot(MultipleSitesBot, CategoryPreprocess): @deprecated_args(editSummary='comment', dry=None) def __init__(self, generator, newcat=None, sort_by_last_name=False, create=False, comment='', follow_redirects=False) -> None: super().__init__() self.generator = generator self.newcat = newcat self.sort = sort_by_last_name self.create = create self.follow_redirects = follow_redirects self.always = False self.comment = comment def sorted_by_last_name(self, catlink, pagelink) -> pywikibot.Page: page_name = pagelink.title() site = pagelink.site bracketsR = re.compile(r'(.*) \(.+?\)') match_object = bracketsR.match(page_name) if match_object: page_name = match_object.group(1) split_string = page_name.rsplit(' ', 1) if len(split_string) > 1: sorted_key = split_string[1] + ', ' + split_string[0] return pywikibot.Page(site, catlink.title() + '|' + sorted_key) else: return pywikibot.Page(site, catlink.title()) def treat(self, page) -> None: page = self.determine_type_target(page) if not page: return self.current_page = self.determine_template_target(page) text = self.current_page.text old_text = text cats = textlib.getCategoryLinks( text, self.current_page.site, include=self.includeonly) pywikibot.output('Current categories:') for cat in cats: pywikibot.output('* ' + cat.title()) catpl = pywikibot.Category(self.current_page.site, self.newcat) if catpl in cats: pywikibot.output('{} is already in {}.' .format(self.current_page.title(), catpl.title())) else: if self.sort: catpl = self.sorted_by_last_name(catpl, self.current_page) pywikibot.output('Adding %s' % catpl.title(as_link=True)) if page.namespace() == page.site.namespaces.TEMPLATE: tagname = 'noinclude' if self.includeonly == ['includeonly']: tagname = 'includeonly' tagnameregexp = re.compile(r'(.*)(<\/{0}>)'.format(tagname), re.I | re.DOTALL) categorytitle = catpl.title( as_link=True, allow_interwiki=False) if tagnameregexp.search(text): # add category into the <includeonly> tag in the # template document page or the <noinclude> tag # in the template page text = textlib.replaceExcept( text, tagnameregexp, r'\1{0}\n\2'.format(categorytitle), ['nowiki', 'comment', 'math', 'pre', 'source'], site=self.current_page.site) else: if self.includeonly == ['includeonly']: text += '\n\n' text += '<{0}>\n{1}\n</{0}>'.format( tagname, categorytitle) else: cats.append(catpl) text = textlib.replaceCategoryLinks( text, cats, site=self.current_page.site) comment = self.comment if not comment: comment = i18n.twtranslate(self.current_page.site, 'category-adding', {'newcat': catpl.title( with_ns=False)}) try: self.userPut(self.current_page, old_text, text, summary=comment) except pywikibot.PageSaveRelatedError as error: pywikibot.output('Page {} not saved: {}' .format(self.current_page.title(as_link=True), error)) class CategoryMoveRobot(CategoryPreprocess): DELETION_COMMENT_AUTOMATIC = 0 DELETION_COMMENT_SAME_AS_EDIT_COMMENT = 1 @deprecated_args(oldCatTitle='oldcat', newCatTitle='newcat', batchMode='batch', editSummary='comment', inPlace='inplace', moveCatPage='move_oldcat', deleteEmptySourceCat='delete_oldcat', titleRegex='title_regex', withHistory='history') def __init__(self, oldcat, newcat=None, batch=False, comment='', inplace=False, move_oldcat=True, delete_oldcat=True, title_regex=None, history=False, pagesonly=False, deletion_comment=DELETION_COMMENT_AUTOMATIC, move_comment=None, wikibase=True, allow_split=False, move_together=False, keep_sortkey=None) -> None: self.site = pywikibot.Site() self.can_move_cats = self.site.has_right('move-categorypages') self.noredirect = delete_oldcat \ and self.site.has_right('suppressredirect') # Create attributes for the categories and their talk pages. self.oldcat = self._makecat(oldcat) self.oldtalk = self.oldcat.toggleTalkPage() if newcat: self.newcat = self._makecat(newcat) self.newtalk = self.newcat.toggleTalkPage() else: self.newcat = None self.newtalk = None # Set boolean settings. self.inplace = inplace self.move_oldcat = move_oldcat self.delete_oldcat = delete_oldcat self.batch = batch self.title_regex = title_regex self.history = history self.pagesonly = pagesonly # if that page doesn't has a wikibase self.wikibase = wikibase and self.site.has_data_repository self.allow_split = allow_split self.move_together = move_together self.keep_sortkey = keep_sortkey if not self.can_move_cats: repo = self.site.data_repository() if self.wikibase and repo.username() is None: raise pywikibot.NoUsername( "The 'wikibase' option is turned on and {0} has no " 'registered username.'.format(repo)) template_vars = {'oldcat': self.oldcat.title(with_ns=False)} if self.newcat: template_vars.update({ 'newcat': self.newcat.title( with_ns=False, as_link=True, textlink=True ), 'title': self.newcat.title(with_ns=False)}) # Set edit summary for changed pages. if comment: self.comment = comment elif self.newcat: self.comment = i18n.twtranslate(self.site, 'category-replacing', template_vars) else: self.comment = i18n.twtranslate(self.site, 'category-removing', template_vars) # Set deletion reason for category page and talkpage. if isinstance(deletion_comment, str): # Deletion comment is set to given string. self.deletion_comment = deletion_comment elif deletion_comment == self.DELETION_COMMENT_SAME_AS_EDIT_COMMENT: # Use the edit comment as the deletion comment. self.deletion_comment = self.comment else: # Deletion comment is set to internationalized default. if self.newcat: # Category is moved. self.deletion_comment = i18n.twtranslate(self.site, 'category-was-moved', template_vars) else: # Category is deleted. self.deletion_comment = i18n.twtranslate( self.site, 'category-was-disbanded') self.move_comment = move_comment if move_comment else self.comment def run(self) -> None: # can_move_* determines if the page can be moved safely (target # doesn't exist but source does), move_items determines if the can_move_page = CategoryMoveRobot.check_move( 'category page', self.oldcat, self.newcat) can_move_talk = CategoryMoveRobot.check_move( 'category talk page', self.oldtalk, self.newtalk) if not self.newcat: move_items = True else: move_items = not self.newcat.exists() or not self.move_together if not self.allow_split: can_move_page = can_move_page and move_items can_move_talk = can_move_talk and move_items if self.newcat and self.move_oldcat: if self.can_move_cats: if can_move_page: old_cat_title = self.oldcat.title() old_cat_text = self.oldcat.text self.newcat = self.oldcat.move(self.newcat.title(), reason=self.move_comment, movetalk=can_move_talk, noredirect=self.noredirect) self.newcat.text = old_cat_text self._strip_cfd_templates() self.oldcat = pywikibot.Category(self.oldcat.site, old_cat_title) else: if can_move_page: self._movecat() if can_move_talk: self._movetalk() if self.wikibase: self._update_wikibase_item() if self.history and can_move_page: self._hist() if move_items: self._change(pagegenerators.CategorizedPageGenerator(self.oldcat)) if not self.pagesonly: self._change( pagegenerators.SubCategoriesPageGenerator(self.oldcat)) else: pywikibot.log("Didn't move pages/subcategories, because the " "category page hasn't been moved.") if self.oldcat.isEmptyCategory() and self.delete_oldcat and \ ((self.newcat and self.move_oldcat) or not self.newcat): self._delete(can_move_page, can_move_talk) def _delete(self, moved_page, moved_talk) -> None: if moved_page and self.oldcat.exists(): self.oldcat.delete(self.deletion_comment, not self.batch, mark=True) if moved_talk and self.oldtalk.exists(): self.oldtalk.delete(self.deletion_comment, not self.batch, mark=True) def _change(self, gen) -> None: for page in pagegenerators.PreloadingGenerator(gen): if not self.title_regex or re.search(self.title_regex, page.title()): page.change_category(self.oldcat, self.newcat, summary=self.comment, in_place=self.inplace, sort_key=self.keep_sortkey) doc_page = self.determine_template_target(page) if doc_page != page and (not self.title_regex or re.search(self.title_regex, doc_page.title())): doc_page.change_category(self.oldcat, self.newcat, summary=self.comment, in_place=self.inplace, include=self.includeonly, sort_key=self.keep_sortkey) @staticmethod def check_move(name, old_page, new_page) -> bool: move_possible = True if new_page and new_page.exists(): pywikibot.warning("The {0} target '{1}' already exists." .format(name, new_page.title())) move_possible = False if not old_page.exists(): log = (pywikibot.log if old_page.namespace() % 2 else pywikibot.warning) log("Moving {0} '{1}' requested, but the page doesn't exist." .format(name, old_page.title())) move_possible = False return move_possible def _movecat(self) -> None: # Some preparing pywikibot.output('Moving text from {} to {}.'.format( self.oldcat.title(), self.newcat.title())) comma = self.site.mediawiki_message('comma-separator') authors = comma.join(self.oldcat.contributingUsers()) template_vars = {'oldcat': self.oldcat.title(), 'authors': authors} summary = i18n.twtranslate(self.site, 'category-renamed', template_vars) self.newcat.text = self.oldcat.text self._strip_cfd_templates(summary) def _strip_cfd_templates(self, summary=None, commit=True) -> None: # Remove all substed CFD templates REGEX = (r'<!--\s*BEGIN CFD TEMPLATE\s*-->.*?' r'<!--\s*END CFD TEMPLATE\s*-->\n?') match = re.compile(REGEX, re.IGNORECASE | re.MULTILINE | re.DOTALL) self.newcat.text = match.sub('', self.newcat.text) # Remove all language-specified, non substed CFD templates site_templates = i18n.translate(self.site, cfd_templates) or () for template_name in site_templates: match = re.compile(r'{{%s.*?}}' % template_name, re.IGNORECASE) self.newcat.text = match.sub('', self.newcat.text) # Remove leading whitespace self.newcat.text = self.newcat.text.lstrip() if not summary: summary = i18n.twtranslate(self.site, 'category-strip-cfd-templates') if commit: self.newcat.save(summary=summary) def _movetalk(self) -> None: cat_name_only = self.newcat.title(with_ns=False) comment = i18n.twtranslate(self.site, 'category-was-moved', {'newcat': cat_name_only, 'title': cat_name_only}) self.oldtalk.move(self.newtalk.title(), comment) def _update_wikibase_item(self) -> None: if self.oldcat.exists(): try: item = pywikibot.ItemPage.fromPage(self.oldcat) except pywikibot.NoPage: item = None if item and item.exists(): cat_name_only = self.newcat.title(with_ns=False) comment = i18n.twtranslate(self.site, 'category-was-moved', {'newcat': cat_name_only, 'title': cat_name_only}) item.setSitelink(self.newcat, summary=comment) def _hist(self) -> None: history = self.oldcat.getVersionHistoryTable() title = i18n.twtranslate(self.site, 'category-section-title', {'oldcat': self.oldcat.title()}) self.newtalk.text = '{}\n== {} ==\n{}'.format(self.newtalk.text, title, history) comment = i18n.twtranslate(self.site, 'category-version-history', {'oldcat': self.oldcat.title()}) self.newtalk.save(comment) def _makecat(self, var) -> pywikibot.Category: if not isinstance(var, pywikibot.Category): var = pywikibot.Category(self.site, var) return var class CategoryRemoveRobot(CategoryMoveRobot): @deprecated('CategoryMoveRobot without newcat parameter', since='20140416', future_warning=True) def __init__( self, catTitle, batchMode=False, editSummary='', useSummaryForDeletion=CategoryMoveRobot.DELETION_COMMENT_AUTOMATIC, titleRegex=None, inPlace=False, pagesonly=False) -> None: super().__init__( oldcat=catTitle, batch=batchMode, comment=editSummary, deletion_comment=useSummaryForDeletion, title_regex=titleRegex, inplace=inPlace, pagesonly=pagesonly) class CategoryListifyRobot: def __init__(self, catTitle, listTitle, editSummary, append=False, overwrite=False, showImages=False, subCats=False, talkPages=False, recurse=False, prefix='*') -> None: self.editSummary = editSummary self.append = append self.overwrite = overwrite self.showImages = showImages self.site = pywikibot.Site() self.cat = pywikibot.Category(self.site, catTitle) self.list = pywikibot.Page(self.site, listTitle) self.subCats = subCats self.talkPages = talkPages self.recurse = recurse self.prefix = prefix def run(self) -> None: setOfArticles = set(self.cat.articles(recurse=self.recurse)) if self.subCats: setOfArticles = setOfArticles.union(set(self.cat.subcategories())) if not self.editSummary: self.editSummary = i18n.twtranslate(self.site, 'category-listifying', {'fromcat': self.cat.title(), 'num': len(setOfArticles)}) listString = '' for article in setOfArticles: if (not article.is_filepage() or self.showImages) and not article.is_categorypage(): if self.talkPages and not article.isTalkPage(): listString += '{0} [[{1}]] -- [[{2}|talk]]\n'.format( self.prefix, article.title(), article.toggleTalkPage().title()) else: listString += '{0} [[{1}]]\n'.format(self.prefix, article.title()) else: if self.talkPages and not article.isTalkPage(): listString += '{0} [[:{1}]] -- [[{2}|talk]]\n'.format( self.prefix, article.title(), article.toggleTalkPage().title()) else: listString += '{0} [[:{1}]]\n'.format(self.prefix, article.title()) if self.list.exists(): if self.append: # append content by default at the bottom listString = self.list.text + '\n' + listString pywikibot.output('Category list appending...') elif not self.overwrite: pywikibot.output( 'Page {} already exists, aborting.\n' 'Use -overwrite option to overwrite the output page.' .format(self.list.title())) return self.list.put(listString, summary=self.editSummary) class CategoryTidyRobot(Bot, CategoryPreprocess): def __init__(self, cat_title, cat_db, namespaces=None, comment=None ) -> None: self.cat_title = cat_title self.cat_db = cat_db self.edit_summary = comment if not comment: self.template_vars = {'oldcat': cat_title} site = pywikibot.Site() self.cat = pywikibot.Category(site, cat_title) super(CategoryTidyRobot, self).__init__( generator=pagegenerators.PreloadingGenerator( self.cat.articles(namespaces=namespaces))) @deprecated_args(article='member') def move_to_category(self, member, original_cat, current_cat) -> None: class CatContextOption(ContextOption): def output_range(self, start, end) -> None: pywikibot.output(self.text[start:end] + '...') # if categories weren't visible, show them additionally if len(self.text) > end: for cat in member.categories(): if cat != original_cat: pywikibot.output(cat.title(as_link=True)) else: pywikibot.output(color_format( '{lightpurple}{0}{default}', current_cat.title(as_link=True))) class CatIntegerOption(IntegerOption): def list_categories(self, cat_list, prefix='') -> None: count = len(cat_list) if count > 1 and len(max(cat_list, key=len)) <= 31: new_column = int(math.ceil(count / 2.0)) else: new_column = 0 if count > 9: index = '%2d' else: index = '%d' lines = [] for i, cat in enumerate(cat_list): if new_column: if i == new_column: break i2 = i + new_column if i2 < count: lines.append('[{}{}] {:35}[{}{}] {}'.format( prefix, index % i, cat, prefix, index % i2, cat_list[i2])) else: lines.append('[{}{}] {}'.format( prefix, index % i, cat)) else: lines.append('[{}{}] {}'.format( prefix, index % i, cat)) for line in lines: pywikibot.output(line) pywikibot.output('') pywikibot.output(color_format( '>>> {lightpurple}{0}{default} <<<', member.title())) try: full_text = member.get() except pywikibot.NoPage: pywikibot.output('Page {} not found.'.format(member.title())) return if member.namespace() == member.site.namespaces.MAIN: excludes = ('template', 'file', 'comment') regexes = textlib._get_regexes(excludes, member.site) i = 0 while i < 3: i = 0 for reg in regexes: if reg.match(full_text): full_text = reg.sub(r'', full_text, count=1).lstrip() else: i += 1 context_option = CatContextOption('show more context', 'm', full_text, 500, 500) context_option.output() supercatlist = sorted(self.cat_db.getSupercats(current_cat), key=methodcaller('title')) subcatlist = sorted(self.cat_db.getSubcats(current_cat), key=methodcaller('title')) pywikibot.output('') supercat_option = CatIntegerOption(0, len(supercatlist), 'u') if not supercatlist: pywikibot.output('This category has no supercategories.') else: pywikibot.output('Move up to category:') cat_list = [cat.title( with_ns=False) for cat in supercatlist] supercat_option.list_categories(cat_list, 'u') subcat_option = CatIntegerOption(0, len(subcatlist)) if not subcatlist: pywikibot.output('This category has no subcategories.') else: pywikibot.output('Move down to category:') cat_list = [cat.title(with_ns=False) for cat in subcatlist] subcat_option.list_categories(cat_list) pywikibot.output('') options = (supercat_option, subcat_option, StandardOption(color_format( 'save page to category {lightpurple}{0}{default}', current_cat.title(with_ns=False)), 'c'), StandardOption('remove the category from page', 'r'), StandardOption('skip page', 's'), context_option, StandardOption('jump to custom category', 'j'), ) choice = pywikibot.input_choice(color_format( 'Choice for page {lightpurple}{0}{default}:', member.title()), options, default='c') if choice == 'c': pywikibot.output('Saving page to {}'.format(current_cat.title())) if current_cat == original_cat: pywikibot.output('No changes necessary.') else: if not self.edit_summary: self.template_vars.update({ 'newcat': current_cat.title( as_link=True, textlink=True) }) self.edit_summary = i18n.twtranslate(self.site, 'category-replacing', self.template_vars) member.change_category(original_cat, current_cat, summary=self.edit_summary) doc_page = self.determine_template_target(member) if doc_page != member: doc_page.change_category(original_cat, current_cat, include=self.includeonly, summary=self.edit_summary) elif choice == 'j': new_cat_title = pywikibot.input('Please enter the category ' 'the page should be moved to:', default=None) new_cat = pywikibot.Category(pywikibot.Link('Category:' + new_cat_title)) self.move_to_category(member, original_cat, new_cat) elif choice == 'r': if not self.edit_summary: self.edit_summary = i18n.twtranslate(self.site, 'category-removing', self.template_vars) member.change_category(original_cat, None, summary=self.edit_summary) doc_page = self.determine_template_target(member) if doc_page != member: doc_page.change_category(original_cat, None, include=self.includeonly, summary=self.edit_summary) elif choice != 's': if choice[0] == 'u': self.move_to_category(member, original_cat, supercatlist[choice[1]]) elif choice[0] == '': self.move_to_category(member, original_cat, subcatlist[choice[1]]) def teardown(self) -> None: if self._generator_completed and not self._treat_counter: pywikibot.output('There are no pages or files in category {}.' .format(self.cat_title)) def treat(self, page) -> None: pywikibot.output('') self.move_to_category(page, self.cat, self.cat) class CategoryTreeRobot: def __init__(self, catTitle, catDB, filename=None, maxDepth=10) -> None: self.catTitle = catTitle self.catDB = catDB if filename and not os.path.isabs(filename): filename = config.datafilepath(filename) self.filename = filename self.maxDepth = maxDepth self.site = pywikibot.Site() def treeview(self, cat, currentDepth=0, parent=None) -> str: result = '#' * currentDepth if currentDepth > 0: result += ' ' result += cat.title(as_link=True, textlink=True, with_ns=False) result += ' (%d)' % cat.categoryinfo['pages'] if currentDepth < self.maxDepth // 2: pywikibot.output('.', newline=False) supercat_names = [super_cat.title(as_link=True, textlink=True, with_ns=False) for super_cat in self.catDB.getSupercats(cat) if super_cat != parent] if supercat_names: comma = self.site.mediawiki_message('comma-separator') result += ' ' + i18n.twtranslate(self.site, 'category-also-in', {'alsocat': comma.join( supercat_names)}) del supercat_names result += '\n' if currentDepth < self.maxDepth: for subcat in self.catDB.getSubcats(cat): result += self.treeview(subcat, currentDepth + 1, parent=cat) elif self.catDB.getSubcats(cat): result += '#' * (currentDepth + 1) + ' [...]\n' return result def run(self) -> None: cat = pywikibot.Category(self.site, self.catTitle) pywikibot.output('Generating tree...', newline=False) tree = self.treeview(cat) pywikibot.output('') if self.filename: pywikibot.output('Saving results in ' + self.filename) with codecs.open(self.filename, 'a', 'utf-8') as f: f.write(tree) else: pywikibot.stdout(tree) def main(*args) -> None: from_given = False to_given = False batch = False summary = '' inplace = False append = False overwrite = False showimages = False talkpages = False recurse = False title_regex = None pagesonly = False wikibase = True history = False rebuild = False allow_split = False move_together = False keep_sortkey = None depth = 5 prefix = '*' local_args = pywikibot.handle_args(args) gen_factory = pagegenerators.GeneratorFactory() use_deletion_summary = True action = None sort_by_last_name = False create_pages = False follow_redirects = False delete_empty_cat = True unknown = [] for arg in local_args: if arg in ('add', 'remove', 'move', 'tidy', 'tree', 'listify'): action = arg continue if arg[0] != '-': unknown.append(arg) continue option, _, value = arg[1:].partition(':') if option == 'nodelete': delete_empty_cat = False elif option == 'person': sort_by_last_name = True elif option == 'rebuild': rebuild = True elif option == 'from': old_cat_title = value.replace('_', ' ') from_given = True elif option == 'to': new_cat_title = value.replace('_', ' ') to_given = True elif option == 'batch': batch = True elif option == 'inplace': inplace = True elif option == 'nodelsum': use_deletion_summary = False elif option == 'append': append = True elif option == 'overwrite': overwrite = True elif option == 'showimages': showimages = True elif option == 'summary': summary = value elif option == '-match': title_regex = value or pywikibot.input( 'Which regular expression should affected objects match?') elif option == 'talkpages': talkpages = True elif option == 'recurse': recurse = True elif option == 'pagesonly': pagesonly = True elif option == 'nowb': wikibase = False elif option == 'allowsplit': allow_split = True elif option == 'mvtogether': move_together = True elif option == 'create': create_pages = True elif option == 'redirect': follow_redirects = True elif option == 'hist': history = True elif option == 'depth': depth = int(value) elif option == 'keepsortkey': keep_sortkey = True elif option == 'prefix': prefix = value else: gen_factory.handleArg(arg) bot = None cat_db = CategoryDatabase(rebuild=rebuild) gen = gen_factory.getCombinedGenerator() if action == 'add': if not to_given: new_cat_title = pywikibot.input( 'Category to add (do not give namespace):') if not gen: gen_factory.handleArg('-links') gen = gen_factory.getCombinedGenerator() gen = pagegenerators.PreloadingGenerator(gen) bot = CategoryAddBot(gen, newcat=new_cat_title, sort_by_last_name=sort_by_last_name, create=create_pages, comment=summary, follow_redirects=follow_redirects) elif action == 'remove': if not from_given: old_cat_title = pywikibot.input('Please enter the name of the ' 'category that should be removed:') bot = CategoryMoveRobot(oldcat=old_cat_title, batch=batch, comment=summary, inplace=inplace, delete_oldcat=delete_empty_cat, title_regex=title_regex, history=history, pagesonly=pagesonly, deletion_comment=use_deletion_summary) elif action == 'move': if not from_given: old_cat_title = pywikibot.input( 'Please enter the old name of the category:') if not to_given: new_cat_title = pywikibot.input( 'Please enter the new name of the category:') if use_deletion_summary: deletion_comment = \ CategoryMoveRobot.DELETION_COMMENT_SAME_AS_EDIT_COMMENT else: deletion_comment = CategoryMoveRobot.DELETION_COMMENT_AUTOMATIC bot = CategoryMoveRobot(oldcat=old_cat_title, newcat=new_cat_title, batch=batch, comment=summary, inplace=inplace, delete_oldcat=delete_empty_cat, title_regex=title_regex, history=history, pagesonly=pagesonly, deletion_comment=deletion_comment, wikibase=wikibase, allow_split=allow_split, move_together=move_together, keep_sortkey=keep_sortkey) elif action == 'tidy': cat_title = pywikibot.input('Which category do you want to tidy up?') bot = CategoryTidyRobot(cat_title, cat_db, gen_factory.namespaces, summary) elif action == 'tree': catTitle = pywikibot.input( 'For which category do you want to create a tree view?') filename = pywikibot.input( 'Please enter the name of the file where the tree should be saved,' '\nor press enter to simply show the tree:') bot = CategoryTreeRobot(catTitle, cat_db, filename, depth) elif action == 'listify': if not from_given: old_cat_title = pywikibot.input( 'Please enter the name of the category to listify:') if not to_given: new_cat_title = pywikibot.input( 'Please enter the name of the list to create:') bot = CategoryListifyRobot(old_cat_title, new_cat_title, summary, append, overwrite, showimages, subCats=True, talkPages=talkpages, recurse=recurse, prefix=prefix) if bot: pywikibot.Site().login() suggest_help(unknown_parameters=unknown) try: bot.run() except pywikibot.Error: pywikibot.error('Fatal error:', exc_info=True) finally: if cat_db: cat_db.dump() else: suggest_help(missing_action=True, unknown_parameters=unknown) if __name__ == '__main__': main() wrapper = ModuleDeprecationWrapper(__name__) wrapper._add_deprecated_attr('AddCategory', CategoryAddBot, since='20140918', future_warning=True)
true
true
f725d27cbdff7297840854931171bd38aad72f40
2,668
py
Python
src/reactive/aodh_handlers.py
javacruft/charm-aodh
bd4d63d7baf1c1af542854ea1acfd936be01e27f
[ "Apache-2.0" ]
1
2016-06-21T16:33:22.000Z
2016-06-21T16:33:22.000Z
src/reactive/aodh_handlers.py
javacruft/charm-aodh
bd4d63d7baf1c1af542854ea1acfd936be01e27f
[ "Apache-2.0" ]
null
null
null
src/reactive/aodh_handlers.py
javacruft/charm-aodh
bd4d63d7baf1c1af542854ea1acfd936be01e27f
[ "Apache-2.0" ]
null
null
null
# Copyright 2016 Canonical Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import charms.reactive as reactive import charmhelpers.core.hookenv as hookenv # This charm's library contains all of the handler code associated with # aodh import charm.openstack.aodh as aodh # Minimal inferfaces required for operation MINIMAL_INTERFACES = [ 'shared-db.available', 'identity-service.available', 'amqp.available', ] # use a synthetic state to ensure that it get it to be installed independent of # the install hook. @reactive.when_not('charm.installed') def install_packages(): aodh.install() reactive.set_state('charm.installed') @reactive.when('amqp.connected') def setup_amqp_req(amqp): """Use the amqp interface to request access to the amqp broker using our local configuration. """ amqp.request_access(username='aodh', vhost='openstack') aodh.assess_status() @reactive.when('shared-db.connected') def setup_database(database): """On receiving database credentials, configure the database on the interface. """ database.configure('aodh', 'aodh', hookenv.unit_private_ip()) aodh.assess_status() @reactive.when('identity-service.connected') def setup_endpoint(keystone): aodh.setup_endpoint(keystone) aodh.assess_status() def render(*args): aodh.render_configs(args) reactive.set_state('config.complete') aodh.assess_status() @reactive.when('charm.installed') @reactive.when_not('cluster.available') @reactive.when(*MINIMAL_INTERFACES) def render_unclustered(*args): render(*args) @reactive.when('charm.installed') @reactive.when('cluster.available', *MINIMAL_INTERFACES) def render_clustered(*args): render(*args) @reactive.when('charm.installed') @reactive.when('config.complete') @reactive.when_not('db.synced') def run_db_migration(): aodh.db_sync() aodh.restart_all() reactive.set_state('db.synced') aodh.assess_status() @reactive.when('ha.connected') def cluster_connected(hacluster): aodh.configure_ha_resources(hacluster) @reactive.hook('upgrade-charm') def upgrade_charm(): aodh.install()
26.156863
79
0.733883
import charms.reactive as reactive import charmhelpers.core.hookenv as hookenv # aodh import charm.openstack.aodh as aodh # Minimal inferfaces required for operation MINIMAL_INTERFACES = [ 'shared-db.available', 'identity-service.available', 'amqp.available', ] # use a synthetic state to ensure that it get it to be installed independent of # the install hook. @reactive.when_not('charm.installed') def install_packages(): aodh.install() reactive.set_state('charm.installed') @reactive.when('amqp.connected') def setup_amqp_req(amqp): amqp.request_access(username='aodh', vhost='openstack') aodh.assess_status() @reactive.when('shared-db.connected') def setup_database(database): database.configure('aodh', 'aodh', hookenv.unit_private_ip()) aodh.assess_status() @reactive.when('identity-service.connected') def setup_endpoint(keystone): aodh.setup_endpoint(keystone) aodh.assess_status() def render(*args): aodh.render_configs(args) reactive.set_state('config.complete') aodh.assess_status() @reactive.when('charm.installed') @reactive.when_not('cluster.available') @reactive.when(*MINIMAL_INTERFACES) def render_unclustered(*args): render(*args) @reactive.when('charm.installed') @reactive.when('cluster.available', *MINIMAL_INTERFACES) def render_clustered(*args): render(*args) @reactive.when('charm.installed') @reactive.when('config.complete') @reactive.when_not('db.synced') def run_db_migration(): aodh.db_sync() aodh.restart_all() reactive.set_state('db.synced') aodh.assess_status() @reactive.when('ha.connected') def cluster_connected(hacluster): aodh.configure_ha_resources(hacluster) @reactive.hook('upgrade-charm') def upgrade_charm(): aodh.install()
true
true
f725d3b3f04ef12cb9eabb16862afc6710c21899
9,828
py
Python
userbot/modules/filemanager.py
akihiro69/akihirouserbot
e07da853e0938e40c29366d20ae7e917c215ceb6
[ "curl" ]
2
2022-03-04T12:25:41.000Z
2022-03-09T10:06:55.000Z
userbot/modules/filemanager.py
akihiro69/AkihiroProject
649ac4f8b786a36df25aa3085333940fe7825188
[ "curl" ]
null
null
null
userbot/modules/filemanager.py
akihiro69/AkihiroProject
649ac4f8b786a36df25aa3085333940fe7825188
[ "curl" ]
null
null
null
# Credits to Userge for Remove and Rename import io import os import os.path import re import shutil import time from datetime import datetime from os.path import basename, dirname, exists, isdir, isfile, join, relpath from shutil import rmtree from tarfile import TarFile, is_tarfile from zipfile import ZIP_DEFLATED, BadZipFile, ZipFile, is_zipfile from natsort import os_sorted from rarfile import BadRarFile, RarFile, is_rarfile from userbot import CMD_HANDLER as cmd from userbot import CMD_HELP, TEMP_DOWNLOAD_DIRECTORY, bot from userbot.events import geez_cmd from userbot.utils import humanbytes MAX_MESSAGE_SIZE_LIMIT = 4095 @bot.on(geez_cmd(outgoing=True, pattern=r"ls(?: |$)(.*)")) async def lst(event): if event.fwd_from: return cat = event.pattern_match.group(1) path = cat or os.getcwd() if not exists(path): await event.edit( f"Tidak ada direktori atau file dengan nama `{cat}` coba check lagi!" ) return if isdir(path): if cat: msg = "**Folder dan File di `{}`** :\n\n".format(path) else: msg = "**Folder dan File di Direktori Saat Ini** :\n\n" lists = os.listdir(path) files = "" folders = "" for contents in os_sorted(lists): catpath = path + "/" + contents if not isdir(catpath): size = os.stat(catpath).st_size if contents.endswith((".mp3", ".flac", ".wav", ".m4a")): files += "🎵 " elif contents.endswith((".opus")): files += "🎙 " elif contents.endswith( (".mkv", ".mp4", ".webm", ".avi", ".mov", ".flv") ): files += "🎞 " elif contents.endswith( (".zip", ".tar", ".tar.gz", ".rar", ".7z", ".xz") ): files += "🗜 " elif contents.endswith( (".jpg", ".jpeg", ".png", ".gif", ".bmp", ".ico", ".webp") ): files += "🖼 " elif contents.endswith((".exe", ".deb")): files += "⚙️ " elif contents.endswith((".iso", ".img")): files += "💿 " elif contents.endswith((".apk", ".xapk")): files += "📱 " elif contents.endswith((".py")): files += "🐍 " else: files += "📄 " files += f"`{contents}` (__{humanbytes(size)}__)\n" else: folders += f"📁 `{contents}`\n" msg = msg + folders + files if files or folders else msg + "__empty path__" else: size = os.stat(path).st_size msg = "Rincian file yang diberikan:\n\n" if path.endswith((".mp3", ".flac", ".wav", ".m4a")): mode = "🎵 " elif path.endswith((".opus")): mode = "🎙 " elif path.endswith((".mkv", ".mp4", ".webm", ".avi", ".mov", ".flv")): mode = "🎞 " elif path.endswith((".zip", ".tar", ".tar.gz", ".rar", ".7z", ".xz")): mode = "🗜 " elif path.endswith((".jpg", ".jpeg", ".png", ".gif", ".bmp", ".ico", ".webp")): mode = "🖼 " elif path.endswith((".exe", ".deb")): mode = "⚙️ " elif path.endswith((".iso", ".img")): mode = "💿 " elif path.endswith((".apk", ".xapk")): mode = "📱 " elif path.endswith((".py")): mode = "🐍 " else: mode = "📄 " time.ctime(os.path.getctime(path)) time2 = time.ctime(os.path.getmtime(path)) time3 = time.ctime(os.path.getatime(path)) msg += f"**Location :** `{path}`\n" msg += f"**Icon :** `{mode}`\n" msg += f"**Size :** `{humanbytes(size)}`\n" msg += f"**Last Modified Time:** `{time2}`\n" msg += f"**Last Accessed Time:** `{time3}`" if len(msg) > MAX_MESSAGE_SIZE_LIMIT: with io.BytesIO(str.encode(msg)) as out_file: out_file.name = "ls.txt" await event.client.send_file( event.chat_id, out_file, force_document=True, allow_cache=False, caption=path, ) await event.delete() else: await event.edit(msg) @bot.on(geez_cmd(outgoing=True, pattern=r"rm(?: |$)(.*)")) async def rmove(event): """Removing Directory/File""" cat = event.pattern_match.group(1) if not cat: await event.edit("`Lokasi file tidak ada!`") return if not exists(cat): await event.edit("`Lokasi file tidak ada!`") return if isfile(cat): os.remove(cat) else: rmtree(cat) await event.edit(f"Dihapus `{cat}`") @bot.on(geez_cmd(outgoing=True, pattern=r"rn ([^|]+)\|([^|]+)")) async def rname(event): """Renaming Directory/File""" cat = str(event.pattern_match.group(1)).strip() new_name = str(event.pattern_match.group(2)).strip() if not exists(cat): await event.edit(f"file path : {cat} tidak ada!") return new_path = join(dirname(cat), new_name) shutil.move(cat, new_path) await event.edit(f"Diganti nama dari `{cat}` ke `{new_path}`") @bot.on(geez_cmd(outgoing=True, pattern=r"zip (.*)")) async def zip_file(event): if event.fwd_from: return if not exists(TEMP_DOWNLOAD_DIRECTORY): os.makedirs(TEMP_DOWNLOAD_DIRECTORY) input_str = event.pattern_match.group(1) path = input_str zip_name = "" if "|" in input_str: path, zip_name = path.split("|") path = path.strip() zip_name = zip_name.strip() if exists(path): await event.edit("`Zipping...`") start_time = datetime.now() if isdir(path): dir_path = path.split("/")[-1] if path.endswith("/"): dir_path = path.split("/")[-2] zip_path = join(TEMP_DOWNLOAD_DIRECTORY, dir_path) + ".zip" if zip_name: zip_path = join(TEMP_DOWNLOAD_DIRECTORY, zip_name) if not zip_name.endswith(".zip"): zip_path += ".zip" with ZipFile(zip_path, "w", ZIP_DEFLATED) as zip_obj: for roots, _, files in os.walk(path): for file in files: files_path = join(roots, file) arc_path = join(dir_path, relpath(files_path, path)) zip_obj.write(files_path, arc_path) end_time = (datetime.now() - start_time).seconds await event.edit( f"Zipped `{path}` ke `{zip_path}` dalam `{end_time}` detik." ) elif isfile(path): file_name = basename(path) zip_path = join(TEMP_DOWNLOAD_DIRECTORY, file_name) + ".zip" if zip_name: zip_path = join(TEMP_DOWNLOAD_DIRECTORY, zip_name) if not zip_name.endswith(".zip"): zip_path += ".zip" with ZipFile(zip_path, "w", ZIP_DEFLATED) as zip_obj: zip_obj.write(path, file_name) await event.edit(f"Zipped `{path}` ke `{zip_path}`") else: await event.edit("`404: Not Found`") @bot.on(geez_cmd(outgoing=True, pattern=r"unzip (.*)")) async def unzip_file(event): if event.fwd_from: return if not exists(TEMP_DOWNLOAD_DIRECTORY): os.makedirs(TEMP_DOWNLOAD_DIRECTORY) input_str = event.pattern_match.group(1) file_name = basename(input_str) output_path = TEMP_DOWNLOAD_DIRECTORY + re.split("(.zip|.rar|.tar)", file_name)[0] if exists(input_str): start_time = datetime.now() await event.edit("`Unzipping...`") if is_zipfile(input_str): zip_type = ZipFile elif is_rarfile(input_str): zip_type = RarFile elif is_tarfile(input_str): zip_type = TarFile else: return await event.edit( "`Jenis file tidak didukung!`\n`Hanya Bisa ZIP, RAR dan TAR`" ) try: with zip_type(input_str, "r") as zip_obj: zip_obj.extractall(output_path) except BadRarFile: return await event.edit("**Error:** `File RAR Rusak`") except BadZipFile: return await event.edit("**Error:** `File ZIP Rusak`") except BaseException as err: return await event.edit(f"**Error:** `{err}`") end_time = (datetime.now() - start_time).seconds await event.edit( f"Unzipped `{input_str}` ke `{output_path}` dalam `{end_time}` detik." ) else: await event.edit("`404: Not Found`") CMD_HELP.update( { "file": f"**Plugin : **`file`\ \n\n 𝘾𝙤𝙢𝙢𝙖𝙣𝙙 :** `{cmd}ls`\ \n ❍▸ : **Untuk Melihat Daftar file di dalam direktori server\ \n\n 𝘾𝙤𝙢𝙢𝙖𝙣𝙙 :** `{cmd}rm` <directory/file>\ \n ❍▸ : **Untuk Menghapus File atau folder yg tersimpan di server\ \n\n 𝘾𝙤𝙢𝙢𝙖𝙣𝙙 :** `{cmd}rn` <directory/file> | <nama baru>\ \n ❍▸ : **Untuk Mengubah nama file atau direktori\ \n\n 𝘾𝙤𝙢𝙢𝙖𝙣𝙙 :** `{cmd}zip` <file/folder path> | <nama zip> (optional)\ \n ❍▸ : **Untuk mengcompress file atau folder.\ \n\n 𝘾𝙤𝙢𝙢𝙖𝙣𝙙 :** `{cmd}unzip` <path ke zip file>\ \n ❍▸ : **Untuk mengekstrak file arsip.\ \n • **NOTE : **Hanya bisa untuk file ZIP, RAR dan TAR!\ " } )
37.655172
88
0.50987
import io import os import os.path import re import shutil import time from datetime import datetime from os.path import basename, dirname, exists, isdir, isfile, join, relpath from shutil import rmtree from tarfile import TarFile, is_tarfile from zipfile import ZIP_DEFLATED, BadZipFile, ZipFile, is_zipfile from natsort import os_sorted from rarfile import BadRarFile, RarFile, is_rarfile from userbot import CMD_HANDLER as cmd from userbot import CMD_HELP, TEMP_DOWNLOAD_DIRECTORY, bot from userbot.events import geez_cmd from userbot.utils import humanbytes MAX_MESSAGE_SIZE_LIMIT = 4095 @bot.on(geez_cmd(outgoing=True, pattern=r"ls(?: |$)(.*)")) async def lst(event): if event.fwd_from: return cat = event.pattern_match.group(1) path = cat or os.getcwd() if not exists(path): await event.edit( f"Tidak ada direktori atau file dengan nama `{cat}` coba check lagi!" ) return if isdir(path): if cat: msg = "**Folder dan File di `{}`** :\n\n".format(path) else: msg = "**Folder dan File di Direktori Saat Ini** :\n\n" lists = os.listdir(path) files = "" folders = "" for contents in os_sorted(lists): catpath = path + "/" + contents if not isdir(catpath): size = os.stat(catpath).st_size if contents.endswith((".mp3", ".flac", ".wav", ".m4a")): files += "🎵 " elif contents.endswith((".opus")): files += "🎙 " elif contents.endswith( (".mkv", ".mp4", ".webm", ".avi", ".mov", ".flv") ): files += "🎞 " elif contents.endswith( (".zip", ".tar", ".tar.gz", ".rar", ".7z", ".xz") ): files += "🗜 " elif contents.endswith( (".jpg", ".jpeg", ".png", ".gif", ".bmp", ".ico", ".webp") ): files += "🖼 " elif contents.endswith((".exe", ".deb")): files += "⚙️ " elif contents.endswith((".iso", ".img")): files += "💿 " elif contents.endswith((".apk", ".xapk")): files += "📱 " elif contents.endswith((".py")): files += "🐍 " else: files += "📄 " files += f"`{contents}` (__{humanbytes(size)}__)\n" else: folders += f"📁 `{contents}`\n" msg = msg + folders + files if files or folders else msg + "__empty path__" else: size = os.stat(path).st_size msg = "Rincian file yang diberikan:\n\n" if path.endswith((".mp3", ".flac", ".wav", ".m4a")): mode = "🎵 " elif path.endswith((".opus")): mode = "🎙 " elif path.endswith((".mkv", ".mp4", ".webm", ".avi", ".mov", ".flv")): mode = "🎞 " elif path.endswith((".zip", ".tar", ".tar.gz", ".rar", ".7z", ".xz")): mode = "🗜 " elif path.endswith((".jpg", ".jpeg", ".png", ".gif", ".bmp", ".ico", ".webp")): mode = "🖼 " elif path.endswith((".exe", ".deb")): mode = "⚙️ " elif path.endswith((".iso", ".img")): mode = "💿 " elif path.endswith((".apk", ".xapk")): mode = "📱 " elif path.endswith((".py")): mode = "🐍 " else: mode = "📄 " time.ctime(os.path.getctime(path)) time2 = time.ctime(os.path.getmtime(path)) time3 = time.ctime(os.path.getatime(path)) msg += f"**Location :** `{path}`\n" msg += f"**Icon :** `{mode}`\n" msg += f"**Size :** `{humanbytes(size)}`\n" msg += f"**Last Modified Time:** `{time2}`\n" msg += f"**Last Accessed Time:** `{time3}`" if len(msg) > MAX_MESSAGE_SIZE_LIMIT: with io.BytesIO(str.encode(msg)) as out_file: out_file.name = "ls.txt" await event.client.send_file( event.chat_id, out_file, force_document=True, allow_cache=False, caption=path, ) await event.delete() else: await event.edit(msg) @bot.on(geez_cmd(outgoing=True, pattern=r"rm(?: |$)(.*)")) async def rmove(event): cat = event.pattern_match.group(1) if not cat: await event.edit("`Lokasi file tidak ada!`") return if not exists(cat): await event.edit("`Lokasi file tidak ada!`") return if isfile(cat): os.remove(cat) else: rmtree(cat) await event.edit(f"Dihapus `{cat}`") @bot.on(geez_cmd(outgoing=True, pattern=r"rn ([^|]+)\|([^|]+)")) async def rname(event): cat = str(event.pattern_match.group(1)).strip() new_name = str(event.pattern_match.group(2)).strip() if not exists(cat): await event.edit(f"file path : {cat} tidak ada!") return new_path = join(dirname(cat), new_name) shutil.move(cat, new_path) await event.edit(f"Diganti nama dari `{cat}` ke `{new_path}`") @bot.on(geez_cmd(outgoing=True, pattern=r"zip (.*)")) async def zip_file(event): if event.fwd_from: return if not exists(TEMP_DOWNLOAD_DIRECTORY): os.makedirs(TEMP_DOWNLOAD_DIRECTORY) input_str = event.pattern_match.group(1) path = input_str zip_name = "" if "|" in input_str: path, zip_name = path.split("|") path = path.strip() zip_name = zip_name.strip() if exists(path): await event.edit("`Zipping...`") start_time = datetime.now() if isdir(path): dir_path = path.split("/")[-1] if path.endswith("/"): dir_path = path.split("/")[-2] zip_path = join(TEMP_DOWNLOAD_DIRECTORY, dir_path) + ".zip" if zip_name: zip_path = join(TEMP_DOWNLOAD_DIRECTORY, zip_name) if not zip_name.endswith(".zip"): zip_path += ".zip" with ZipFile(zip_path, "w", ZIP_DEFLATED) as zip_obj: for roots, _, files in os.walk(path): for file in files: files_path = join(roots, file) arc_path = join(dir_path, relpath(files_path, path)) zip_obj.write(files_path, arc_path) end_time = (datetime.now() - start_time).seconds await event.edit( f"Zipped `{path}` ke `{zip_path}` dalam `{end_time}` detik." ) elif isfile(path): file_name = basename(path) zip_path = join(TEMP_DOWNLOAD_DIRECTORY, file_name) + ".zip" if zip_name: zip_path = join(TEMP_DOWNLOAD_DIRECTORY, zip_name) if not zip_name.endswith(".zip"): zip_path += ".zip" with ZipFile(zip_path, "w", ZIP_DEFLATED) as zip_obj: zip_obj.write(path, file_name) await event.edit(f"Zipped `{path}` ke `{zip_path}`") else: await event.edit("`404: Not Found`") @bot.on(geez_cmd(outgoing=True, pattern=r"unzip (.*)")) async def unzip_file(event): if event.fwd_from: return if not exists(TEMP_DOWNLOAD_DIRECTORY): os.makedirs(TEMP_DOWNLOAD_DIRECTORY) input_str = event.pattern_match.group(1) file_name = basename(input_str) output_path = TEMP_DOWNLOAD_DIRECTORY + re.split("(.zip|.rar|.tar)", file_name)[0] if exists(input_str): start_time = datetime.now() await event.edit("`Unzipping...`") if is_zipfile(input_str): zip_type = ZipFile elif is_rarfile(input_str): zip_type = RarFile elif is_tarfile(input_str): zip_type = TarFile else: return await event.edit( "`Jenis file tidak didukung!`\n`Hanya Bisa ZIP, RAR dan TAR`" ) try: with zip_type(input_str, "r") as zip_obj: zip_obj.extractall(output_path) except BadRarFile: return await event.edit("**Error:** `File RAR Rusak`") except BadZipFile: return await event.edit("**Error:** `File ZIP Rusak`") except BaseException as err: return await event.edit(f"**Error:** `{err}`") end_time = (datetime.now() - start_time).seconds await event.edit( f"Unzipped `{input_str}` ke `{output_path}` dalam `{end_time}` detik." ) else: await event.edit("`404: Not Found`") CMD_HELP.update( { "file": f"**Plugin : **`file`\ \n\n 𝘾𝙤𝙢𝙢𝙖𝙣𝙙 :** `{cmd}ls`\ \n ❍▸ : **Untuk Melihat Daftar file di dalam direktori server\ \n\n 𝘾𝙤𝙢𝙢𝙖𝙣𝙙 :** `{cmd}rm` <directory/file>\ \n ❍▸ : **Untuk Menghapus File atau folder yg tersimpan di server\ \n\n 𝘾𝙤𝙢𝙢𝙖𝙣𝙙 :** `{cmd}rn` <directory/file> | <nama baru>\ \n ❍▸ : **Untuk Mengubah nama file atau direktori\ \n\n 𝘾𝙤𝙢𝙢𝙖𝙣𝙙 :** `{cmd}zip` <file/folder path> | <nama zip> (optional)\ \n ❍▸ : **Untuk mengcompress file atau folder.\ \n\n 𝘾𝙤𝙢𝙢𝙖𝙣𝙙 :** `{cmd}unzip` <path ke zip file>\ \n ❍▸ : **Untuk mengekstrak file arsip.\ \n • **NOTE : **Hanya bisa untuk file ZIP, RAR dan TAR!\ " } )
true
true
f725d482affcb8a458620913281844682449d4b0
463
py
Python
virtual/lib/python3.6/site-packages/pylint/test/functional/disable_wrong_import_order.py
drewheathens/The-Moringa-Tribune
98ee4d63c9df6f1f7497fc6876960a822d914500
[ "MIT" ]
69
2019-02-18T12:07:35.000Z
2022-03-12T10:38:32.000Z
virtual/lib/python3.6/site-packages/pylint/test/functional/disable_wrong_import_order.py
drewheathens/The-Moringa-Tribune
98ee4d63c9df6f1f7497fc6876960a822d914500
[ "MIT" ]
32
2018-05-01T05:24:43.000Z
2022-03-11T23:20:39.000Z
virtual/lib/python3.6/site-packages/pylint/test/functional/disable_wrong_import_order.py
drewheathens/The-Moringa-Tribune
98ee4d63c9df6f1f7497fc6876960a822d914500
[ "MIT" ]
28
2019-03-22T01:07:13.000Z
2022-02-21T16:38:27.000Z
"""Checks that disabling 'wrong-import-order' on an import prevents subsequent imports from being considered out-of-order in respect to it but does not prevent it from being considered for 'ungrouped-imports'.""" # pylint: disable=unused-import,import-error,no-name-in-module from first_party.foo import bar # pylint: disable=wrong-import-order import logging import os.path import sys from astroid import are_exclusive import first_party # [ungrouped-imports]
38.583333
80
0.803456
from first_party.foo import bar import logging import os.path import sys from astroid import are_exclusive import first_party
true
true
f725d527eca9f1244b658df525134e4894d1750c
26,199
py
Python
discord/iterators.py
squaresmile/discord.py
44d5bafa3d44a0b4de6407727d8d313a55a77662
[ "MIT" ]
11,948
2015-08-25T00:07:50.000Z
2022-03-31T23:30:54.000Z
discord/iterators.py
squaresmile/discord.py
44d5bafa3d44a0b4de6407727d8d313a55a77662
[ "MIT" ]
6,163
2015-09-03T07:43:30.000Z
2022-03-31T16:56:47.000Z
discord/iterators.py
squaresmile/discord.py
44d5bafa3d44a0b4de6407727d8d313a55a77662
[ "MIT" ]
6,761
2015-08-25T18:44:12.000Z
2022-03-31T16:45:38.000Z
""" The MIT License (MIT) Copyright (c) 2015-present Rapptz Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from __future__ import annotations import asyncio import datetime from typing import Awaitable, TYPE_CHECKING, TypeVar, Optional, Any, Callable, Union, List, AsyncIterator from .errors import NoMoreItems from .utils import snowflake_time, time_snowflake, maybe_coroutine from .object import Object from .audit_logs import AuditLogEntry __all__ = ( 'ReactionIterator', 'HistoryIterator', 'AuditLogIterator', 'GuildIterator', 'MemberIterator', ) if TYPE_CHECKING: from .types.audit_log import ( AuditLog as AuditLogPayload, ) from .types.guild import ( Guild as GuildPayload, ) from .types.message import ( Message as MessagePayload, ) from .types.user import ( PartialUser as PartialUserPayload, ) from .types.threads import ( Thread as ThreadPayload, ) from .member import Member from .user import User from .message import Message from .audit_logs import AuditLogEntry from .guild import Guild from .threads import Thread from .abc import Snowflake T = TypeVar('T') OT = TypeVar('OT') _Func = Callable[[T], Union[OT, Awaitable[OT]]] OLDEST_OBJECT = Object(id=0) class _AsyncIterator(AsyncIterator[T]): __slots__ = () async def next(self) -> T: raise NotImplementedError def get(self, **attrs: Any) -> Awaitable[Optional[T]]: def predicate(elem: T): for attr, val in attrs.items(): nested = attr.split('__') obj = elem for attribute in nested: obj = getattr(obj, attribute) if obj != val: return False return True return self.find(predicate) async def find(self, predicate: _Func[T, bool]) -> Optional[T]: while True: try: elem = await self.next() except NoMoreItems: return None ret = await maybe_coroutine(predicate, elem) if ret: return elem def chunk(self, max_size: int) -> _ChunkedAsyncIterator[T]: if max_size <= 0: raise ValueError('async iterator chunk sizes must be greater than 0.') return _ChunkedAsyncIterator(self, max_size) def map(self, func: _Func[T, OT]) -> _MappedAsyncIterator[OT]: return _MappedAsyncIterator(self, func) def filter(self, predicate: _Func[T, bool]) -> _FilteredAsyncIterator[T]: return _FilteredAsyncIterator(self, predicate) async def flatten(self) -> List[T]: return [element async for element in self] async def __anext__(self) -> T: try: return await self.next() except NoMoreItems: raise StopAsyncIteration() def _identity(x): return x class _ChunkedAsyncIterator(_AsyncIterator[List[T]]): def __init__(self, iterator, max_size): self.iterator = iterator self.max_size = max_size async def next(self) -> List[T]: ret: List[T] = [] n = 0 while n < self.max_size: try: item = await self.iterator.next() except NoMoreItems: if ret: return ret raise else: ret.append(item) n += 1 return ret class _MappedAsyncIterator(_AsyncIterator[T]): def __init__(self, iterator, func): self.iterator = iterator self.func = func async def next(self) -> T: # this raises NoMoreItems and will propagate appropriately item = await self.iterator.next() return await maybe_coroutine(self.func, item) class _FilteredAsyncIterator(_AsyncIterator[T]): def __init__(self, iterator, predicate): self.iterator = iterator if predicate is None: predicate = _identity self.predicate = predicate async def next(self) -> T: getter = self.iterator.next pred = self.predicate while True: # propagate NoMoreItems similar to _MappedAsyncIterator item = await getter() ret = await maybe_coroutine(pred, item) if ret: return item class ReactionIterator(_AsyncIterator[Union['User', 'Member']]): def __init__(self, message, emoji, limit=100, after=None): self.message = message self.limit = limit self.after = after state = message._state self.getter = state.http.get_reaction_users self.state = state self.emoji = emoji self.guild = message.guild self.channel_id = message.channel.id self.users = asyncio.Queue() async def next(self) -> Union[User, Member]: if self.users.empty(): await self.fill_users() try: return self.users.get_nowait() except asyncio.QueueEmpty: raise NoMoreItems() async def fill_users(self): # this is a hack because >circular imports< from .user import User if self.limit > 0: retrieve = self.limit if self.limit <= 100 else 100 after = self.after.id if self.after else None data: List[PartialUserPayload] = await self.getter( self.channel_id, self.message.id, self.emoji, retrieve, after=after ) if data: self.limit -= retrieve self.after = Object(id=int(data[-1]['id'])) if self.guild is None or isinstance(self.guild, Object): for element in reversed(data): await self.users.put(User(state=self.state, data=element)) else: for element in reversed(data): member_id = int(element['id']) member = self.guild.get_member(member_id) if member is not None: await self.users.put(member) else: await self.users.put(User(state=self.state, data=element)) class HistoryIterator(_AsyncIterator['Message']): """Iterator for receiving a channel's message history. The messages endpoint has two behaviours we care about here: If ``before`` is specified, the messages endpoint returns the `limit` newest messages before ``before``, sorted with newest first. For filling over 100 messages, update the ``before`` parameter to the oldest message received. Messages will be returned in order by time. If ``after`` is specified, it returns the ``limit`` oldest messages after ``after``, sorted with newest first. For filling over 100 messages, update the ``after`` parameter to the newest message received. If messages are not reversed, they will be out of order (99-0, 199-100, so on) A note that if both ``before`` and ``after`` are specified, ``before`` is ignored by the messages endpoint. Parameters ----------- messageable: :class:`abc.Messageable` Messageable class to retrieve message history from. limit: :class:`int` Maximum number of messages to retrieve before: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] Message before which all messages must be. after: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] Message after which all messages must be. around: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] Message around which all messages must be. Limit max 101. Note that if limit is an even number, this will return at most limit+1 messages. oldest_first: Optional[:class:`bool`] If set to ``True``, return messages in oldest->newest order. Defaults to ``True`` if `after` is specified, otherwise ``False``. """ def __init__(self, messageable, limit, before=None, after=None, around=None, oldest_first=None): if isinstance(before, datetime.datetime): before = Object(id=time_snowflake(before, high=False)) if isinstance(after, datetime.datetime): after = Object(id=time_snowflake(after, high=True)) if isinstance(around, datetime.datetime): around = Object(id=time_snowflake(around)) if oldest_first is None: self.reverse = after is not None else: self.reverse = oldest_first self.messageable = messageable self.limit = limit self.before = before self.after = after or OLDEST_OBJECT self.around = around self._filter = None # message dict -> bool self.state = self.messageable._state self.logs_from = self.state.http.logs_from self.messages = asyncio.Queue() if self.around: if self.limit is None: raise ValueError('history does not support around with limit=None') if self.limit > 101: raise ValueError("history max limit 101 when specifying around parameter") elif self.limit == 101: self.limit = 100 # Thanks discord self._retrieve_messages = self._retrieve_messages_around_strategy # type: ignore if self.before and self.after: self._filter = lambda m: self.after.id < int(m['id']) < self.before.id elif self.before: self._filter = lambda m: int(m['id']) < self.before.id elif self.after: self._filter = lambda m: self.after.id < int(m['id']) else: if self.reverse: self._retrieve_messages = self._retrieve_messages_after_strategy # type: ignore if self.before: self._filter = lambda m: int(m['id']) < self.before.id else: self._retrieve_messages = self._retrieve_messages_before_strategy # type: ignore if self.after and self.after != OLDEST_OBJECT: self._filter = lambda m: int(m['id']) > self.after.id async def next(self) -> Message: if self.messages.empty(): await self.fill_messages() try: return self.messages.get_nowait() except asyncio.QueueEmpty: raise NoMoreItems() def _get_retrieve(self): l = self.limit if l is None or l > 100: r = 100 else: r = l self.retrieve = r return r > 0 async def fill_messages(self): if not hasattr(self, 'channel'): # do the required set up channel = await self.messageable._get_channel() self.channel = channel if self._get_retrieve(): data = await self._retrieve_messages(self.retrieve) if len(data) < 100: self.limit = 0 # terminate the infinite loop if self.reverse: data = reversed(data) if self._filter: data = filter(self._filter, data) channel = self.channel for element in data: await self.messages.put(self.state.create_message(channel=channel, data=element)) async def _retrieve_messages(self, retrieve) -> List[Message]: """Retrieve messages and update next parameters.""" raise NotImplementedError async def _retrieve_messages_before_strategy(self, retrieve): """Retrieve messages using before parameter.""" before = self.before.id if self.before else None data: List[MessagePayload] = await self.logs_from(self.channel.id, retrieve, before=before) if len(data): if self.limit is not None: self.limit -= retrieve self.before = Object(id=int(data[-1]['id'])) return data async def _retrieve_messages_after_strategy(self, retrieve): """Retrieve messages using after parameter.""" after = self.after.id if self.after else None data: List[MessagePayload] = await self.logs_from(self.channel.id, retrieve, after=after) if len(data): if self.limit is not None: self.limit -= retrieve self.after = Object(id=int(data[0]['id'])) return data async def _retrieve_messages_around_strategy(self, retrieve): """Retrieve messages using around parameter.""" if self.around: around = self.around.id if self.around else None data: List[MessagePayload] = await self.logs_from(self.channel.id, retrieve, around=around) self.around = None return data return [] class AuditLogIterator(_AsyncIterator['AuditLogEntry']): def __init__(self, guild, limit=None, before=None, after=None, oldest_first=None, user_id=None, action_type=None): if isinstance(before, datetime.datetime): before = Object(id=time_snowflake(before, high=False)) if isinstance(after, datetime.datetime): after = Object(id=time_snowflake(after, high=True)) if oldest_first is None: self.reverse = after is not None else: self.reverse = oldest_first self.guild = guild self.loop = guild._state.loop self.request = guild._state.http.get_audit_logs self.limit = limit self.before = before self.user_id = user_id self.action_type = action_type self.after = OLDEST_OBJECT self._users = {} self._state = guild._state self._filter = None # entry dict -> bool self.entries = asyncio.Queue() if self.reverse: self._strategy = self._after_strategy if self.before: self._filter = lambda m: int(m['id']) < self.before.id else: self._strategy = self._before_strategy if self.after and self.after != OLDEST_OBJECT: self._filter = lambda m: int(m['id']) > self.after.id async def _before_strategy(self, retrieve): before = self.before.id if self.before else None data: AuditLogPayload = await self.request( self.guild.id, limit=retrieve, user_id=self.user_id, action_type=self.action_type, before=before ) entries = data.get('audit_log_entries', []) if len(data) and entries: if self.limit is not None: self.limit -= retrieve self.before = Object(id=int(entries[-1]['id'])) return data.get('users', []), entries async def _after_strategy(self, retrieve): after = self.after.id if self.after else None data: AuditLogPayload = await self.request( self.guild.id, limit=retrieve, user_id=self.user_id, action_type=self.action_type, after=after ) entries = data.get('audit_log_entries', []) if len(data) and entries: if self.limit is not None: self.limit -= retrieve self.after = Object(id=int(entries[0]['id'])) return data.get('users', []), entries async def next(self) -> AuditLogEntry: if self.entries.empty(): await self._fill() try: return self.entries.get_nowait() except asyncio.QueueEmpty: raise NoMoreItems() def _get_retrieve(self): l = self.limit if l is None or l > 100: r = 100 else: r = l self.retrieve = r return r > 0 async def _fill(self): from .user import User if self._get_retrieve(): users, data = await self._strategy(self.retrieve) if len(data) < 100: self.limit = 0 # terminate the infinite loop if self.reverse: data = reversed(data) if self._filter: data = filter(self._filter, data) for user in users: u = User(data=user, state=self._state) self._users[u.id] = u for element in data: # TODO: remove this if statement later if element['action_type'] is None: continue await self.entries.put(AuditLogEntry(data=element, users=self._users, guild=self.guild)) class GuildIterator(_AsyncIterator['Guild']): """Iterator for receiving the client's guilds. The guilds endpoint has the same two behaviours as described in :class:`HistoryIterator`: If ``before`` is specified, the guilds endpoint returns the ``limit`` newest guilds before ``before``, sorted with newest first. For filling over 100 guilds, update the ``before`` parameter to the oldest guild received. Guilds will be returned in order by time. If `after` is specified, it returns the ``limit`` oldest guilds after ``after``, sorted with newest first. For filling over 100 guilds, update the ``after`` parameter to the newest guild received, If guilds are not reversed, they will be out of order (99-0, 199-100, so on) Not that if both ``before`` and ``after`` are specified, ``before`` is ignored by the guilds endpoint. Parameters ----------- bot: :class:`discord.Client` The client to retrieve the guilds from. limit: :class:`int` Maximum number of guilds to retrieve. before: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] Object before which all guilds must be. after: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] Object after which all guilds must be. """ def __init__(self, bot, limit, before=None, after=None): if isinstance(before, datetime.datetime): before = Object(id=time_snowflake(before, high=False)) if isinstance(after, datetime.datetime): after = Object(id=time_snowflake(after, high=True)) self.bot = bot self.limit = limit self.before = before self.after = after self._filter = None self.state = self.bot._connection self.get_guilds = self.bot.http.get_guilds self.guilds = asyncio.Queue() if self.before and self.after: self._retrieve_guilds = self._retrieve_guilds_before_strategy # type: ignore self._filter = lambda m: int(m['id']) > self.after.id elif self.after: self._retrieve_guilds = self._retrieve_guilds_after_strategy # type: ignore else: self._retrieve_guilds = self._retrieve_guilds_before_strategy # type: ignore async def next(self) -> Guild: if self.guilds.empty(): await self.fill_guilds() try: return self.guilds.get_nowait() except asyncio.QueueEmpty: raise NoMoreItems() def _get_retrieve(self): l = self.limit if l is None or l > 100: r = 100 else: r = l self.retrieve = r return r > 0 def create_guild(self, data): from .guild import Guild return Guild(state=self.state, data=data) async def fill_guilds(self): if self._get_retrieve(): data = await self._retrieve_guilds(self.retrieve) if self.limit is None or len(data) < 100: self.limit = 0 if self._filter: data = filter(self._filter, data) for element in data: await self.guilds.put(self.create_guild(element)) async def _retrieve_guilds(self, retrieve) -> List[Guild]: """Retrieve guilds and update next parameters.""" raise NotImplementedError async def _retrieve_guilds_before_strategy(self, retrieve): """Retrieve guilds using before parameter.""" before = self.before.id if self.before else None data: List[GuildPayload] = await self.get_guilds(retrieve, before=before) if len(data): if self.limit is not None: self.limit -= retrieve self.before = Object(id=int(data[-1]['id'])) return data async def _retrieve_guilds_after_strategy(self, retrieve): """Retrieve guilds using after parameter.""" after = self.after.id if self.after else None data: List[GuildPayload] = await self.get_guilds(retrieve, after=after) if len(data): if self.limit is not None: self.limit -= retrieve self.after = Object(id=int(data[0]['id'])) return data class MemberIterator(_AsyncIterator['Member']): def __init__(self, guild, limit=1000, after=None): if isinstance(after, datetime.datetime): after = Object(id=time_snowflake(after, high=True)) self.guild = guild self.limit = limit self.after = after or OLDEST_OBJECT self.state = self.guild._state self.get_members = self.state.http.get_members self.members = asyncio.Queue() async def next(self) -> Member: if self.members.empty(): await self.fill_members() try: return self.members.get_nowait() except asyncio.QueueEmpty: raise NoMoreItems() def _get_retrieve(self): l = self.limit if l is None or l > 1000: r = 1000 else: r = l self.retrieve = r return r > 0 async def fill_members(self): if self._get_retrieve(): after = self.after.id if self.after else None data = await self.get_members(self.guild.id, self.retrieve, after) if not data: # no data, terminate return if len(data) < 1000: self.limit = 0 # terminate loop self.after = Object(id=int(data[-1]['user']['id'])) for element in reversed(data): await self.members.put(self.create_member(element)) def create_member(self, data): from .member import Member return Member(data=data, guild=self.guild, state=self.state) class ArchivedThreadIterator(_AsyncIterator['Thread']): def __init__( self, channel_id: int, guild: Guild, limit: Optional[int], joined: bool, private: bool, before: Optional[Union[Snowflake, datetime.datetime]] = None, ): self.channel_id = channel_id self.guild = guild self.limit = limit self.joined = joined self.private = private self.http = guild._state.http if joined and not private: raise ValueError('Cannot iterate over joined public archived threads') self.before: Optional[str] if before is None: self.before = None elif isinstance(before, datetime.datetime): if joined: self.before = str(time_snowflake(before, high=False)) else: self.before = before.isoformat() else: if joined: self.before = str(before.id) else: self.before = snowflake_time(before.id).isoformat() self.update_before: Callable[[ThreadPayload], str] = self.get_archive_timestamp if joined: self.endpoint = self.http.get_joined_private_archived_threads self.update_before = self.get_thread_id elif private: self.endpoint = self.http.get_private_archived_threads else: self.endpoint = self.http.get_public_archived_threads self.queue: asyncio.Queue[Thread] = asyncio.Queue() self.has_more: bool = True async def next(self) -> Thread: if self.queue.empty(): await self.fill_queue() try: return self.queue.get_nowait() except asyncio.QueueEmpty: raise NoMoreItems() @staticmethod def get_archive_timestamp(data: ThreadPayload) -> str: return data['thread_metadata']['archive_timestamp'] @staticmethod def get_thread_id(data: ThreadPayload) -> str: return data['id'] # type: ignore async def fill_queue(self) -> None: if not self.has_more: raise NoMoreItems() limit = 50 if self.limit is None else max(self.limit, 50) data = await self.endpoint(self.channel_id, before=self.before, limit=limit) # This stuff is obviously WIP because 'members' is always empty threads: List[ThreadPayload] = data.get('threads', []) for d in reversed(threads): self.queue.put_nowait(self.create_thread(d)) self.has_more = data.get('has_more', False) if self.limit is not None: self.limit -= len(threads) if self.limit <= 0: self.has_more = False if self.has_more: self.before = self.update_before(threads[-1]) def create_thread(self, data: ThreadPayload) -> Thread: from .threads import Thread return Thread(guild=self.guild, state=self.guild._state, data=data)
34.746684
118
0.608802
from __future__ import annotations import asyncio import datetime from typing import Awaitable, TYPE_CHECKING, TypeVar, Optional, Any, Callable, Union, List, AsyncIterator from .errors import NoMoreItems from .utils import snowflake_time, time_snowflake, maybe_coroutine from .object import Object from .audit_logs import AuditLogEntry __all__ = ( 'ReactionIterator', 'HistoryIterator', 'AuditLogIterator', 'GuildIterator', 'MemberIterator', ) if TYPE_CHECKING: from .types.audit_log import ( AuditLog as AuditLogPayload, ) from .types.guild import ( Guild as GuildPayload, ) from .types.message import ( Message as MessagePayload, ) from .types.user import ( PartialUser as PartialUserPayload, ) from .types.threads import ( Thread as ThreadPayload, ) from .member import Member from .user import User from .message import Message from .audit_logs import AuditLogEntry from .guild import Guild from .threads import Thread from .abc import Snowflake T = TypeVar('T') OT = TypeVar('OT') _Func = Callable[[T], Union[OT, Awaitable[OT]]] OLDEST_OBJECT = Object(id=0) class _AsyncIterator(AsyncIterator[T]): __slots__ = () async def next(self) -> T: raise NotImplementedError def get(self, **attrs: Any) -> Awaitable[Optional[T]]: def predicate(elem: T): for attr, val in attrs.items(): nested = attr.split('__') obj = elem for attribute in nested: obj = getattr(obj, attribute) if obj != val: return False return True return self.find(predicate) async def find(self, predicate: _Func[T, bool]) -> Optional[T]: while True: try: elem = await self.next() except NoMoreItems: return None ret = await maybe_coroutine(predicate, elem) if ret: return elem def chunk(self, max_size: int) -> _ChunkedAsyncIterator[T]: if max_size <= 0: raise ValueError('async iterator chunk sizes must be greater than 0.') return _ChunkedAsyncIterator(self, max_size) def map(self, func: _Func[T, OT]) -> _MappedAsyncIterator[OT]: return _MappedAsyncIterator(self, func) def filter(self, predicate: _Func[T, bool]) -> _FilteredAsyncIterator[T]: return _FilteredAsyncIterator(self, predicate) async def flatten(self) -> List[T]: return [element async for element in self] async def __anext__(self) -> T: try: return await self.next() except NoMoreItems: raise StopAsyncIteration() def _identity(x): return x class _ChunkedAsyncIterator(_AsyncIterator[List[T]]): def __init__(self, iterator, max_size): self.iterator = iterator self.max_size = max_size async def next(self) -> List[T]: ret: List[T] = [] n = 0 while n < self.max_size: try: item = await self.iterator.next() except NoMoreItems: if ret: return ret raise else: ret.append(item) n += 1 return ret class _MappedAsyncIterator(_AsyncIterator[T]): def __init__(self, iterator, func): self.iterator = iterator self.func = func async def next(self) -> T: item = await self.iterator.next() return await maybe_coroutine(self.func, item) class _FilteredAsyncIterator(_AsyncIterator[T]): def __init__(self, iterator, predicate): self.iterator = iterator if predicate is None: predicate = _identity self.predicate = predicate async def next(self) -> T: getter = self.iterator.next pred = self.predicate while True: item = await getter() ret = await maybe_coroutine(pred, item) if ret: return item class ReactionIterator(_AsyncIterator[Union['User', 'Member']]): def __init__(self, message, emoji, limit=100, after=None): self.message = message self.limit = limit self.after = after state = message._state self.getter = state.http.get_reaction_users self.state = state self.emoji = emoji self.guild = message.guild self.channel_id = message.channel.id self.users = asyncio.Queue() async def next(self) -> Union[User, Member]: if self.users.empty(): await self.fill_users() try: return self.users.get_nowait() except asyncio.QueueEmpty: raise NoMoreItems() async def fill_users(self): from .user import User if self.limit > 0: retrieve = self.limit if self.limit <= 100 else 100 after = self.after.id if self.after else None data: List[PartialUserPayload] = await self.getter( self.channel_id, self.message.id, self.emoji, retrieve, after=after ) if data: self.limit -= retrieve self.after = Object(id=int(data[-1]['id'])) if self.guild is None or isinstance(self.guild, Object): for element in reversed(data): await self.users.put(User(state=self.state, data=element)) else: for element in reversed(data): member_id = int(element['id']) member = self.guild.get_member(member_id) if member is not None: await self.users.put(member) else: await self.users.put(User(state=self.state, data=element)) class HistoryIterator(_AsyncIterator['Message']): def __init__(self, messageable, limit, before=None, after=None, around=None, oldest_first=None): if isinstance(before, datetime.datetime): before = Object(id=time_snowflake(before, high=False)) if isinstance(after, datetime.datetime): after = Object(id=time_snowflake(after, high=True)) if isinstance(around, datetime.datetime): around = Object(id=time_snowflake(around)) if oldest_first is None: self.reverse = after is not None else: self.reverse = oldest_first self.messageable = messageable self.limit = limit self.before = before self.after = after or OLDEST_OBJECT self.around = around self._filter = None self.state = self.messageable._state self.logs_from = self.state.http.logs_from self.messages = asyncio.Queue() if self.around: if self.limit is None: raise ValueError('history does not support around with limit=None') if self.limit > 101: raise ValueError("history max limit 101 when specifying around parameter") elif self.limit == 101: self.limit = 100 self._retrieve_messages = self._retrieve_messages_around_strategy if self.before and self.after: self._filter = lambda m: self.after.id < int(m['id']) < self.before.id elif self.before: self._filter = lambda m: int(m['id']) < self.before.id elif self.after: self._filter = lambda m: self.after.id < int(m['id']) else: if self.reverse: self._retrieve_messages = self._retrieve_messages_after_strategy if self.before: self._filter = lambda m: int(m['id']) < self.before.id else: self._retrieve_messages = self._retrieve_messages_before_strategy if self.after and self.after != OLDEST_OBJECT: self._filter = lambda m: int(m['id']) > self.after.id async def next(self) -> Message: if self.messages.empty(): await self.fill_messages() try: return self.messages.get_nowait() except asyncio.QueueEmpty: raise NoMoreItems() def _get_retrieve(self): l = self.limit if l is None or l > 100: r = 100 else: r = l self.retrieve = r return r > 0 async def fill_messages(self): if not hasattr(self, 'channel'): channel = await self.messageable._get_channel() self.channel = channel if self._get_retrieve(): data = await self._retrieve_messages(self.retrieve) if len(data) < 100: self.limit = 0 if self.reverse: data = reversed(data) if self._filter: data = filter(self._filter, data) channel = self.channel for element in data: await self.messages.put(self.state.create_message(channel=channel, data=element)) async def _retrieve_messages(self, retrieve) -> List[Message]: raise NotImplementedError async def _retrieve_messages_before_strategy(self, retrieve): before = self.before.id if self.before else None data: List[MessagePayload] = await self.logs_from(self.channel.id, retrieve, before=before) if len(data): if self.limit is not None: self.limit -= retrieve self.before = Object(id=int(data[-1]['id'])) return data async def _retrieve_messages_after_strategy(self, retrieve): after = self.after.id if self.after else None data: List[MessagePayload] = await self.logs_from(self.channel.id, retrieve, after=after) if len(data): if self.limit is not None: self.limit -= retrieve self.after = Object(id=int(data[0]['id'])) return data async def _retrieve_messages_around_strategy(self, retrieve): if self.around: around = self.around.id if self.around else None data: List[MessagePayload] = await self.logs_from(self.channel.id, retrieve, around=around) self.around = None return data return [] class AuditLogIterator(_AsyncIterator['AuditLogEntry']): def __init__(self, guild, limit=None, before=None, after=None, oldest_first=None, user_id=None, action_type=None): if isinstance(before, datetime.datetime): before = Object(id=time_snowflake(before, high=False)) if isinstance(after, datetime.datetime): after = Object(id=time_snowflake(after, high=True)) if oldest_first is None: self.reverse = after is not None else: self.reverse = oldest_first self.guild = guild self.loop = guild._state.loop self.request = guild._state.http.get_audit_logs self.limit = limit self.before = before self.user_id = user_id self.action_type = action_type self.after = OLDEST_OBJECT self._users = {} self._state = guild._state self._filter = None self.entries = asyncio.Queue() if self.reverse: self._strategy = self._after_strategy if self.before: self._filter = lambda m: int(m['id']) < self.before.id else: self._strategy = self._before_strategy if self.after and self.after != OLDEST_OBJECT: self._filter = lambda m: int(m['id']) > self.after.id async def _before_strategy(self, retrieve): before = self.before.id if self.before else None data: AuditLogPayload = await self.request( self.guild.id, limit=retrieve, user_id=self.user_id, action_type=self.action_type, before=before ) entries = data.get('audit_log_entries', []) if len(data) and entries: if self.limit is not None: self.limit -= retrieve self.before = Object(id=int(entries[-1]['id'])) return data.get('users', []), entries async def _after_strategy(self, retrieve): after = self.after.id if self.after else None data: AuditLogPayload = await self.request( self.guild.id, limit=retrieve, user_id=self.user_id, action_type=self.action_type, after=after ) entries = data.get('audit_log_entries', []) if len(data) and entries: if self.limit is not None: self.limit -= retrieve self.after = Object(id=int(entries[0]['id'])) return data.get('users', []), entries async def next(self) -> AuditLogEntry: if self.entries.empty(): await self._fill() try: return self.entries.get_nowait() except asyncio.QueueEmpty: raise NoMoreItems() def _get_retrieve(self): l = self.limit if l is None or l > 100: r = 100 else: r = l self.retrieve = r return r > 0 async def _fill(self): from .user import User if self._get_retrieve(): users, data = await self._strategy(self.retrieve) if len(data) < 100: self.limit = 0 if self.reverse: data = reversed(data) if self._filter: data = filter(self._filter, data) for user in users: u = User(data=user, state=self._state) self._users[u.id] = u for element in data: if element['action_type'] is None: continue await self.entries.put(AuditLogEntry(data=element, users=self._users, guild=self.guild)) class GuildIterator(_AsyncIterator['Guild']): def __init__(self, bot, limit, before=None, after=None): if isinstance(before, datetime.datetime): before = Object(id=time_snowflake(before, high=False)) if isinstance(after, datetime.datetime): after = Object(id=time_snowflake(after, high=True)) self.bot = bot self.limit = limit self.before = before self.after = after self._filter = None self.state = self.bot._connection self.get_guilds = self.bot.http.get_guilds self.guilds = asyncio.Queue() if self.before and self.after: self._retrieve_guilds = self._retrieve_guilds_before_strategy self._filter = lambda m: int(m['id']) > self.after.id elif self.after: self._retrieve_guilds = self._retrieve_guilds_after_strategy else: self._retrieve_guilds = self._retrieve_guilds_before_strategy async def next(self) -> Guild: if self.guilds.empty(): await self.fill_guilds() try: return self.guilds.get_nowait() except asyncio.QueueEmpty: raise NoMoreItems() def _get_retrieve(self): l = self.limit if l is None or l > 100: r = 100 else: r = l self.retrieve = r return r > 0 def create_guild(self, data): from .guild import Guild return Guild(state=self.state, data=data) async def fill_guilds(self): if self._get_retrieve(): data = await self._retrieve_guilds(self.retrieve) if self.limit is None or len(data) < 100: self.limit = 0 if self._filter: data = filter(self._filter, data) for element in data: await self.guilds.put(self.create_guild(element)) async def _retrieve_guilds(self, retrieve) -> List[Guild]: raise NotImplementedError async def _retrieve_guilds_before_strategy(self, retrieve): before = self.before.id if self.before else None data: List[GuildPayload] = await self.get_guilds(retrieve, before=before) if len(data): if self.limit is not None: self.limit -= retrieve self.before = Object(id=int(data[-1]['id'])) return data async def _retrieve_guilds_after_strategy(self, retrieve): after = self.after.id if self.after else None data: List[GuildPayload] = await self.get_guilds(retrieve, after=after) if len(data): if self.limit is not None: self.limit -= retrieve self.after = Object(id=int(data[0]['id'])) return data class MemberIterator(_AsyncIterator['Member']): def __init__(self, guild, limit=1000, after=None): if isinstance(after, datetime.datetime): after = Object(id=time_snowflake(after, high=True)) self.guild = guild self.limit = limit self.after = after or OLDEST_OBJECT self.state = self.guild._state self.get_members = self.state.http.get_members self.members = asyncio.Queue() async def next(self) -> Member: if self.members.empty(): await self.fill_members() try: return self.members.get_nowait() except asyncio.QueueEmpty: raise NoMoreItems() def _get_retrieve(self): l = self.limit if l is None or l > 1000: r = 1000 else: r = l self.retrieve = r return r > 0 async def fill_members(self): if self._get_retrieve(): after = self.after.id if self.after else None data = await self.get_members(self.guild.id, self.retrieve, after) if not data: return if len(data) < 1000: self.limit = 0 self.after = Object(id=int(data[-1]['user']['id'])) for element in reversed(data): await self.members.put(self.create_member(element)) def create_member(self, data): from .member import Member return Member(data=data, guild=self.guild, state=self.state) class ArchivedThreadIterator(_AsyncIterator['Thread']): def __init__( self, channel_id: int, guild: Guild, limit: Optional[int], joined: bool, private: bool, before: Optional[Union[Snowflake, datetime.datetime]] = None, ): self.channel_id = channel_id self.guild = guild self.limit = limit self.joined = joined self.private = private self.http = guild._state.http if joined and not private: raise ValueError('Cannot iterate over joined public archived threads') self.before: Optional[str] if before is None: self.before = None elif isinstance(before, datetime.datetime): if joined: self.before = str(time_snowflake(before, high=False)) else: self.before = before.isoformat() else: if joined: self.before = str(before.id) else: self.before = snowflake_time(before.id).isoformat() self.update_before: Callable[[ThreadPayload], str] = self.get_archive_timestamp if joined: self.endpoint = self.http.get_joined_private_archived_threads self.update_before = self.get_thread_id elif private: self.endpoint = self.http.get_private_archived_threads else: self.endpoint = self.http.get_public_archived_threads self.queue: asyncio.Queue[Thread] = asyncio.Queue() self.has_more: bool = True async def next(self) -> Thread: if self.queue.empty(): await self.fill_queue() try: return self.queue.get_nowait() except asyncio.QueueEmpty: raise NoMoreItems() @staticmethod def get_archive_timestamp(data: ThreadPayload) -> str: return data['thread_metadata']['archive_timestamp'] @staticmethod def get_thread_id(data: ThreadPayload) -> str: return data['id'] async def fill_queue(self) -> None: if not self.has_more: raise NoMoreItems() limit = 50 if self.limit is None else max(self.limit, 50) data = await self.endpoint(self.channel_id, before=self.before, limit=limit) threads: List[ThreadPayload] = data.get('threads', []) for d in reversed(threads): self.queue.put_nowait(self.create_thread(d)) self.has_more = data.get('has_more', False) if self.limit is not None: self.limit -= len(threads) if self.limit <= 0: self.has_more = False if self.has_more: self.before = self.update_before(threads[-1]) def create_thread(self, data: ThreadPayload) -> Thread: from .threads import Thread return Thread(guild=self.guild, state=self.guild._state, data=data)
true
true