idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
234,400
def _read_dict ( self , dictionary ) : values = dictionary self . _did = values [ 'id' ] self . _created = values . get ( 'created' , None ) if 'publicKey' in values : self . _public_keys = [ ] for value in values [ 'publicKey' ] : if isinstance ( value , str ) : value = json . loads ( value ) self . _public_keys . append ( DDO . create_public_key_from_json ( value ) ) if 'authentication' in values : self . _authentications = [ ] for value in values [ 'authentication' ] : if isinstance ( value , str ) : value = json . loads ( value ) self . _authentications . append ( DDO . create_authentication_from_json ( value ) ) if 'service' in values : self . _services = [ ] for value in values [ 'service' ] : if isinstance ( value , str ) : value = json . loads ( value ) service = Service . from_json ( value ) service . set_did ( self . _did ) self . _services . append ( service ) if 'proof' in values : self . _proof = values [ 'proof' ]
Import a JSON dict into this DDO .
266
9
234,401
def get_public_key ( self , key_id , is_search_embedded = False ) : if isinstance ( key_id , int ) : return self . _public_keys [ key_id ] for item in self . _public_keys : if item . get_id ( ) == key_id : return item if is_search_embedded : for authentication in self . _authentications : if authentication . get_public_key_id ( ) == key_id : return authentication . get_public_key ( ) return None
Key_id can be a string or int . If int then the index in the list of keys .
117
21
234,402
def _get_public_key_count ( self ) : index = len ( self . _public_keys ) for authentication in self . _authentications : if authentication . is_public_key ( ) : index += 1 return index
Return the count of public keys in the list and embedded .
49
12
234,403
def _get_authentication_from_public_key_id ( self , key_id ) : for authentication in self . _authentications : if authentication . is_key_id ( key_id ) : return authentication return None
Return the authentication based on it s id .
49
9
234,404
def get_service ( self , service_type = None ) : for service in self . _services : if service . type == service_type and service_type : return service return None
Return a service using .
39
5
234,405
def find_service_by_id ( self , service_id ) : service_id_key = 'serviceDefinitionId' service_id = str ( service_id ) for service in self . _services : if service_id_key in service . values and str ( service . values [ service_id_key ] ) == service_id : return service try : # If service_id is int or can be converted to int then we couldn't find it int ( service_id ) return None except ValueError : pass # try to find by type return self . find_service_by_type ( service_id )
Get service for a given service_id .
131
9
234,406
def find_service_by_type ( self , service_type ) : for service in self . _services : if service_type == service . type : return service return None
Get service for a given service type .
37
8
234,407
def create_public_key_from_json ( values ) : # currently we only support RSA public keys _id = values . get ( 'id' ) if not _id : # Make it more forgiving for now. _id = '' # raise ValueError('publicKey definition is missing the "id" value.') if values . get ( 'type' ) == PUBLIC_KEY_TYPE_RSA : public_key = PublicKeyRSA ( _id , owner = values . get ( 'owner' ) ) else : public_key = PublicKeyBase ( _id , owner = values . get ( 'owner' ) , type = 'EthereumECDSAKey' ) public_key . set_key_value ( values ) return public_key
Create a public key object based on the values from the JSON record .
159
14
234,408
def create_authentication_from_json ( values ) : key_id = values . get ( 'publicKey' ) authentication_type = values . get ( 'type' ) if not key_id : raise ValueError ( f'Invalid authentication definition, "publicKey" is missing: {values}' ) authentication = { 'type' : authentication_type , 'publicKey' : key_id } return authentication
Create authentitaciton object from a JSON string .
88
11
234,409
def generate_checksum ( did , metadata ) : files_checksum = '' for file in metadata [ 'base' ] [ 'files' ] : if 'checksum' in file : files_checksum = files_checksum + file [ 'checksum' ] return hashlib . sha3_256 ( ( files_checksum + metadata [ 'base' ] [ 'name' ] + metadata [ 'base' ] [ 'author' ] + metadata [ 'base' ] [ 'license' ] + did ) . encode ( 'UTF-8' ) ) . hexdigest ( )
Generation of the hash for integrity checksum .
127
10
234,410
def register ( self , did , checksum , url , account , providers = None ) : did_source_id = did_to_id_bytes ( did ) if not did_source_id : raise ValueError ( f'{did} must be a valid DID to register' ) if not urlparse ( url ) : raise ValueError ( f'Invalid URL {url} to register for DID {did}' ) if checksum is None : checksum = Web3Provider . get_web3 ( ) . toBytes ( 0 ) if not isinstance ( checksum , bytes ) : raise ValueError ( f'Invalid checksum value {checksum}, must be bytes or string' ) if account is None : raise ValueError ( 'You must provide an account to use to register a DID' ) transaction = self . _register_attribute ( did_source_id , checksum , url , account , providers or [ ] ) receipt = self . get_tx_receipt ( transaction ) return receipt and receipt . status == 1
Register or update a DID on the block chain using the DIDRegistry smart contract .
218
17
234,411
def _register_attribute ( self , did , checksum , value , account , providers ) : assert isinstance ( providers , list ) , '' return self . send_transaction ( 'registerAttribute' , ( did , checksum , providers , value ) , transact = { 'from' : account . address , 'passphrase' : account . password } )
Register an DID attribute as an event on the block chain .
75
12
234,412
def remove_provider ( self , did , provider_address , account ) : tx_hash = self . send_transaction ( 'removeDIDProvider' , ( did , provider_address ) , transact = { 'from' : account . address , 'passphrase' : account . password } ) return self . get_tx_receipt ( tx_hash )
Remove a provider
79
3
234,413
def get_did_providers ( self , did ) : register_values = self . contract_concise . getDIDRegister ( did ) if register_values and len ( register_values ) == 5 : return DIDRegisterValues ( * register_values ) . providers return None
Return the list providers registered on - chain for the given did .
59
13
234,414
def get_owner_asset_ids ( self , address ) : block_filter = self . _get_event_filter ( owner = address ) log_items = block_filter . get_all_entries ( max_tries = 5 ) did_list = [ ] for log_i in log_items : did_list . append ( id_to_did ( log_i . args [ '_did' ] ) ) return did_list
Get the list of assets owned by an address owner .
98
11
234,415
def set_encode_key_value ( self , value , store_type = PUBLIC_KEY_STORE_TYPE_BASE64 ) : if store_type == PUBLIC_KEY_STORE_TYPE_PEM : PublicKeyBase . set_encode_key_value ( self , value . exportKey ( 'PEM' ) . decode ( ) , store_type ) else : PublicKeyBase . set_encode_key_value ( self , value . exportKey ( 'DER' ) , store_type )
Set the value based on the type of encoding supported by RSA .
114
13
234,416
def did_parse ( did ) : if not isinstance ( did , str ) : raise TypeError ( f'Expecting DID of string type, got {did} of {type(did)} type' ) match = re . match ( '^did:([a-z0-9]+):([a-zA-Z0-9-.]+)(.*)' , did ) if not match : raise ValueError ( f'DID {did} does not seem to be valid.' ) result = { 'method' : match . group ( 1 ) , 'id' : match . group ( 2 ) , } return result
Parse a DID into it s parts .
133
9
234,417
def id_to_did ( did_id , method = 'op' ) : if isinstance ( did_id , bytes ) : did_id = Web3 . toHex ( did_id ) # remove leading '0x' of a hex string if isinstance ( did_id , str ) : did_id = remove_0x_prefix ( did_id ) else : raise TypeError ( "did id must be a hex string or bytes" ) # test for zero address if Web3 . toBytes ( hexstr = did_id ) == b'' : did_id = '0' return f'did:{method}:{did_id}'
Return an Ocean DID from given a hex id .
142
10
234,418
def did_to_id_bytes ( did ) : if isinstance ( did , str ) : if re . match ( '^[0x]?[0-9A-Za-z]+$' , did ) : raise ValueError ( f'{did} must be a DID not a hex string' ) else : did_result = did_parse ( did ) if not did_result : raise ValueError ( f'{did} is not a valid did' ) if not did_result [ 'id' ] : raise ValueError ( f'{did} is not a valid ocean did' ) id_bytes = Web3 . toBytes ( hexstr = did_result [ 'id' ] ) elif isinstance ( did , bytes ) : id_bytes = did else : raise TypeError ( f'Unknown did format, expected str or bytes, got {did} of type {type(did)}' ) return id_bytes
Return an Ocean DID to it s correspondng hex id in bytes .
202
14
234,419
def get_template ( self , template_id ) : template = self . contract_concise . getTemplate ( template_id ) if template and len ( template ) == 4 : return AgreementTemplate ( * template ) return None
Get the template for a given template id .
47
9
234,420
def propose_template ( self , template_id , from_account ) : tx_hash = self . send_transaction ( 'proposeTemplate' , ( template_id , ) , transact = { 'from' : from_account . address , 'passphrase' : from_account . password } ) return self . get_tx_receipt ( tx_hash ) . status == 1
Propose a template .
84
5
234,421
def access_service_descriptor ( price , consume_endpoint , service_endpoint , timeout , template_id ) : return ( ServiceTypes . ASSET_ACCESS , { 'price' : price , 'consumeEndpoint' : consume_endpoint , 'serviceEndpoint' : service_endpoint , 'timeout' : timeout , 'templateId' : template_id } )
Access service descriptor .
85
4
234,422
def compute_service_descriptor ( price , consume_endpoint , service_endpoint , timeout ) : return ( ServiceTypes . CLOUD_COMPUTE , { 'price' : price , 'consumeEndpoint' : consume_endpoint , 'serviceEndpoint' : service_endpoint , 'timeout' : timeout } )
Compute service descriptor .
74
5
234,423
def build_services ( did , service_descriptors ) : services = [ ] sa_def_key = ServiceAgreement . SERVICE_DEFINITION_ID for i , service_desc in enumerate ( service_descriptors ) : service = ServiceFactory . build_service ( service_desc , did ) # set serviceDefinitionId for each service service . update_value ( sa_def_key , str ( i ) ) services . append ( service ) return services
Build a list of services .
100
6
234,424
def build_service ( service_descriptor , did ) : assert isinstance ( service_descriptor , tuple ) and len ( service_descriptor ) == 2 , 'Unknown service descriptor format.' service_type , kwargs = service_descriptor if service_type == ServiceTypes . METADATA : return ServiceFactory . build_metadata_service ( did , kwargs [ 'metadata' ] , kwargs [ 'serviceEndpoint' ] ) elif service_type == ServiceTypes . AUTHORIZATION : return ServiceFactory . build_authorization_service ( kwargs [ 'serviceEndpoint' ] ) elif service_type == ServiceTypes . ASSET_ACCESS : return ServiceFactory . build_access_service ( did , kwargs [ 'price' ] , kwargs [ 'consumeEndpoint' ] , kwargs [ 'serviceEndpoint' ] , kwargs [ 'timeout' ] , kwargs [ 'templateId' ] ) elif service_type == ServiceTypes . CLOUD_COMPUTE : return ServiceFactory . build_compute_service ( did , kwargs [ 'price' ] , kwargs [ 'consumeEndpoint' ] , kwargs [ 'serviceEndpoint' ] , kwargs [ 'timeout' ] ) raise ValueError ( f'Unknown service type {service_type}' )
Build a service .
301
4
234,425
def build_metadata_service ( did , metadata , service_endpoint ) : return Service ( service_endpoint , ServiceTypes . METADATA , values = { 'metadata' : metadata } , did = did )
Build a metadata service .
46
5
234,426
def build_access_service ( did , price , consume_endpoint , service_endpoint , timeout , template_id ) : # TODO fill all the possible mappings param_map = { '_documentId' : did_to_id ( did ) , '_amount' : price , '_rewardAddress' : Keeper . get_instance ( ) . escrow_reward_condition . address , } sla_template_path = get_sla_template_path ( ) sla_template = ServiceAgreementTemplate . from_json_file ( sla_template_path ) sla_template . template_id = template_id conditions = sla_template . conditions [ : ] for cond in conditions : for param in cond . parameters : param . value = param_map . get ( param . name , '' ) if cond . timeout > 0 : cond . timeout = timeout sla_template . set_conditions ( conditions ) sa = ServiceAgreement ( 1 , sla_template , consume_endpoint , service_endpoint , ServiceTypes . ASSET_ACCESS ) sa . set_did ( did ) return sa
Build the access service .
247
5
234,427
def record_service_agreement ( storage_path , service_agreement_id , did , service_definition_id , price , files , start_time , status = 'pending' ) : conn = sqlite3 . connect ( storage_path ) try : cursor = conn . cursor ( ) cursor . execute ( '''CREATE TABLE IF NOT EXISTS service_agreements (id VARCHAR PRIMARY KEY, did VARCHAR, service_definition_id INTEGER, price INTEGER, files VARCHAR, start_time INTEGER, status VARCHAR(10));''' ) cursor . execute ( 'INSERT OR REPLACE INTO service_agreements VALUES (?,?,?,?,?,?,?)' , [ service_agreement_id , did , service_definition_id , price , files , start_time , status ] , ) conn . commit ( ) finally : conn . close ( )
Records the given pending service agreement .
199
8
234,428
def update_service_agreement_status ( storage_path , service_agreement_id , status = 'pending' ) : conn = sqlite3 . connect ( storage_path ) try : cursor = conn . cursor ( ) cursor . execute ( 'UPDATE service_agreements SET status=? WHERE id=?' , ( status , service_agreement_id ) , ) conn . commit ( ) finally : conn . close ( )
Update the service agreement status .
93
6
234,429
def setup_logging ( default_path = 'logging.yaml' , default_level = logging . INFO , env_key = 'LOG_CFG' ) : path = default_path value = os . getenv ( env_key , None ) if value : path = value if os . path . exists ( path ) : with open ( path , 'rt' ) as file : try : config = yaml . safe_load ( file . read ( ) ) logging . config . dictConfig ( config ) coloredlogs . install ( ) logging . info ( f'Logging configuration loaded from file: {path}' ) except Exception as ex : print ( ex ) print ( 'Error in Logging Configuration. Using default configs' ) logging . basicConfig ( level = default_level ) coloredlogs . install ( level = default_level ) else : logging . basicConfig ( level = default_level ) coloredlogs . install ( level = default_level ) print ( 'Using default logging settings.' )
Logging setup .
216
4
234,430
def encrypt ( self , document_id , content , account ) : return self . _secret_store ( account ) . encrypt_document ( document_id , content )
Encrypt string data using the DID as an secret store id if secret store is enabled then return the result from secret store encryption
35
25
234,431
def get_resolve_url ( self , did_bytes ) : data = self . _did_registry . get_registered_attribute ( did_bytes ) if not ( data and data . get ( 'value' ) ) : return None return data [ 'value' ]
Return a did value and value type from the block chain event record using did .
59
16
234,432
def get_instance ( cls , dependencies = None ) : assert cls is not ContractBase , 'ContractBase is not meant to be used directly.' assert cls . CONTRACT_NAME , 'CONTRACT_NAME must be set to a valid keeper contract name.' return cls ( cls . CONTRACT_NAME , dependencies )
Return an instance for a contract name .
71
8
234,433
def get_tx_receipt ( tx_hash ) : try : Web3Provider . get_web3 ( ) . eth . waitForTransactionReceipt ( tx_hash , timeout = 20 ) except Timeout : logger . info ( 'Waiting for transaction receipt timed out.' ) return return Web3Provider . get_web3 ( ) . eth . getTransactionReceipt ( tx_hash )
Get the receipt of a tx .
87
7
234,434
def subscribe_to_event ( self , event_name , timeout , event_filter , callback = False , timeout_callback = None , args = None , wait = False ) : from squid_py . keeper . event_listener import EventListener return EventListener ( self . CONTRACT_NAME , event_name , args , filters = event_filter ) . listen_once ( callback , timeout_callback = timeout_callback , timeout = timeout , blocking = wait )
Create a listener for the event choose .
98
8
234,435
def refund_reward ( event , agreement_id , did , service_agreement , price , consumer_account , publisher_address , condition_ids ) : logger . debug ( f"trigger refund after event {event}." ) access_id , lock_id = condition_ids [ : 2 ] name_to_parameter = { param . name : param for param in service_agreement . condition_by_name [ 'escrowReward' ] . parameters } document_id = add_0x_prefix ( name_to_parameter [ '_documentId' ] . value ) asset_id = add_0x_prefix ( did_to_id ( did ) ) assert document_id == asset_id , f'document_id {document_id} <=> asset_id {asset_id} mismatch.' assert price == service_agreement . get_price ( ) , 'price mismatch.' # logger.info(f'About to do grantAccess: account {account.address}, # saId {service_agreement_id}, ' # f'documentKeyId {document_key_id}') try : tx_hash = Keeper . get_instance ( ) . escrow_reward_condition . fulfill ( agreement_id , price , publisher_address , consumer_account . address , lock_id , access_id , consumer_account ) process_tx_receipt ( tx_hash , Keeper . get_instance ( ) . escrow_reward_condition . FULFILLED_EVENT , 'EscrowReward.Fulfilled' ) except Exception as e : # logger.error(f'Error when doing escrow_reward_condition.fulfills: {e}') raise e
Refund the reward to the publisher address .
374
9
234,436
def consume_asset ( event , agreement_id , did , service_agreement , consumer_account , consume_callback ) : logger . debug ( f"consuming asset after event {event}." ) if consume_callback : config = ConfigProvider . get_config ( ) secret_store = SecretStoreProvider . get_secret_store ( config . secret_store_url , config . parity_url , consumer_account ) brizo = BrizoProvider . get_brizo ( ) consume_callback ( agreement_id , service_agreement . service_definition_id , DIDResolver ( Keeper . get_instance ( ) . did_registry ) . resolve ( did ) , consumer_account , ConfigProvider . get_config ( ) . downloads_path , brizo , secret_store )
Consumption of an asset after get the event call .
170
11
234,437
def verify_contracts ( ) : artifacts_path = ConfigProvider . get_config ( ) . keeper_path logger . info ( f'Keeper contract artifacts (JSON abi files) at: {artifacts_path}' ) if os . environ . get ( 'KEEPER_NETWORK_NAME' ) : logger . warning ( f'The `KEEPER_NETWORK_NAME` env var is set to ' f'{os.environ.get("KEEPER_NETWORK_NAME")}. ' f'This enables the user to override the method of how the network name ' f'is inferred from network id.' ) # try to find contract with this network name contract_name = Diagnostics . TEST_CONTRACT_NAME network_id = Keeper . get_network_id ( ) network_name = Keeper . get_network_name ( network_id ) logger . info ( f'Using keeper contracts from network {network_name}, ' f'network id is {network_id}' ) logger . info ( f'Looking for keeper contracts ending with ".{network_name}.json", ' f'e.g. "{contract_name}.{network_name}.json".' ) existing_contract_names = os . listdir ( artifacts_path ) try : ContractHandler . get ( contract_name ) except Exception as e : logger . error ( e ) logger . error ( f'Cannot find the keeper contracts. \n' f'Current network id is {network_id} and network name is {network_name}.' f'Expected to find contracts ending with ".{network_name}.json",' f' e.g. "{contract_name}.{network_name}.json"' ) raise OceanKeeperContractsNotFound ( f'Keeper contracts for keeper network {network_name} were not found ' f'in {artifacts_path}. \n' f'Found the following contracts: \n\t{existing_contract_names}' ) keeper = Keeper . get_instance ( ) contracts = [ keeper . dispenser , keeper . token , keeper . did_registry , keeper . agreement_manager , keeper . template_manager , keeper . condition_manager , keeper . access_secret_store_condition , keeper . sign_condition , keeper . lock_reward_condition , keeper . escrow_access_secretstore_template , keeper . escrow_reward_condition , keeper . hash_lock_condition ] addresses = '\n' . join ( [ f'\t{c.name}: {c.address}' for c in contracts ] ) logging . info ( 'Finished loading keeper contracts:\n' '%s' , addresses )
Verify that the contracts are deployed correctly in the network .
580
12
234,438
def create_access_service ( price , service_endpoint , consume_endpoint , timeout = None ) : timeout = timeout or 3600 # default to one hour timeout service = ServiceDescriptor . access_service_descriptor ( price , service_endpoint , consume_endpoint , timeout , '' ) return service
Publish an asset with an Access service according to the supplied attributes .
69
14
234,439
def lock_reward ( self , agreement_id , amount , account ) : return self . _keeper . lock_reward_condition . fulfill ( agreement_id , self . _keeper . escrow_reward_condition . address , amount , account )
Lock reward condition .
55
4
234,440
def grant_access ( self , agreement_id , did , grantee_address , account ) : return self . _keeper . access_secret_store_condition . fulfill ( agreement_id , add_0x_prefix ( did_to_id ( did ) ) , grantee_address , account )
Grant access condition .
65
4
234,441
def release_reward ( self , agreement_id , amount , account ) : agreement_values = self . _keeper . agreement_manager . get_agreement ( agreement_id ) consumer , provider = self . _keeper . escrow_access_secretstore_template . get_agreement_data ( agreement_id ) access_id , lock_id = agreement_values . condition_ids [ : 2 ] return self . _keeper . escrow_reward_condition . fulfill ( agreement_id , amount , provider , consumer , lock_id , access_id , account )
Release reward condition .
124
4
234,442
def refund_reward ( self , agreement_id , amount , account ) : return self . release_reward ( agreement_id , amount , account )
Refund reaward condition .
33
7
234,443
def from_json_file ( cls , path ) : with open ( path ) as jsf : template_json = json . load ( jsf ) return cls ( template_json = template_json )
Return a template from a json allocated in a path .
45
11
234,444
def parse_template_json ( self , template_json ) : assert template_json [ 'type' ] == self . DOCUMENT_TYPE , '' self . template_id = template_json [ 'templateId' ] self . name = template_json . get ( 'name' ) self . creator = template_json . get ( 'creator' ) self . template = template_json [ 'serviceAgreementTemplate' ]
Parse a template from a json .
91
8
234,445
def as_dictionary ( self ) : template = { 'contractName' : self . contract_name , 'events' : [ e . as_dictionary ( ) for e in self . agreement_events ] , 'fulfillmentOrder' : self . fulfillment_order , 'conditionDependency' : self . condition_dependency , 'conditions' : [ cond . as_dictionary ( ) for cond in self . conditions ] } return { # 'type': self.DOCUMENT_TYPE, 'name' : self . name , 'creator' : self . creator , 'serviceAgreementTemplate' : template }
Return the service agreement template as a dictionary .
134
9
234,446
def request ( self , account , amount ) : return self . _keeper . dispenser . request_tokens ( amount , account )
Request a number of tokens to be minted and transfered to account
29
14
234,447
def transfer ( self , receiver_address , amount , sender_account ) : self . _keeper . token . token_approve ( receiver_address , amount , sender_account ) self . _keeper . token . transfer ( receiver_address , amount , sender_account )
Transfer a number of tokens from sender_account to receiver_address
57
13
234,448
def list_assets ( self ) : response = self . requests_session . get ( self . _base_url ) . content if not response : return { } try : asset_list = json . loads ( response ) except TypeError : asset_list = None except ValueError : raise ValueError ( response . decode ( 'UTF-8' ) ) if not asset_list : return [ ] if 'ids' in asset_list : return asset_list [ 'ids' ] return [ ]
List all the assets registered in the aquarius instance .
104
11
234,449
def get_asset_ddo ( self , did ) : response = self . requests_session . get ( f'{self.url}/{did}' ) . content if not response : return { } try : parsed_response = json . loads ( response ) except TypeError : parsed_response = None except ValueError : raise ValueError ( response . decode ( 'UTF-8' ) ) if parsed_response is None : return { } return Asset ( dictionary = parsed_response )
Retrieve asset ddo for a given did .
105
10
234,450
def get_asset_metadata ( self , did ) : response = self . requests_session . get ( f'{self._base_url}/metadata/{did}' ) . content if not response : return { } try : parsed_response = json . loads ( response ) except TypeError : parsed_response = None except ValueError : raise ValueError ( response . decode ( 'UTF-8' ) ) if parsed_response is None : return { } return parsed_response [ 'metadata' ]
Retrieve asset metadata for a given did .
108
9
234,451
def list_assets_ddo ( self ) : return json . loads ( self . requests_session . get ( self . url ) . content )
List all the ddos registered in the aquarius instance .
31
12
234,452
def publish_asset_ddo ( self , ddo ) : try : asset_did = ddo . did response = self . requests_session . post ( self . url , data = ddo . as_text ( ) , headers = self . _headers ) except AttributeError : raise AttributeError ( 'DDO invalid. Review that all the required parameters are filled.' ) if response . status_code == 500 : raise ValueError ( f'This Asset ID already exists! \n\tHTTP Error message: \n\t\t{response.text}' ) elif response . status_code != 201 : raise Exception ( f'{response.status_code} ERROR Full error: \n{response.text}' ) elif response . status_code == 201 : response = json . loads ( response . content ) logger . debug ( f'Published asset DID {asset_did}' ) return response else : raise Exception ( f'Unhandled ERROR: status-code {response.status_code}, ' f'error message {response.text}' )
Register asset ddo in aquarius .
231
8
234,453
def update_asset_ddo ( self , did , ddo ) : response = self . requests_session . put ( f'{self.url}/{did}' , data = ddo . as_text ( ) , headers = self . _headers ) if response . status_code == 200 or response . status_code == 201 : return json . loads ( response . content ) else : raise Exception ( f'Unable to update DDO: {response.content}' )
Update the ddo of a did already registered .
105
10
234,454
def text_search ( self , text , sort = None , offset = 100 , page = 1 ) : assert page >= 1 , f'Invalid page value {page}. Required page >= 1.' payload = { "text" : text , "sort" : sort , "offset" : offset , "page" : page } response = self . requests_session . get ( f'{self.url}/query' , params = payload , headers = self . _headers ) if response . status_code == 200 : return self . _parse_search_response ( response . content ) else : raise Exception ( f'Unable to search for DDO: {response.content}' )
Search in aquarius using text query .
144
8
234,455
def query_search ( self , search_query , sort = None , offset = 100 , page = 1 ) : assert page >= 1 , f'Invalid page value {page}. Required page >= 1.' search_query [ 'sort' ] = sort search_query [ 'offset' ] = offset search_query [ 'page' ] = page response = self . requests_session . post ( f'{self.url}/query' , data = json . dumps ( search_query ) , headers = self . _headers ) if response . status_code == 200 : return self . _parse_search_response ( response . content ) else : raise Exception ( f'Unable to search for DDO: {response.content}' )
Search using a query .
156
5
234,456
def retire_asset_ddo ( self , did ) : response = self . requests_session . delete ( f'{self.url}/{did}' , headers = self . _headers ) if response . status_code == 200 : logging . debug ( f'Removed asset DID: {did} from metadata store' ) return response raise AquariusGenericError ( f'Unable to remove DID: {response}' )
Retire asset ddo of Aquarius .
92
9
234,457
def validate_metadata ( self , metadata ) : response = self . requests_session . post ( f'{self.url}/validate' , data = json . dumps ( metadata ) , headers = self . _headers ) if response . content == b'true\n' : return True else : logger . info ( self . _parse_search_response ( response . content ) ) return False
Validate that the metadata of your ddo is valid .
84
12
234,458
def get_sla_template_path ( service_type = ServiceTypes . ASSET_ACCESS ) : if service_type == ServiceTypes . ASSET_ACCESS : name = 'access_sla_template.json' elif service_type == ServiceTypes . CLOUD_COMPUTE : name = 'compute_sla_template.json' elif service_type == ServiceTypes . FITCHAIN_COMPUTE : name = 'fitchain_sla_template.json' else : raise ValueError ( f'Invalid/unsupported service agreement type {service_type}' ) return os . path . join ( os . path . sep , * os . path . realpath ( __file__ ) . split ( os . path . sep ) [ 1 : - 1 ] , name )
Get the template for a ServiceType .
176
8
234,459
def balance ( self , account ) : return Balance ( self . _keeper . get_ether_balance ( account . address ) , self . _keeper . token . get_token_balance ( account . address ) )
Return the balance a tuple with the eth and ocn balance .
45
13
234,460
def process_agreement_events_consumer ( publisher_address , agreement_id , did , service_agreement , price , consumer_account , condition_ids , consume_callback ) : conditions_dict = service_agreement . condition_by_name events_manager = EventsManager . get_instance ( Keeper . get_instance ( ) ) events_manager . watch_agreement_created_event ( agreement_id , lock_reward_condition . fulfillLockRewardCondition , None , ( agreement_id , price , consumer_account ) , EVENT_WAIT_TIMEOUT , ) if consume_callback : def _refund_callback ( _price , _publisher_address , _condition_ids ) : def do_refund ( _event , _agreement_id , _did , _service_agreement , _consumer_account , * _ ) : escrow_reward_condition . refund_reward ( _event , _agreement_id , _did , _service_agreement , _price , _consumer_account , _publisher_address , _condition_ids ) return do_refund events_manager . watch_access_event ( agreement_id , escrow_reward_condition . consume_asset , _refund_callback ( price , publisher_address , condition_ids ) , ( agreement_id , did , service_agreement , consumer_account , consume_callback ) , conditions_dict [ 'accessSecretStore' ] . timeout )
Process the agreement events during the register of the service agreement for the consumer side .
318
16
234,461
def process_agreement_events_publisher ( publisher_account , agreement_id , did , service_agreement , price , consumer_address , condition_ids ) : conditions_dict = service_agreement . condition_by_name events_manager = EventsManager . get_instance ( Keeper . get_instance ( ) ) events_manager . watch_lock_reward_event ( agreement_id , access_secret_store_condition . fulfillAccessSecretStoreCondition , None , ( agreement_id , did , service_agreement , consumer_address , publisher_account ) , conditions_dict [ 'lockReward' ] . timeout ) events_manager . watch_access_event ( agreement_id , escrow_reward_condition . fulfillEscrowRewardCondition , None , ( agreement_id , service_agreement , price , consumer_address , publisher_account , condition_ids ) , conditions_dict [ 'accessSecretStore' ] . timeout ) events_manager . watch_reward_event ( agreement_id , verify_reward_condition . verifyRewardTokens , None , ( agreement_id , did , service_agreement , price , consumer_address , publisher_account ) , conditions_dict [ 'escrowReward' ] . timeout )
Process the agreement events during the register of the service agreement for the publisher side
268
15
234,462
def execute_pending_service_agreements ( storage_path , account , actor_type , did_resolver_fn ) : keeper = Keeper . get_instance ( ) # service_agreement_id, did, service_definition_id, price, files, start_time, status for ( agreement_id , did , _ , price , files , start_time , _ ) in get_service_agreements ( storage_path ) : ddo = did_resolver_fn ( did ) for service in ddo . services : if service . type != 'Access' : continue consumer_provider_tuple = keeper . escrow_access_secretstore_template . get_agreement_data ( agreement_id ) if not consumer_provider_tuple : continue consumer , provider = consumer_provider_tuple did = ddo . did service_agreement = ServiceAgreement . from_service_dict ( service . as_dictionary ( ) ) condition_ids = service_agreement . generate_agreement_condition_ids ( agreement_id , did , consumer , provider , keeper ) if actor_type == 'consumer' : assert account . address == consumer process_agreement_events_consumer ( provider , agreement_id , did , service_agreement , price , account , condition_ids , None ) else : assert account . address == provider process_agreement_events_publisher ( account , agreement_id , did , service_agreement , price , consumer , condition_ids )
Iterates over pending service agreements recorded in the local storage fetches their service definitions and subscribes to service agreement events .
325
24
234,463
def generate_multi_value_hash ( types , values ) : assert len ( types ) == len ( values ) return Web3Provider . get_web3 ( ) . soliditySha3 ( types , values )
Return the hash of the given list of values . This is equivalent to packing and hashing values in a solidity smart contract hence the use of soliditySha3 .
46
34
234,464
def process_tx_receipt ( tx_hash , event , event_name ) : web3 = Web3Provider . get_web3 ( ) try : web3 . eth . waitForTransactionReceipt ( tx_hash , timeout = 20 ) except Timeout : logger . info ( 'Waiting for transaction receipt timed out. Cannot verify receipt and event.' ) return receipt = web3 . eth . getTransactionReceipt ( tx_hash ) event = event ( ) . processReceipt ( receipt ) if event : logger . info ( f'Success: got {event_name} event after fulfilling condition.' ) logger . debug ( f'Success: got {event_name} event after fulfilling condition. {receipt}, ::: {event}' ) else : logger . debug ( f'Something is not right, cannot find the {event_name} event after calling the' f' fulfillment condition. This is the transaction receipt {receipt}' ) if receipt and receipt . status == 0 : logger . warning ( f'Transaction failed: tx_hash {tx_hash}, tx event {event_name}, receipt {receipt}' )
Wait until the tx receipt is processed .
248
8
234,465
def get_condition ( self , condition_id ) : condition = self . contract_concise . getCondition ( condition_id ) if condition and len ( condition ) == 7 : return ConditionValues ( * condition ) return None
Retrieve the condition for a condition_id .
47
10
234,466
def fulfill ( self , agreement_id , message , account_address , signature , from_account ) : return self . _fulfill ( agreement_id , message , account_address , signature , transact = { 'from' : from_account . address , 'passphrase' : from_account . password } )
Fulfill the sign conditon .
66
8
234,467
def is_access_granted ( self , agreement_id , did , consumer_address ) : agreement_consumer = self . _keeper . escrow_access_secretstore_template . get_agreement_consumer ( agreement_id ) if agreement_consumer != consumer_address : logger . warning ( f'Invalid consumer address {consumer_address} and/or ' f'service agreement id {agreement_id} (did {did})' f', agreement consumer is {agreement_consumer}' ) return False document_id = did_to_id ( did ) return self . _keeper . access_secret_store_condition . check_permissions ( document_id , consumer_address )
Check permission for the agreement .
150
6
234,468
def _verify_service_agreement_signature ( self , did , agreement_id , service_definition_id , consumer_address , signature , ddo = None ) : if not ddo : ddo = self . _asset_resolver . resolve ( did ) service_agreement = ServiceAgreement . from_ddo ( service_definition_id , ddo ) agreement_hash = service_agreement . get_service_agreement_hash ( agreement_id , ddo . asset_id , consumer_address , Web3Provider . get_web3 ( ) . toChecksumAddress ( ddo . proof [ 'creator' ] ) , self . _keeper ) prefixed_hash = prepare_prefixed_hash ( agreement_hash ) recovered_address = Web3Provider . get_web3 ( ) . eth . account . recoverHash ( prefixed_hash , signature = signature ) is_valid = ( recovered_address == consumer_address ) if not is_valid : logger . warning ( f'Agreement signature failed: agreement hash is {agreement_hash.hex()}' ) return is_valid
Verify service agreement signature .
244
6
234,469
def status ( self , agreement_id ) : condition_ids = self . _keeper . agreement_manager . get_agreement ( agreement_id ) . condition_ids result = { "agreementId" : agreement_id } conditions = dict ( ) for i in condition_ids : conditions [ self . _keeper . get_condition_name_by_address ( self . _keeper . condition_manager . get_condition ( i ) . type_ref ) ] = self . _keeper . condition_manager . get_condition_state ( i ) result [ "conditions" ] = conditions return result
Get the status of a service agreement .
128
8
234,470
def create_agreement ( self , agreement_id , did , condition_ids , time_locks , time_outs , consumer_address , account ) : logger . info ( f'Creating agreement {agreement_id} with did={did}, consumer={consumer_address}.' ) tx_hash = self . send_transaction ( 'createAgreement' , ( agreement_id , did , condition_ids , time_locks , time_outs , consumer_address ) , transact = { 'from' : account . address , 'passphrase' : account . password } ) receipt = self . get_tx_receipt ( tx_hash ) return receipt and receipt . status == 1
Create the service agreement . Return true if it is created successfully .
146
13
234,471
def subscribe_agreement_created ( self , agreement_id , timeout , callback , args , wait = False ) : logger . info ( f'Subscribing {self.AGREEMENT_CREATED_EVENT} event with agreement id {agreement_id}.' ) return self . subscribe_to_event ( self . AGREEMENT_CREATED_EVENT , timeout , { '_agreementId' : Web3Provider . get_web3 ( ) . toBytes ( hexstr = agreement_id ) } , callback = callback , args = args , wait = wait )
Subscribe to an agreement created .
125
6
234,472
def generate_id ( self , agreement_id , types , values ) : values_hash = utils . generate_multi_value_hash ( types , values ) return utils . generate_multi_value_hash ( [ 'bytes32' , 'address' , 'bytes32' ] , [ agreement_id , self . address , values_hash ] )
Generate id for the condition .
77
7
234,473
def _fulfill ( self , * args , * * kwargs ) : tx_hash = self . send_transaction ( 'fulfill' , args , * * kwargs ) receipt = self . get_tx_receipt ( tx_hash ) return receipt . status == 1
Fulfill the condition .
63
6
234,474
def subscribe_condition_fulfilled ( self , agreement_id , timeout , callback , args , timeout_callback = None , wait = False ) : logger . info ( f'Subscribing {self.FULFILLED_EVENT} event with agreement id {agreement_id}.' ) return self . subscribe_to_event ( self . FULFILLED_EVENT , timeout , { '_agreementId' : Web3Provider . get_web3 ( ) . toBytes ( hexstr = agreement_id ) } , callback = callback , timeout_callback = timeout_callback , args = args , wait = wait )
Subscribe to the condition fullfilled event .
136
8
234,475
def transact_with_contract_function ( address , web3 , function_name = None , transaction = None , contract_abi = None , fn_abi = None , * args , * * kwargs ) : transact_transaction = prepare_transaction ( address , web3 , fn_identifier = function_name , contract_abi = contract_abi , transaction = transaction , fn_abi = fn_abi , fn_args = args , fn_kwargs = kwargs , ) passphrase = None if transaction and 'passphrase' in transaction : passphrase = transaction [ 'passphrase' ] transact_transaction . pop ( 'passphrase' ) if passphrase : txn_hash = web3 . personal . sendTransaction ( transact_transaction , passphrase ) else : txn_hash = web3 . eth . sendTransaction ( transact_transaction ) return txn_hash
Helper function for interacting with a contract function by sending a transaction . This is copied from web3 transact_with_contract_function so we can use personal_sendTransaction when possible .
192
37
234,476
def transact ( self , transaction = None ) : if transaction is None : transact_transaction = { } else : transact_transaction = dict ( * * transaction ) if 'data' in transact_transaction : raise ValueError ( "Cannot set data in transact transaction" ) cf = self . _contract_function if cf . address is not None : transact_transaction . setdefault ( 'to' , cf . address ) if cf . web3 . eth . defaultAccount is not empty : transact_transaction . setdefault ( 'from' , cf . web3 . eth . defaultAccount ) if 'to' not in transact_transaction : if isinstance ( self , type ) : raise ValueError ( "When using `Contract.transact` from a contract factory you " "must provide a `to` address with the transaction" ) else : raise ValueError ( "Please ensure that this contract instance has an address." ) if 'gas' not in transact_transaction : tx = transaction . copy ( ) if 'passphrase' in tx : tx . pop ( 'passphrase' ) gas = cf . estimateGas ( tx ) transact_transaction [ 'gas' ] = gas return transact_with_contract_function ( cf . address , cf . web3 , cf . function_identifier , transact_transaction , cf . contract_abi , cf . abi , * cf . args , * * cf . kwargs )
Customize calling smart contract transaction functions to use personal_sendTransaction instead of eth_sendTransaction and to estimate gas limit . This function is largely copied from web3 ContractFunction with important addition .
306
39
234,477
def fulfill ( self , agreement_id , amount , receiver_address , sender_address , lock_condition_id , release_condition_id , account ) : return self . _fulfill ( agreement_id , amount , receiver_address , sender_address , lock_condition_id , release_condition_id , transact = { 'from' : account . address , 'passphrase' : account . password } )
Fulfill the escrow reward condition .
88
9
234,478
def hash_values ( self , amount , receiver_address , sender_address , lock_condition_id , release_condition_id ) : return self . _hash_values ( amount , receiver_address , sender_address , lock_condition_id , release_condition_id )
Hash the values of the escrow reward condition .
60
10
234,479
def as_dictionary ( self ) : return { "name" : self . name , "type" : self . type , "value" : remove_0x_prefix ( self . value ) if self . type == 'bytes32' else self . value }
Return the parameter as a dictionary .
56
7
234,480
def init_from_condition_json ( self , condition_json ) : self . name = condition_json [ 'name' ] self . timelock = condition_json [ 'timelock' ] self . timeout = condition_json [ 'timeout' ] self . contract_name = condition_json [ 'contractName' ] self . function_name = condition_json [ 'functionName' ] self . parameters = [ Parameter ( p ) for p in condition_json [ 'parameters' ] ] self . events = [ Event ( e ) for e in condition_json [ 'events' ] ]
Init the condition values from a condition json .
130
9
234,481
def as_dictionary ( self ) : condition_dict = { "name" : self . name , "timelock" : self . timelock , "timeout" : self . timeout , "contractName" : self . contract_name , "functionName" : self . function_name , "events" : [ e . as_dictionary ( ) for e in self . events ] , "parameters" : [ p . as_dictionary ( ) for p in self . parameters ] , } return condition_dict
Return the condition as a dictionary .
112
7
234,482
def update_value ( self , name , value ) : if name not in { 'id' , self . SERVICE_ENDPOINT , self . CONSUME_ENDPOINT , 'type' } : self . _values [ name ] = value
Update value in the array of values .
54
8
234,483
def as_text ( self , is_pretty = False ) : values = { 'type' : self . _type , self . SERVICE_ENDPOINT : self . _service_endpoint , } if self . _consume_endpoint is not None : values [ self . CONSUME_ENDPOINT ] = self . _consume_endpoint if self . _values : # add extra service values to the dictionary for name , value in self . _values . items ( ) : values [ name ] = value if is_pretty : return json . dumps ( values , indent = 4 , separators = ( ',' , ': ' ) ) return json . dumps ( values )
Return the service as a JSON string .
147
8
234,484
def as_dictionary ( self ) : values = { 'type' : self . _type , self . SERVICE_ENDPOINT : self . _service_endpoint , } if self . _consume_endpoint is not None : values [ self . CONSUME_ENDPOINT ] = self . _consume_endpoint if self . _values : # add extra service values to the dictionary for name , value in self . _values . items ( ) : if isinstance ( value , object ) and hasattr ( value , 'as_dictionary' ) : value = value . as_dictionary ( ) elif isinstance ( value , list ) : value = [ v . as_dictionary ( ) if hasattr ( v , 'as_dictionary' ) else v for v in value ] values [ name ] = value return values
Return the service as a python dictionary .
182
8
234,485
def from_json ( cls , service_dict ) : sd = service_dict . copy ( ) service_endpoint = sd . get ( cls . SERVICE_ENDPOINT ) if not service_endpoint : logger . error ( 'Service definition in DDO document is missing the "serviceEndpoint" key/value.' ) raise IndexError _type = sd . get ( 'type' ) if not _type : logger . error ( 'Service definition in DDO document is missing the "type" key/value.' ) raise IndexError sd . pop ( cls . SERVICE_ENDPOINT ) sd . pop ( 'type' ) return cls ( service_endpoint , _type , sd )
Create a service object from a JSON string .
152
9
234,486
def fulfill ( self , agreement_id , document_id , grantee_address , account ) : return self . _fulfill ( agreement_id , document_id , grantee_address , transact = { 'from' : account . address , 'passphrase' : account . password } )
Fulfill the access secret store condition .
62
9
234,487
def get_purchased_assets_by_address ( self , address , from_block = 0 , to_block = 'latest' ) : block_filter = EventFilter ( ConditionBase . FULFILLED_EVENT , getattr ( self . events , ConditionBase . FULFILLED_EVENT ) , from_block = from_block , to_block = to_block , argument_filters = { '_grantee' : address } ) log_items = block_filter . get_all_entries ( max_tries = 5 ) did_list = [ ] for log_i in log_items : did_list . append ( id_to_did ( log_i . args [ '_documentId' ] ) ) return did_list
Get the list of the assets dids consumed for an address .
170
13
234,488
def get_web3 ( ) : if Web3Provider . _web3 is None : config = ConfigProvider . get_config ( ) provider = ( config . web3_provider if config . web3_provider else CustomHTTPProvider ( config . keeper_url ) ) Web3Provider . _web3 = Web3 ( provider ) # Reset attributes to avoid lint issue about no attribute Web3Provider . _web3 . eth = getattr ( Web3Provider . _web3 , 'eth' ) Web3Provider . _web3 . net = getattr ( Web3Provider . _web3 , 'net' ) Web3Provider . _web3 . personal = getattr ( Web3Provider . _web3 , 'personal' ) Web3Provider . _web3 . version = getattr ( Web3Provider . _web3 , 'version' ) Web3Provider . _web3 . txpool = getattr ( Web3Provider . _web3 , 'txpool' ) Web3Provider . _web3 . miner = getattr ( Web3Provider . _web3 , 'miner' ) Web3Provider . _web3 . admin = getattr ( Web3Provider . _web3 , 'admin' ) Web3Provider . _web3 . parity = getattr ( Web3Provider . _web3 , 'parity' ) Web3Provider . _web3 . testing = getattr ( Web3Provider . _web3 , 'testing' ) return Web3Provider . _web3
Return the web3 instance to interact with the ethereum client .
320
13
234,489
def _get_type ( points , soma_class ) : assert soma_class in ( SOMA_CONTOUR , SOMA_CYLINDER ) npoints = len ( points ) if soma_class == SOMA_CONTOUR : return { 0 : None , 1 : SomaSinglePoint , 2 : None } . get ( npoints , SomaSimpleContour ) if ( npoints == 3 and points [ 0 ] [ COLS . P ] == - 1 and points [ 1 ] [ COLS . P ] == 1 and points [ 2 ] [ COLS . P ] == 1 ) : L . warning ( 'Using neuromorpho 3-Point soma' ) # NeuroMorpho is the main provider of morphologies, but they # with SWC as their default file format: they convert all # uploads to SWC. In the process of conversion, they turn all # somas into their custom 'Three-point soma representation': # http://neuromorpho.org/SomaFormat.html return SomaNeuromorphoThreePointCylinders return { 0 : None , 1 : SomaSinglePoint } . get ( npoints , SomaCylinders )
get the type of the soma
257
7
234,490
def make_soma ( points , soma_check = None , soma_class = SOMA_CONTOUR ) : if soma_check : soma_check ( points ) stype = _get_type ( points , soma_class ) if stype is None : raise SomaError ( 'Invalid soma points' ) return stype ( points )
Make a soma object from a set of points
79
10
234,491
def center ( self ) : points = np . array ( self . _points ) return np . mean ( points [ : , COLS . XYZ ] , axis = 0 )
Obtain the center from the average of all points
37
10
234,492
def section_tortuosity ( section ) : pts = section . points return 1 if len ( pts ) < 2 else mm . section_length ( pts ) / mm . point_dist ( pts [ - 1 ] , pts [ 0 ] )
Tortuosity of a section
52
7
234,493
def section_end_distance ( section ) : pts = section . points return 0 if len ( pts ) < 2 else mm . point_dist ( pts [ - 1 ] , pts [ 0 ] )
End to end distance of a section
42
7
234,494
def strahler_order ( section ) : if section . children : child_orders = [ strahler_order ( child ) for child in section . children ] max_so_children = max ( child_orders ) it = iter ( co == max_so_children for co in child_orders ) # check if there are *two* or more children w/ the max_so_children any ( it ) if any ( it ) : return max_so_children + 1 return max_so_children return 1
Branching order of a tree section
108
8
234,495
def figure_naming ( pretitle = '' , posttitle = '' , prefile = '' , postfile = '' ) : if pretitle : pretitle = "%s -- " % pretitle if posttitle : posttitle = " -- %s" % posttitle if prefile : prefile = "%s_" % prefile if postfile : postfile = "_%s" % postfile return pretitle , posttitle , prefile , postfile
Helper function to define the strings that handle pre - post conventions for viewing - plotting title and saving options .
96
21
234,496
def get_figure ( new_fig = True , subplot = '111' , params = None ) : _get_plt ( ) if new_fig : fig = plt . figure ( ) else : fig = plt . gcf ( ) params = dict_if_none ( params ) if isinstance ( subplot , ( tuple , list ) ) : ax = fig . add_subplot ( * subplot , * * params ) else : ax = fig . add_subplot ( subplot , * * params ) return fig , ax
Function to be used for viewing - plotting to initialize the matplotlib figure - axes .
117
18
234,497
def save_plot ( fig , prefile = '' , postfile = '' , output_path = './' , output_name = 'Figure' , output_format = 'png' , dpi = 300 , transparent = False , * * _ ) : if not os . path . exists ( output_path ) : os . makedirs ( output_path ) # Make output directory if non-exsiting output = os . path . join ( output_path , prefile + output_name + postfile + "." + output_format ) fig . savefig ( output , dpi = dpi , transparent = transparent )
Generates a figure file in the selected directory .
134
10
234,498
def plot_style ( fig , ax , # pylint: disable=too-many-arguments, too-many-locals # plot_title pretitle = '' , title = 'Figure' , posttitle = '' , title_fontsize = 14 , title_arg = None , # plot_labels label_fontsize = 14 , xlabel = None , xlabel_arg = None , ylabel = None , ylabel_arg = None , zlabel = None , zlabel_arg = None , # plot_ticks tick_fontsize = 12 , xticks = None , xticks_args = None , yticks = None , yticks_args = None , zticks = None , zticks_args = None , # update_plot_limits white_space = 30 , # plot_legend no_legend = True , legend_arg = None , # internal no_axes = False , aspect_ratio = 'equal' , tight = False , * * _ ) : plot_title ( ax , pretitle , title , posttitle , title_fontsize , title_arg ) plot_labels ( ax , label_fontsize , xlabel , xlabel_arg , ylabel , ylabel_arg , zlabel , zlabel_arg ) plot_ticks ( ax , tick_fontsize , xticks , xticks_args , yticks , yticks_args , zticks , zticks_args ) update_plot_limits ( ax , white_space ) plot_legend ( ax , no_legend , legend_arg ) if no_axes : ax . set_frame_on ( False ) ax . xaxis . set_visible ( False ) ax . yaxis . set_visible ( False ) ax . set_aspect ( aspect_ratio ) if tight : fig . set_tight_layout ( True )
Set the basic options of a matplotlib figure to be used by viewing - plotting functions
413
18
234,499
def plot_title ( ax , pretitle = '' , title = 'Figure' , posttitle = '' , title_fontsize = 14 , title_arg = None ) : current_title = ax . get_title ( ) if not current_title : current_title = pretitle + title + posttitle title_arg = dict_if_none ( title_arg ) ax . set_title ( current_title , fontsize = title_fontsize , * * title_arg )
Set title options of a matplotlib plot
103
9