hexsha
stringlengths
40
40
size
int64
2
1.02M
ext
stringclasses
10 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
2
1.02M
avg_line_length
float64
1
417k
max_line_length
int64
1
987k
alphanum_fraction
float64
0
1
content_no_comment
stringlengths
0
1.01M
is_comment_constant_removed
bool
1 class
is_sharp_comment_removed
bool
1 class
f72a41c562cc666e7693a5618222e1ff98c66a18
1,240
py
Python
Configuration/Generator/python/QCD_Pt_3000_3500_14TeV_TuneCUETP8M1_cfi.py
Purva-Chaudhari/cmssw
32e5cbfe54c4d809d60022586cf200b7c3020bcf
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
Configuration/Generator/python/QCD_Pt_3000_3500_14TeV_TuneCUETP8M1_cfi.py
Purva-Chaudhari/cmssw
32e5cbfe54c4d809d60022586cf200b7c3020bcf
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
Configuration/Generator/python/QCD_Pt_3000_3500_14TeV_TuneCUETP8M1_cfi.py
Purva-Chaudhari/cmssw
32e5cbfe54c4d809d60022586cf200b7c3020bcf
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
import FWCore.ParameterSet.Config as cms from Configuration.Generator.Pythia8CommonSettings_cfi import * from Configuration.Generator.Pythia8CUEP8M1Settings_cfi import * generator = cms.EDFilter("Pythia8ConcurrentGeneratorFilter", pythiaHepMCVerbosity = cms.untracked.bool(False), maxEventsToPrint = cms.untracked.int32(0), pythiaPylistVerbosity = cms.untracked.int32(1), filterEfficiency = cms.untracked.double(0.037), crossSection = cms.untracked.double(74310000.), comEnergy = cms.double(14000.0), # center of mass energy in GeV PythiaParameters = cms.PSet( pythia8CommonSettingsBlock, pythia8CUEP8M1SettingsBlock, processParameters = cms.vstring( 'HardQCD:all = on', 'PhaseSpace:pTHatMin = 3000.', 'PhaseSpace:pTHatMax = 3500.' ), parameterSets = cms.vstring('pythia8CommonSettings', 'pythia8CUEP8M1Settings', 'processParameters', ) ) )
45.925926
89
0.549194
import FWCore.ParameterSet.Config as cms from Configuration.Generator.Pythia8CommonSettings_cfi import * from Configuration.Generator.Pythia8CUEP8M1Settings_cfi import * generator = cms.EDFilter("Pythia8ConcurrentGeneratorFilter", pythiaHepMCVerbosity = cms.untracked.bool(False), maxEventsToPrint = cms.untracked.int32(0), pythiaPylistVerbosity = cms.untracked.int32(1), filterEfficiency = cms.untracked.double(0.037), crossSection = cms.untracked.double(74310000.), comEnergy = cms.double(14000.0), PythiaParameters = cms.PSet( pythia8CommonSettingsBlock, pythia8CUEP8M1SettingsBlock, processParameters = cms.vstring( 'HardQCD:all = on', 'PhaseSpace:pTHatMin = 3000.', 'PhaseSpace:pTHatMax = 3500.' ), parameterSets = cms.vstring('pythia8CommonSettings', 'pythia8CUEP8M1Settings', 'processParameters', ) ) )
true
true
f72a42c2e1e5a77f302472332be6e9a10fe5c67c
15,891
py
Python
azure-mgmt-devtestlabs/azure/mgmt/devtestlabs/operations/custom_image_operations.py
CharaD7/azure-sdk-for-python
9fdf0aac0cec8a15a5bb2a0ea27dd331dbfa2f5c
[ "MIT" ]
null
null
null
azure-mgmt-devtestlabs/azure/mgmt/devtestlabs/operations/custom_image_operations.py
CharaD7/azure-sdk-for-python
9fdf0aac0cec8a15a5bb2a0ea27dd331dbfa2f5c
[ "MIT" ]
null
null
null
azure-mgmt-devtestlabs/azure/mgmt/devtestlabs/operations/custom_image_operations.py
CharaD7/azure-sdk-for-python
9fdf0aac0cec8a15a5bb2a0ea27dd331dbfa2f5c
[ "MIT" ]
null
null
null
# 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. # -------------------------------------------------------------------------- from msrest.pipeline import ClientRawResponse from msrestazure.azure_exceptions import CloudError from msrestazure.azure_operation import AzureOperationPoller import uuid from .. import models class CustomImageOperations(object): """CustomImageOperations operations. :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An objec model deserializer. """ def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self.config = config def list( self, resource_group_name, lab_name, filter=None, top=None, order_by=None, custom_headers=None, raw=False, **operation_config): """List custom images in a given lab. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param lab_name: The name of the lab. :type lab_name: str :param filter: The filter to apply on the operation. :type filter: str :param top: The maximum number of resources to return from the operation. :type top: int :param order_by: The ordering expression for the results, using OData notation. :type order_by: str :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>`. :rtype: :class:`CustomImagePaged <azure.mgmt.devtestlabs.models.CustomImagePaged>` """ def internal_paging(next_link=None, raw=False): if not next_link: # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/customimages' path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'labName': self._serialize.url("lab_name", lab_name, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} if filter is not None: query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') if top is not None: query_parameters['$top'] = self._serialize.query("top", top, 'int') if order_by is not None: query_parameters['$orderBy'] = self._serialize.query("order_by", order_by, 'str') query_parameters['api-version'] = self._serialize.query("self.config.api_version", self.config.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, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp return response # Deserialize response deserialized = models.CustomImagePaged(internal_paging, self._deserialize.dependencies) if raw: header_dict = {} client_raw_response = models.CustomImagePaged(internal_paging, self._deserialize.dependencies, header_dict) return client_raw_response return deserialized def get_resource( self, resource_group_name, lab_name, name, custom_headers=None, raw=False, **operation_config): """Get custom image. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param lab_name: The name of the lab. :type lab_name: str :param name: The name of the custom image. :type name: str :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>`. :rtype: :class:`CustomImage <azure.mgmt.devtestlabs.models.CustomImage>` :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` if raw=true """ # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/customimages/{name}' path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'labName': self._serialize.url("lab_name", lab_name, 'str'), 'name': self._serialize.url("name", name, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.config.api_version", self.config.api_version, 'str') # 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, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('CustomImage', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized def create_or_update_resource( self, resource_group_name, lab_name, name, custom_image, custom_headers=None, raw=False, **operation_config): """Create or replace an existing custom image. This operation can take a while to complete. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param lab_name: The name of the lab. :type lab_name: str :param name: The name of the custom image. :type name: str :param custom_image: :type custom_image: :class:`CustomImage <azure.mgmt.devtestlabs.models.CustomImage>` :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :rtype: :class:`AzureOperationPoller<msrestazure.azure_operation.AzureOperationPoller>` instance that returns :class:`CustomImage <azure.mgmt.devtestlabs.models.CustomImage>` :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` if raw=true """ # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/customimages/{name}' path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'labName': self._serialize.url("lab_name", lab_name, 'str'), 'name': self._serialize.url("name", name, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.config.api_version", self.config.api_version, 'str') # 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 body body_content = self._serialize.body(custom_image, 'CustomImage') # Construct and send request def long_running_send(): request = self._client.put(url, query_parameters) return self._client.send( request, header_parameters, body_content, **operation_config) def get_long_running_status(status_link, headers=None): request = self._client.get(status_link) if headers: request.headers.update(headers) return self._client.send( request, header_parameters, **operation_config) def get_long_running_output(response): if response.status_code not in [200, 201]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('CustomImage', response) if response.status_code == 201: deserialized = self._deserialize('CustomImage', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized if raw: response = long_running_send() return get_long_running_output(response) long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) return AzureOperationPoller( long_running_send, get_long_running_output, get_long_running_status, long_running_operation_timeout) def delete_resource( self, resource_group_name, lab_name, name, custom_headers=None, raw=False, **operation_config): """Delete custom image. This operation can take a while to complete. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param lab_name: The name of the lab. :type lab_name: str :param name: The name of the custom image. :type name: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :rtype: :class:`AzureOperationPoller<msrestazure.azure_operation.AzureOperationPoller>` instance that returns None :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` if raw=true """ # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/customimages/{name}' path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'labName': self._serialize.url("lab_name", lab_name, 'str'), 'name': self._serialize.url("name", name, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.config.api_version", self.config.api_version, 'str') # 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 def long_running_send(): request = self._client.delete(url, query_parameters) return self._client.send(request, header_parameters, **operation_config) def get_long_running_status(status_link, headers=None): request = self._client.get(status_link) if headers: request.headers.update(headers) return self._client.send( request, header_parameters, **operation_config) def get_long_running_output(response): if response.status_code not in [202, 204]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp if raw: client_raw_response = ClientRawResponse(None, response) return client_raw_response if raw: response = long_running_send() return get_long_running_output(response) long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) return AzureOperationPoller( long_running_send, get_long_running_output, get_long_running_status, long_running_operation_timeout)
44.388268
149
0.646655
from msrest.pipeline import ClientRawResponse from msrestazure.azure_exceptions import CloudError from msrestazure.azure_operation import AzureOperationPoller import uuid from .. import models class CustomImageOperations(object): def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self.config = config def list( self, resource_group_name, lab_name, filter=None, top=None, order_by=None, custom_headers=None, raw=False, **operation_config): def internal_paging(next_link=None, raw=False): if not next_link: url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/customimages' path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'labName': self._serialize.url("lab_name", lab_name, 'str') } url = self._client.format_url(url, **path_format_arguments) query_parameters = {} if filter is not None: query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') if top is not None: query_parameters['$top'] = self._serialize.query("top", top, 'int') if order_by is not None: query_parameters['$orderBy'] = self._serialize.query("order_by", order_by, 'str') query_parameters['api-version'] = self._serialize.query("self.config.api_version", self.config.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, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp return response deserialized = models.CustomImagePaged(internal_paging, self._deserialize.dependencies) if raw: header_dict = {} client_raw_response = models.CustomImagePaged(internal_paging, self._deserialize.dependencies, header_dict) return client_raw_response return deserialized def get_resource( self, resource_group_name, lab_name, name, custom_headers=None, raw=False, **operation_config): url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/customimages/{name}' path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'labName': self._serialize.url("lab_name", lab_name, 'str'), 'name': self._serialize.url("name", name, 'str') } url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.config.api_version", self.config.api_version, 'str') 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, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('CustomImage', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized def create_or_update_resource( self, resource_group_name, lab_name, name, custom_image, custom_headers=None, raw=False, **operation_config): url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/customimages/{name}' path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'labName': self._serialize.url("lab_name", lab_name, 'str'), 'name': self._serialize.url("name", name, 'str') } url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.config.api_version", self.config.api_version, 'str') 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') body_content = self._serialize.body(custom_image, 'CustomImage') def long_running_send(): request = self._client.put(url, query_parameters) return self._client.send( request, header_parameters, body_content, **operation_config) def get_long_running_status(status_link, headers=None): request = self._client.get(status_link) if headers: request.headers.update(headers) return self._client.send( request, header_parameters, **operation_config) def get_long_running_output(response): if response.status_code not in [200, 201]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('CustomImage', response) if response.status_code == 201: deserialized = self._deserialize('CustomImage', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized if raw: response = long_running_send() return get_long_running_output(response) long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) return AzureOperationPoller( long_running_send, get_long_running_output, get_long_running_status, long_running_operation_timeout) def delete_resource( self, resource_group_name, lab_name, name, custom_headers=None, raw=False, **operation_config): url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/customimages/{name}' path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'labName': self._serialize.url("lab_name", lab_name, 'str'), 'name': self._serialize.url("name", name, 'str') } url = self._client.format_url(url, **path_format_arguments) query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.config.api_version", self.config.api_version, 'str') 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') def long_running_send(): request = self._client.delete(url, query_parameters) return self._client.send(request, header_parameters, **operation_config) def get_long_running_status(status_link, headers=None): request = self._client.get(status_link) if headers: request.headers.update(headers) return self._client.send( request, header_parameters, **operation_config) def get_long_running_output(response): if response.status_code not in [202, 204]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp if raw: client_raw_response = ClientRawResponse(None, response) return client_raw_response if raw: response = long_running_send() return get_long_running_output(response) long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) return AzureOperationPoller( long_running_send, get_long_running_output, get_long_running_status, long_running_operation_timeout)
true
true
f72a42f0de9fa77c288318b1b5d013ccfb8f3bf4
771
py
Python
setup.py
littleq0903/django-gcloud-storage
52e4a4a6773a5e79cf3fec19dcc1290e65942a70
[ "MIT" ]
3
2015-01-08T09:13:12.000Z
2020-11-27T16:23:09.000Z
setup.py
littleq0903/django-gcloud-storage
52e4a4a6773a5e79cf3fec19dcc1290e65942a70
[ "MIT" ]
1
2015-02-25T05:03:02.000Z
2019-02-08T07:00:35.000Z
setup.py
littleq0903/django-gcloud-storage
52e4a4a6773a5e79cf3fec19dcc1290e65942a70
[ "MIT" ]
1
2015-02-25T03:55:54.000Z
2015-02-25T03:55:54.000Z
from setuptools import setup, find_packages import django_gcs setup_options = { 'name': 'django-gcloud-storage', 'version': django_gcs.__version__, 'packages': find_packages(), 'author': 'Colin Su', 'author_email': 'littleq0903@gmail.com', 'license': 'MIT', 'description': open('./README.md').read(), 'url': 'https://github.com/littleq0903/django-gcloud-storage', 'classifiers': [ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ] } setup(**setup_options)
28.555556
70
0.574578
from setuptools import setup, find_packages import django_gcs setup_options = { 'name': 'django-gcloud-storage', 'version': django_gcs.__version__, 'packages': find_packages(), 'author': 'Colin Su', 'author_email': 'littleq0903@gmail.com', 'license': 'MIT', 'description': open('./README.md').read(), 'url': 'https://github.com/littleq0903/django-gcloud-storage', 'classifiers': [ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ] } setup(**setup_options)
true
true
f72a43f375f75914487974a4a07a4ec77f462c62
1,509
py
Python
src/word_processing.py
bsbhaskar/product_review_sentiments
46de372f4d410f44e487c92b9279cf13c33d4cd1
[ "MIT" ]
2
2018-06-07T21:55:33.000Z
2018-09-15T08:33:53.000Z
src/word_processing.py
bsbhaskar/product_review_sentiments
46de372f4d410f44e487c92b9279cf13c33d4cd1
[ "MIT" ]
null
null
null
src/word_processing.py
bsbhaskar/product_review_sentiments
46de372f4d410f44e487c92b9279cf13c33d4cd1
[ "MIT" ]
null
null
null
import string import spacy import pickle from nltk.stem.wordnet import WordNetLemmatizer from gensim.models import Phrases, Word2Vec from nltk.corpus import stopwords import warnings warnings.filterwarnings("ignore") class WordProcessor(): ''' This is a utility class that loads data related to processing words. ''' def __init__(self): ''' Initialize loading of keywords and vocab and custom keywords. In the future, the custom keywords will be moved to a file. ''' self.nlp = spacy.load("en") self.stop_words = set(stopwords.words('english')) custom_stop_words = set(['is','have','was','has','been','','samsung','one','amazon','sony','star','stars','middle','black','use','white','dont','night','room','way','purchased','vanns','think','got','thought','way','set','nice','son','half','line','tv','picture','screen','work','hour','day','week','month','time','work','days','months','weeks','pron']) self.stop_words = self.stop_words.union(custom_stop_words) self.punctuation = set(string.punctuation) self.lemmatize = WordNetLemmatizer() def clean_document(self, doc): ''' returns list of words from a document post word_processing ''' words = [] for word in doc.lower().split(): if ((word not in self.stop_words) and (word not in self.punctuation) and (len(word) > 1)): words.append(self.lemmatize.lemmatize(word)) return words
41.916667
361
0.640822
import string import spacy import pickle from nltk.stem.wordnet import WordNetLemmatizer from gensim.models import Phrases, Word2Vec from nltk.corpus import stopwords import warnings warnings.filterwarnings("ignore") class WordProcessor(): def __init__(self): self.nlp = spacy.load("en") self.stop_words = set(stopwords.words('english')) custom_stop_words = set(['is','have','was','has','been','','samsung','one','amazon','sony','star','stars','middle','black','use','white','dont','night','room','way','purchased','vanns','think','got','thought','way','set','nice','son','half','line','tv','picture','screen','work','hour','day','week','month','time','work','days','months','weeks','pron']) self.stop_words = self.stop_words.union(custom_stop_words) self.punctuation = set(string.punctuation) self.lemmatize = WordNetLemmatizer() def clean_document(self, doc): words = [] for word in doc.lower().split(): if ((word not in self.stop_words) and (word not in self.punctuation) and (len(word) > 1)): words.append(self.lemmatize.lemmatize(word)) return words
true
true
f72a44144e09def7c3fe812e31e7c8bfecf516d8
1,536
py
Python
auth0login/auth0backend.py
chop-dbhi/biorepo-portal
7db13c40b2b9d62af43a28e4af08c2472b98fc96
[ "BSD-2-Clause" ]
6
2016-10-26T19:51:11.000Z
2021-03-18T16:05:55.000Z
auth0login/auth0backend.py
chop-dbhi/biorepo-portal
7db13c40b2b9d62af43a28e4af08c2472b98fc96
[ "BSD-2-Clause" ]
207
2015-09-24T17:41:37.000Z
2021-05-18T18:14:08.000Z
auth0login/auth0backend.py
chop-dbhi/biorepo-portal
7db13c40b2b9d62af43a28e4af08c2472b98fc96
[ "BSD-2-Clause" ]
8
2016-04-27T19:04:50.000Z
2020-08-24T02:33:05.000Z
# auth0login/auth0backend.py from urllib import request from jose import jwt from social_core.backends.oauth import BaseOAuth2 from accounts.models import UserProfile class Auth0(BaseOAuth2): """Auth0 OAuth authentication backend""" name = 'auth0' SCOPE_SEPARATOR = ' ' ACCESS_TOKEN_METHOD = 'POST' REDIRECT_STATE = False EXTRA_DATA = [ ('picture', 'picture'), ('email', 'email') ] def authorization_url(self): return 'https://' + self.setting('DOMAIN') + '/authorize' def access_token_url(self): return 'https://' + self.setting('DOMAIN') + '/oauth/token' def get_user_id(self, details, response): """Return current user id.""" print("is this using user ID?") print("user id: {}".format(details['user_id'])) return details['user_id'] def get_user_details(self, response): # Obtain JWT and the keys to validate the signature id_token = response.get('id_token') jwks = request.urlopen('https://' + self.setting('DOMAIN') + '/.well-known/jwks.json') issuer = 'https://' + self.setting('DOMAIN') + '/' audience = self.setting('KEY') # CLIENT_ID payload = jwt.decode(id_token, jwks.read(), algorithms=['RS256'], audience=audience, issuer=issuer) return {'username': payload['nickname'], 'first_name': payload['name'], 'picture': payload['picture'], 'user_id': payload['sub'], 'email': payload['email']}
34.133333
107
0.609375
from urllib import request from jose import jwt from social_core.backends.oauth import BaseOAuth2 from accounts.models import UserProfile class Auth0(BaseOAuth2): name = 'auth0' SCOPE_SEPARATOR = ' ' ACCESS_TOKEN_METHOD = 'POST' REDIRECT_STATE = False EXTRA_DATA = [ ('picture', 'picture'), ('email', 'email') ] def authorization_url(self): return 'https://' + self.setting('DOMAIN') + '/authorize' def access_token_url(self): return 'https://' + self.setting('DOMAIN') + '/oauth/token' def get_user_id(self, details, response): print("is this using user ID?") print("user id: {}".format(details['user_id'])) return details['user_id'] def get_user_details(self, response): id_token = response.get('id_token') jwks = request.urlopen('https://' + self.setting('DOMAIN') + '/.well-known/jwks.json') issuer = 'https://' + self.setting('DOMAIN') + '/' audience = self.setting('KEY') payload = jwt.decode(id_token, jwks.read(), algorithms=['RS256'], audience=audience, issuer=issuer) return {'username': payload['nickname'], 'first_name': payload['name'], 'picture': payload['picture'], 'user_id': payload['sub'], 'email': payload['email']}
true
true
f72a4476249a5b91384f4535c7234e7f722e0b67
19,874
py
Python
tests/test_cognitoidp/test_cognitoidp.py
alexsult/moto
ed861ecae1039a048a6350a4ff832ef094cdf2c2
[ "Apache-2.0" ]
null
null
null
tests/test_cognitoidp/test_cognitoidp.py
alexsult/moto
ed861ecae1039a048a6350a4ff832ef094cdf2c2
[ "Apache-2.0" ]
5
2018-04-25T21:04:20.000Z
2018-11-02T19:59:27.000Z
tests/test_cognitoidp/test_cognitoidp.py
alexsult/moto
ed861ecae1039a048a6350a4ff832ef094cdf2c2
[ "Apache-2.0" ]
null
null
null
from __future__ import unicode_literals import boto3 import json import os import uuid from jose import jws from moto import mock_cognitoidp import sure # noqa @mock_cognitoidp def test_create_user_pool(): conn = boto3.client("cognito-idp", "us-west-2") name = str(uuid.uuid4()) value = str(uuid.uuid4()) result = conn.create_user_pool( PoolName=name, LambdaConfig={ "PreSignUp": value } ) result["UserPool"]["Id"].should_not.be.none result["UserPool"]["Id"].should.match(r'[\w-]+_[0-9a-zA-Z]+') result["UserPool"]["Name"].should.equal(name) result["UserPool"]["LambdaConfig"]["PreSignUp"].should.equal(value) @mock_cognitoidp def test_list_user_pools(): conn = boto3.client("cognito-idp", "us-west-2") name = str(uuid.uuid4()) conn.create_user_pool(PoolName=name) result = conn.list_user_pools(MaxResults=10) result["UserPools"].should.have.length_of(1) result["UserPools"][0]["Name"].should.equal(name) @mock_cognitoidp def test_describe_user_pool(): conn = boto3.client("cognito-idp", "us-west-2") name = str(uuid.uuid4()) value = str(uuid.uuid4()) user_pool_details = conn.create_user_pool( PoolName=name, LambdaConfig={ "PreSignUp": value } ) result = conn.describe_user_pool(UserPoolId=user_pool_details["UserPool"]["Id"]) result["UserPool"]["Name"].should.equal(name) result["UserPool"]["LambdaConfig"]["PreSignUp"].should.equal(value) @mock_cognitoidp def test_delete_user_pool(): conn = boto3.client("cognito-idp", "us-west-2") user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.list_user_pools(MaxResults=10)["UserPools"].should.have.length_of(1) conn.delete_user_pool(UserPoolId=user_pool_id) conn.list_user_pools(MaxResults=10)["UserPools"].should.have.length_of(0) @mock_cognitoidp def test_create_user_pool_domain(): conn = boto3.client("cognito-idp", "us-west-2") domain = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] result = conn.create_user_pool_domain(UserPoolId=user_pool_id, Domain=domain) result["ResponseMetadata"]["HTTPStatusCode"].should.equal(200) @mock_cognitoidp def test_describe_user_pool_domain(): conn = boto3.client("cognito-idp", "us-west-2") domain = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.create_user_pool_domain(UserPoolId=user_pool_id, Domain=domain) result = conn.describe_user_pool_domain(Domain=domain) result["DomainDescription"]["Domain"].should.equal(domain) result["DomainDescription"]["UserPoolId"].should.equal(user_pool_id) result["DomainDescription"]["AWSAccountId"].should_not.be.none @mock_cognitoidp def test_delete_user_pool_domain(): conn = boto3.client("cognito-idp", "us-west-2") domain = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.create_user_pool_domain(UserPoolId=user_pool_id, Domain=domain) result = conn.delete_user_pool_domain(UserPoolId=user_pool_id, Domain=domain) result["ResponseMetadata"]["HTTPStatusCode"].should.equal(200) result = conn.describe_user_pool_domain(Domain=domain) # This is a surprising behavior of the real service: describing a missing domain comes # back with status 200 and a DomainDescription of {} result["ResponseMetadata"]["HTTPStatusCode"].should.equal(200) result["DomainDescription"].keys().should.have.length_of(0) @mock_cognitoidp def test_create_user_pool_client(): conn = boto3.client("cognito-idp", "us-west-2") client_name = str(uuid.uuid4()) value = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] result = conn.create_user_pool_client( UserPoolId=user_pool_id, ClientName=client_name, CallbackURLs=[value], ) result["UserPoolClient"]["UserPoolId"].should.equal(user_pool_id) result["UserPoolClient"]["ClientId"].should_not.be.none result["UserPoolClient"]["ClientName"].should.equal(client_name) result["UserPoolClient"]["CallbackURLs"].should.have.length_of(1) result["UserPoolClient"]["CallbackURLs"][0].should.equal(value) @mock_cognitoidp def test_list_user_pool_clients(): conn = boto3.client("cognito-idp", "us-west-2") client_name = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.create_user_pool_client(UserPoolId=user_pool_id, ClientName=client_name) result = conn.list_user_pool_clients(UserPoolId=user_pool_id, MaxResults=10) result["UserPoolClients"].should.have.length_of(1) result["UserPoolClients"][0]["ClientName"].should.equal(client_name) @mock_cognitoidp def test_describe_user_pool_client(): conn = boto3.client("cognito-idp", "us-west-2") client_name = str(uuid.uuid4()) value = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] client_details = conn.create_user_pool_client( UserPoolId=user_pool_id, ClientName=client_name, CallbackURLs=[value], ) result = conn.describe_user_pool_client( UserPoolId=user_pool_id, ClientId=client_details["UserPoolClient"]["ClientId"], ) result["UserPoolClient"]["ClientName"].should.equal(client_name) result["UserPoolClient"]["CallbackURLs"].should.have.length_of(1) result["UserPoolClient"]["CallbackURLs"][0].should.equal(value) @mock_cognitoidp def test_update_user_pool_client(): conn = boto3.client("cognito-idp", "us-west-2") old_client_name = str(uuid.uuid4()) new_client_name = str(uuid.uuid4()) old_value = str(uuid.uuid4()) new_value = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] client_details = conn.create_user_pool_client( UserPoolId=user_pool_id, ClientName=old_client_name, CallbackURLs=[old_value], ) result = conn.update_user_pool_client( UserPoolId=user_pool_id, ClientId=client_details["UserPoolClient"]["ClientId"], ClientName=new_client_name, CallbackURLs=[new_value], ) result["UserPoolClient"]["ClientName"].should.equal(new_client_name) result["UserPoolClient"]["CallbackURLs"].should.have.length_of(1) result["UserPoolClient"]["CallbackURLs"][0].should.equal(new_value) @mock_cognitoidp def test_delete_user_pool_client(): conn = boto3.client("cognito-idp", "us-west-2") user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] client_details = conn.create_user_pool_client( UserPoolId=user_pool_id, ClientName=str(uuid.uuid4()), ) conn.delete_user_pool_client( UserPoolId=user_pool_id, ClientId=client_details["UserPoolClient"]["ClientId"], ) caught = False try: conn.describe_user_pool_client( UserPoolId=user_pool_id, ClientId=client_details["UserPoolClient"]["ClientId"], ) except conn.exceptions.ResourceNotFoundException: caught = True caught.should.be.true @mock_cognitoidp def test_create_identity_provider(): conn = boto3.client("cognito-idp", "us-west-2") provider_name = str(uuid.uuid4()) provider_type = "Facebook" value = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] result = conn.create_identity_provider( UserPoolId=user_pool_id, ProviderName=provider_name, ProviderType=provider_type, ProviderDetails={ "thing": value }, ) result["IdentityProvider"]["UserPoolId"].should.equal(user_pool_id) result["IdentityProvider"]["ProviderName"].should.equal(provider_name) result["IdentityProvider"]["ProviderType"].should.equal(provider_type) result["IdentityProvider"]["ProviderDetails"]["thing"].should.equal(value) @mock_cognitoidp def test_list_identity_providers(): conn = boto3.client("cognito-idp", "us-west-2") provider_name = str(uuid.uuid4()) provider_type = "Facebook" user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.create_identity_provider( UserPoolId=user_pool_id, ProviderName=provider_name, ProviderType=provider_type, ProviderDetails={}, ) result = conn.list_identity_providers( UserPoolId=user_pool_id, MaxResults=10, ) result["Providers"].should.have.length_of(1) result["Providers"][0]["ProviderName"].should.equal(provider_name) result["Providers"][0]["ProviderType"].should.equal(provider_type) @mock_cognitoidp def test_describe_identity_providers(): conn = boto3.client("cognito-idp", "us-west-2") provider_name = str(uuid.uuid4()) provider_type = "Facebook" value = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.create_identity_provider( UserPoolId=user_pool_id, ProviderName=provider_name, ProviderType=provider_type, ProviderDetails={ "thing": value }, ) result = conn.describe_identity_provider( UserPoolId=user_pool_id, ProviderName=provider_name, ) result["IdentityProvider"]["UserPoolId"].should.equal(user_pool_id) result["IdentityProvider"]["ProviderName"].should.equal(provider_name) result["IdentityProvider"]["ProviderType"].should.equal(provider_type) result["IdentityProvider"]["ProviderDetails"]["thing"].should.equal(value) @mock_cognitoidp def test_delete_identity_providers(): conn = boto3.client("cognito-idp", "us-west-2") provider_name = str(uuid.uuid4()) provider_type = "Facebook" value = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.create_identity_provider( UserPoolId=user_pool_id, ProviderName=provider_name, ProviderType=provider_type, ProviderDetails={ "thing": value }, ) conn.delete_identity_provider(UserPoolId=user_pool_id, ProviderName=provider_name) caught = False try: conn.describe_identity_provider( UserPoolId=user_pool_id, ProviderName=provider_name, ) except conn.exceptions.ResourceNotFoundException: caught = True caught.should.be.true @mock_cognitoidp def test_admin_create_user(): conn = boto3.client("cognito-idp", "us-west-2") username = str(uuid.uuid4()) value = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] result = conn.admin_create_user( UserPoolId=user_pool_id, Username=username, UserAttributes=[ {"Name": "thing", "Value": value} ], ) result["User"]["Username"].should.equal(username) result["User"]["UserStatus"].should.equal("FORCE_CHANGE_PASSWORD") result["User"]["Attributes"].should.have.length_of(1) result["User"]["Attributes"][0]["Name"].should.equal("thing") result["User"]["Attributes"][0]["Value"].should.equal(value) result["User"]["Enabled"].should.equal(True) @mock_cognitoidp def test_admin_get_user(): conn = boto3.client("cognito-idp", "us-west-2") username = str(uuid.uuid4()) value = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.admin_create_user( UserPoolId=user_pool_id, Username=username, UserAttributes=[ {"Name": "thing", "Value": value} ], ) result = conn.admin_get_user(UserPoolId=user_pool_id, Username=username) result["Username"].should.equal(username) result["UserAttributes"].should.have.length_of(1) result["UserAttributes"][0]["Name"].should.equal("thing") result["UserAttributes"][0]["Value"].should.equal(value) @mock_cognitoidp def test_admin_get_missing_user(): conn = boto3.client("cognito-idp", "us-west-2") username = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] caught = False try: conn.admin_get_user(UserPoolId=user_pool_id, Username=username) except conn.exceptions.UserNotFoundException: caught = True caught.should.be.true @mock_cognitoidp def test_list_users(): conn = boto3.client("cognito-idp", "us-west-2") username = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.admin_create_user(UserPoolId=user_pool_id, Username=username) result = conn.list_users(UserPoolId=user_pool_id) result["Users"].should.have.length_of(1) result["Users"][0]["Username"].should.equal(username) @mock_cognitoidp def test_admin_disable_user(): conn = boto3.client("cognito-idp", "us-west-2") username = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.admin_create_user(UserPoolId=user_pool_id, Username=username) result = conn.admin_disable_user(UserPoolId=user_pool_id, Username=username) list(result.keys()).should.equal(["ResponseMetadata"]) # No response expected conn.admin_get_user(UserPoolId=user_pool_id, Username=username) \ ["Enabled"].should.equal(False) @mock_cognitoidp def test_admin_enable_user(): conn = boto3.client("cognito-idp", "us-west-2") username = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.admin_create_user(UserPoolId=user_pool_id, Username=username) conn.admin_disable_user(UserPoolId=user_pool_id, Username=username) result = conn.admin_enable_user(UserPoolId=user_pool_id, Username=username) list(result.keys()).should.equal(["ResponseMetadata"]) # No response expected conn.admin_get_user(UserPoolId=user_pool_id, Username=username) \ ["Enabled"].should.equal(True) @mock_cognitoidp def test_admin_delete_user(): conn = boto3.client("cognito-idp", "us-west-2") username = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.admin_create_user(UserPoolId=user_pool_id, Username=username) conn.admin_delete_user(UserPoolId=user_pool_id, Username=username) caught = False try: conn.admin_get_user(UserPoolId=user_pool_id, Username=username) except conn.exceptions.UserNotFoundException: caught = True caught.should.be.true def authentication_flow(conn): username = str(uuid.uuid4()) temporary_password = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] user_attribute_name = str(uuid.uuid4()) user_attribute_value = str(uuid.uuid4()) client_id = conn.create_user_pool_client( UserPoolId=user_pool_id, ClientName=str(uuid.uuid4()), ReadAttributes=[user_attribute_name] )["UserPoolClient"]["ClientId"] conn.admin_create_user( UserPoolId=user_pool_id, Username=username, TemporaryPassword=temporary_password, UserAttributes=[{ 'Name': user_attribute_name, 'Value': user_attribute_value }] ) result = conn.admin_initiate_auth( UserPoolId=user_pool_id, ClientId=client_id, AuthFlow="ADMIN_NO_SRP_AUTH", AuthParameters={ "USERNAME": username, "PASSWORD": temporary_password }, ) # A newly created user is forced to set a new password result["ChallengeName"].should.equal("NEW_PASSWORD_REQUIRED") result["Session"].should_not.be.none # This sets a new password and logs the user in (creates tokens) new_password = str(uuid.uuid4()) result = conn.respond_to_auth_challenge( Session=result["Session"], ClientId=client_id, ChallengeName="NEW_PASSWORD_REQUIRED", ChallengeResponses={ "USERNAME": username, "NEW_PASSWORD": new_password } ) result["AuthenticationResult"]["IdToken"].should_not.be.none result["AuthenticationResult"]["AccessToken"].should_not.be.none return { "user_pool_id": user_pool_id, "client_id": client_id, "id_token": result["AuthenticationResult"]["IdToken"], "access_token": result["AuthenticationResult"]["AccessToken"], "username": username, "password": new_password, "additional_fields": { user_attribute_name: user_attribute_value } } @mock_cognitoidp def test_authentication_flow(): conn = boto3.client("cognito-idp", "us-west-2") authentication_flow(conn) @mock_cognitoidp def test_token_legitimacy(): conn = boto3.client("cognito-idp", "us-west-2") path = "../../moto/cognitoidp/resources/jwks-public.json" with open(os.path.join(os.path.dirname(__file__), path)) as f: json_web_key = json.loads(f.read())["keys"][0] outputs = authentication_flow(conn) id_token = outputs["id_token"] access_token = outputs["access_token"] client_id = outputs["client_id"] issuer = "https://cognito-idp.us-west-2.amazonaws.com/{}".format(outputs["user_pool_id"]) id_claims = json.loads(jws.verify(id_token, json_web_key, "RS256")) id_claims["iss"].should.equal(issuer) id_claims["aud"].should.equal(client_id) access_claims = json.loads(jws.verify(access_token, json_web_key, "RS256")) access_claims["iss"].should.equal(issuer) access_claims["aud"].should.equal(client_id) for k, v in outputs["additional_fields"].items(): access_claims[k].should.equal(v) @mock_cognitoidp def test_change_password(): conn = boto3.client("cognito-idp", "us-west-2") outputs = authentication_flow(conn) # Take this opportunity to test change_password, which requires an access token. newer_password = str(uuid.uuid4()) conn.change_password( AccessToken=outputs["access_token"], PreviousPassword=outputs["password"], ProposedPassword=newer_password, ) # Log in again, which should succeed without a challenge because the user is no # longer in the force-new-password state. result = conn.admin_initiate_auth( UserPoolId=outputs["user_pool_id"], ClientId=outputs["client_id"], AuthFlow="ADMIN_NO_SRP_AUTH", AuthParameters={ "USERNAME": outputs["username"], "PASSWORD": newer_password, }, ) result["AuthenticationResult"].should_not.be.none @mock_cognitoidp def test_forgot_password(): conn = boto3.client("cognito-idp", "us-west-2") result = conn.forgot_password(ClientId=str(uuid.uuid4()), Username=str(uuid.uuid4())) result["CodeDeliveryDetails"].should_not.be.none @mock_cognitoidp def test_confirm_forgot_password(): conn = boto3.client("cognito-idp", "us-west-2") username = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] client_id = conn.create_user_pool_client( UserPoolId=user_pool_id, ClientName=str(uuid.uuid4()), )["UserPoolClient"]["ClientId"] conn.admin_create_user( UserPoolId=user_pool_id, Username=username, TemporaryPassword=str(uuid.uuid4()), ) conn.confirm_forgot_password( ClientId=client_id, Username=username, ConfirmationCode=str(uuid.uuid4()), Password=str(uuid.uuid4()), )
33.013289
93
0.690601
from __future__ import unicode_literals import boto3 import json import os import uuid from jose import jws from moto import mock_cognitoidp import sure @mock_cognitoidp def test_create_user_pool(): conn = boto3.client("cognito-idp", "us-west-2") name = str(uuid.uuid4()) value = str(uuid.uuid4()) result = conn.create_user_pool( PoolName=name, LambdaConfig={ "PreSignUp": value } ) result["UserPool"]["Id"].should_not.be.none result["UserPool"]["Id"].should.match(r'[\w-]+_[0-9a-zA-Z]+') result["UserPool"]["Name"].should.equal(name) result["UserPool"]["LambdaConfig"]["PreSignUp"].should.equal(value) @mock_cognitoidp def test_list_user_pools(): conn = boto3.client("cognito-idp", "us-west-2") name = str(uuid.uuid4()) conn.create_user_pool(PoolName=name) result = conn.list_user_pools(MaxResults=10) result["UserPools"].should.have.length_of(1) result["UserPools"][0]["Name"].should.equal(name) @mock_cognitoidp def test_describe_user_pool(): conn = boto3.client("cognito-idp", "us-west-2") name = str(uuid.uuid4()) value = str(uuid.uuid4()) user_pool_details = conn.create_user_pool( PoolName=name, LambdaConfig={ "PreSignUp": value } ) result = conn.describe_user_pool(UserPoolId=user_pool_details["UserPool"]["Id"]) result["UserPool"]["Name"].should.equal(name) result["UserPool"]["LambdaConfig"]["PreSignUp"].should.equal(value) @mock_cognitoidp def test_delete_user_pool(): conn = boto3.client("cognito-idp", "us-west-2") user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.list_user_pools(MaxResults=10)["UserPools"].should.have.length_of(1) conn.delete_user_pool(UserPoolId=user_pool_id) conn.list_user_pools(MaxResults=10)["UserPools"].should.have.length_of(0) @mock_cognitoidp def test_create_user_pool_domain(): conn = boto3.client("cognito-idp", "us-west-2") domain = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] result = conn.create_user_pool_domain(UserPoolId=user_pool_id, Domain=domain) result["ResponseMetadata"]["HTTPStatusCode"].should.equal(200) @mock_cognitoidp def test_describe_user_pool_domain(): conn = boto3.client("cognito-idp", "us-west-2") domain = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.create_user_pool_domain(UserPoolId=user_pool_id, Domain=domain) result = conn.describe_user_pool_domain(Domain=domain) result["DomainDescription"]["Domain"].should.equal(domain) result["DomainDescription"]["UserPoolId"].should.equal(user_pool_id) result["DomainDescription"]["AWSAccountId"].should_not.be.none @mock_cognitoidp def test_delete_user_pool_domain(): conn = boto3.client("cognito-idp", "us-west-2") domain = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.create_user_pool_domain(UserPoolId=user_pool_id, Domain=domain) result = conn.delete_user_pool_domain(UserPoolId=user_pool_id, Domain=domain) result["ResponseMetadata"]["HTTPStatusCode"].should.equal(200) result = conn.describe_user_pool_domain(Domain=domain) result["ResponseMetadata"]["HTTPStatusCode"].should.equal(200) result["DomainDescription"].keys().should.have.length_of(0) @mock_cognitoidp def test_create_user_pool_client(): conn = boto3.client("cognito-idp", "us-west-2") client_name = str(uuid.uuid4()) value = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] result = conn.create_user_pool_client( UserPoolId=user_pool_id, ClientName=client_name, CallbackURLs=[value], ) result["UserPoolClient"]["UserPoolId"].should.equal(user_pool_id) result["UserPoolClient"]["ClientId"].should_not.be.none result["UserPoolClient"]["ClientName"].should.equal(client_name) result["UserPoolClient"]["CallbackURLs"].should.have.length_of(1) result["UserPoolClient"]["CallbackURLs"][0].should.equal(value) @mock_cognitoidp def test_list_user_pool_clients(): conn = boto3.client("cognito-idp", "us-west-2") client_name = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.create_user_pool_client(UserPoolId=user_pool_id, ClientName=client_name) result = conn.list_user_pool_clients(UserPoolId=user_pool_id, MaxResults=10) result["UserPoolClients"].should.have.length_of(1) result["UserPoolClients"][0]["ClientName"].should.equal(client_name) @mock_cognitoidp def test_describe_user_pool_client(): conn = boto3.client("cognito-idp", "us-west-2") client_name = str(uuid.uuid4()) value = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] client_details = conn.create_user_pool_client( UserPoolId=user_pool_id, ClientName=client_name, CallbackURLs=[value], ) result = conn.describe_user_pool_client( UserPoolId=user_pool_id, ClientId=client_details["UserPoolClient"]["ClientId"], ) result["UserPoolClient"]["ClientName"].should.equal(client_name) result["UserPoolClient"]["CallbackURLs"].should.have.length_of(1) result["UserPoolClient"]["CallbackURLs"][0].should.equal(value) @mock_cognitoidp def test_update_user_pool_client(): conn = boto3.client("cognito-idp", "us-west-2") old_client_name = str(uuid.uuid4()) new_client_name = str(uuid.uuid4()) old_value = str(uuid.uuid4()) new_value = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] client_details = conn.create_user_pool_client( UserPoolId=user_pool_id, ClientName=old_client_name, CallbackURLs=[old_value], ) result = conn.update_user_pool_client( UserPoolId=user_pool_id, ClientId=client_details["UserPoolClient"]["ClientId"], ClientName=new_client_name, CallbackURLs=[new_value], ) result["UserPoolClient"]["ClientName"].should.equal(new_client_name) result["UserPoolClient"]["CallbackURLs"].should.have.length_of(1) result["UserPoolClient"]["CallbackURLs"][0].should.equal(new_value) @mock_cognitoidp def test_delete_user_pool_client(): conn = boto3.client("cognito-idp", "us-west-2") user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] client_details = conn.create_user_pool_client( UserPoolId=user_pool_id, ClientName=str(uuid.uuid4()), ) conn.delete_user_pool_client( UserPoolId=user_pool_id, ClientId=client_details["UserPoolClient"]["ClientId"], ) caught = False try: conn.describe_user_pool_client( UserPoolId=user_pool_id, ClientId=client_details["UserPoolClient"]["ClientId"], ) except conn.exceptions.ResourceNotFoundException: caught = True caught.should.be.true @mock_cognitoidp def test_create_identity_provider(): conn = boto3.client("cognito-idp", "us-west-2") provider_name = str(uuid.uuid4()) provider_type = "Facebook" value = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] result = conn.create_identity_provider( UserPoolId=user_pool_id, ProviderName=provider_name, ProviderType=provider_type, ProviderDetails={ "thing": value }, ) result["IdentityProvider"]["UserPoolId"].should.equal(user_pool_id) result["IdentityProvider"]["ProviderName"].should.equal(provider_name) result["IdentityProvider"]["ProviderType"].should.equal(provider_type) result["IdentityProvider"]["ProviderDetails"]["thing"].should.equal(value) @mock_cognitoidp def test_list_identity_providers(): conn = boto3.client("cognito-idp", "us-west-2") provider_name = str(uuid.uuid4()) provider_type = "Facebook" user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.create_identity_provider( UserPoolId=user_pool_id, ProviderName=provider_name, ProviderType=provider_type, ProviderDetails={}, ) result = conn.list_identity_providers( UserPoolId=user_pool_id, MaxResults=10, ) result["Providers"].should.have.length_of(1) result["Providers"][0]["ProviderName"].should.equal(provider_name) result["Providers"][0]["ProviderType"].should.equal(provider_type) @mock_cognitoidp def test_describe_identity_providers(): conn = boto3.client("cognito-idp", "us-west-2") provider_name = str(uuid.uuid4()) provider_type = "Facebook" value = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.create_identity_provider( UserPoolId=user_pool_id, ProviderName=provider_name, ProviderType=provider_type, ProviderDetails={ "thing": value }, ) result = conn.describe_identity_provider( UserPoolId=user_pool_id, ProviderName=provider_name, ) result["IdentityProvider"]["UserPoolId"].should.equal(user_pool_id) result["IdentityProvider"]["ProviderName"].should.equal(provider_name) result["IdentityProvider"]["ProviderType"].should.equal(provider_type) result["IdentityProvider"]["ProviderDetails"]["thing"].should.equal(value) @mock_cognitoidp def test_delete_identity_providers(): conn = boto3.client("cognito-idp", "us-west-2") provider_name = str(uuid.uuid4()) provider_type = "Facebook" value = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.create_identity_provider( UserPoolId=user_pool_id, ProviderName=provider_name, ProviderType=provider_type, ProviderDetails={ "thing": value }, ) conn.delete_identity_provider(UserPoolId=user_pool_id, ProviderName=provider_name) caught = False try: conn.describe_identity_provider( UserPoolId=user_pool_id, ProviderName=provider_name, ) except conn.exceptions.ResourceNotFoundException: caught = True caught.should.be.true @mock_cognitoidp def test_admin_create_user(): conn = boto3.client("cognito-idp", "us-west-2") username = str(uuid.uuid4()) value = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] result = conn.admin_create_user( UserPoolId=user_pool_id, Username=username, UserAttributes=[ {"Name": "thing", "Value": value} ], ) result["User"]["Username"].should.equal(username) result["User"]["UserStatus"].should.equal("FORCE_CHANGE_PASSWORD") result["User"]["Attributes"].should.have.length_of(1) result["User"]["Attributes"][0]["Name"].should.equal("thing") result["User"]["Attributes"][0]["Value"].should.equal(value) result["User"]["Enabled"].should.equal(True) @mock_cognitoidp def test_admin_get_user(): conn = boto3.client("cognito-idp", "us-west-2") username = str(uuid.uuid4()) value = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.admin_create_user( UserPoolId=user_pool_id, Username=username, UserAttributes=[ {"Name": "thing", "Value": value} ], ) result = conn.admin_get_user(UserPoolId=user_pool_id, Username=username) result["Username"].should.equal(username) result["UserAttributes"].should.have.length_of(1) result["UserAttributes"][0]["Name"].should.equal("thing") result["UserAttributes"][0]["Value"].should.equal(value) @mock_cognitoidp def test_admin_get_missing_user(): conn = boto3.client("cognito-idp", "us-west-2") username = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] caught = False try: conn.admin_get_user(UserPoolId=user_pool_id, Username=username) except conn.exceptions.UserNotFoundException: caught = True caught.should.be.true @mock_cognitoidp def test_list_users(): conn = boto3.client("cognito-idp", "us-west-2") username = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.admin_create_user(UserPoolId=user_pool_id, Username=username) result = conn.list_users(UserPoolId=user_pool_id) result["Users"].should.have.length_of(1) result["Users"][0]["Username"].should.equal(username) @mock_cognitoidp def test_admin_disable_user(): conn = boto3.client("cognito-idp", "us-west-2") username = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.admin_create_user(UserPoolId=user_pool_id, Username=username) result = conn.admin_disable_user(UserPoolId=user_pool_id, Username=username) list(result.keys()).should.equal(["ResponseMetadata"]) conn.admin_get_user(UserPoolId=user_pool_id, Username=username) \ ["Enabled"].should.equal(False) @mock_cognitoidp def test_admin_enable_user(): conn = boto3.client("cognito-idp", "us-west-2") username = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.admin_create_user(UserPoolId=user_pool_id, Username=username) conn.admin_disable_user(UserPoolId=user_pool_id, Username=username) result = conn.admin_enable_user(UserPoolId=user_pool_id, Username=username) list(result.keys()).should.equal(["ResponseMetadata"]) conn.admin_get_user(UserPoolId=user_pool_id, Username=username) \ ["Enabled"].should.equal(True) @mock_cognitoidp def test_admin_delete_user(): conn = boto3.client("cognito-idp", "us-west-2") username = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] conn.admin_create_user(UserPoolId=user_pool_id, Username=username) conn.admin_delete_user(UserPoolId=user_pool_id, Username=username) caught = False try: conn.admin_get_user(UserPoolId=user_pool_id, Username=username) except conn.exceptions.UserNotFoundException: caught = True caught.should.be.true def authentication_flow(conn): username = str(uuid.uuid4()) temporary_password = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] user_attribute_name = str(uuid.uuid4()) user_attribute_value = str(uuid.uuid4()) client_id = conn.create_user_pool_client( UserPoolId=user_pool_id, ClientName=str(uuid.uuid4()), ReadAttributes=[user_attribute_name] )["UserPoolClient"]["ClientId"] conn.admin_create_user( UserPoolId=user_pool_id, Username=username, TemporaryPassword=temporary_password, UserAttributes=[{ 'Name': user_attribute_name, 'Value': user_attribute_value }] ) result = conn.admin_initiate_auth( UserPoolId=user_pool_id, ClientId=client_id, AuthFlow="ADMIN_NO_SRP_AUTH", AuthParameters={ "USERNAME": username, "PASSWORD": temporary_password }, ) result["ChallengeName"].should.equal("NEW_PASSWORD_REQUIRED") result["Session"].should_not.be.none new_password = str(uuid.uuid4()) result = conn.respond_to_auth_challenge( Session=result["Session"], ClientId=client_id, ChallengeName="NEW_PASSWORD_REQUIRED", ChallengeResponses={ "USERNAME": username, "NEW_PASSWORD": new_password } ) result["AuthenticationResult"]["IdToken"].should_not.be.none result["AuthenticationResult"]["AccessToken"].should_not.be.none return { "user_pool_id": user_pool_id, "client_id": client_id, "id_token": result["AuthenticationResult"]["IdToken"], "access_token": result["AuthenticationResult"]["AccessToken"], "username": username, "password": new_password, "additional_fields": { user_attribute_name: user_attribute_value } } @mock_cognitoidp def test_authentication_flow(): conn = boto3.client("cognito-idp", "us-west-2") authentication_flow(conn) @mock_cognitoidp def test_token_legitimacy(): conn = boto3.client("cognito-idp", "us-west-2") path = "../../moto/cognitoidp/resources/jwks-public.json" with open(os.path.join(os.path.dirname(__file__), path)) as f: json_web_key = json.loads(f.read())["keys"][0] outputs = authentication_flow(conn) id_token = outputs["id_token"] access_token = outputs["access_token"] client_id = outputs["client_id"] issuer = "https://cognito-idp.us-west-2.amazonaws.com/{}".format(outputs["user_pool_id"]) id_claims = json.loads(jws.verify(id_token, json_web_key, "RS256")) id_claims["iss"].should.equal(issuer) id_claims["aud"].should.equal(client_id) access_claims = json.loads(jws.verify(access_token, json_web_key, "RS256")) access_claims["iss"].should.equal(issuer) access_claims["aud"].should.equal(client_id) for k, v in outputs["additional_fields"].items(): access_claims[k].should.equal(v) @mock_cognitoidp def test_change_password(): conn = boto3.client("cognito-idp", "us-west-2") outputs = authentication_flow(conn) newer_password = str(uuid.uuid4()) conn.change_password( AccessToken=outputs["access_token"], PreviousPassword=outputs["password"], ProposedPassword=newer_password, ) result = conn.admin_initiate_auth( UserPoolId=outputs["user_pool_id"], ClientId=outputs["client_id"], AuthFlow="ADMIN_NO_SRP_AUTH", AuthParameters={ "USERNAME": outputs["username"], "PASSWORD": newer_password, }, ) result["AuthenticationResult"].should_not.be.none @mock_cognitoidp def test_forgot_password(): conn = boto3.client("cognito-idp", "us-west-2") result = conn.forgot_password(ClientId=str(uuid.uuid4()), Username=str(uuid.uuid4())) result["CodeDeliveryDetails"].should_not.be.none @mock_cognitoidp def test_confirm_forgot_password(): conn = boto3.client("cognito-idp", "us-west-2") username = str(uuid.uuid4()) user_pool_id = conn.create_user_pool(PoolName=str(uuid.uuid4()))["UserPool"]["Id"] client_id = conn.create_user_pool_client( UserPoolId=user_pool_id, ClientName=str(uuid.uuid4()), )["UserPoolClient"]["ClientId"] conn.admin_create_user( UserPoolId=user_pool_id, Username=username, TemporaryPassword=str(uuid.uuid4()), ) conn.confirm_forgot_password( ClientId=client_id, Username=username, ConfirmationCode=str(uuid.uuid4()), Password=str(uuid.uuid4()), )
true
true
f72a47612f3599e9c27c19fedb85a488b08046a6
1,760
py
Python
tests/test_buildsets.py
MichalMilewicz/tungsten-ci-dashboard
67ca8e39855009ab7b4d603b691ea910ee6efbbc
[ "Apache-2.0" ]
null
null
null
tests/test_buildsets.py
MichalMilewicz/tungsten-ci-dashboard
67ca8e39855009ab7b4d603b691ea910ee6efbbc
[ "Apache-2.0" ]
null
null
null
tests/test_buildsets.py
MichalMilewicz/tungsten-ci-dashboard
67ca8e39855009ab7b4d603b691ea910ee6efbbc
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- import unittest from unittest.mock import MagicMock, patch from dashboard.exceptions import PageOutOfRange from dashboard.history import BuildSetsPaginated class TestBuildSets(unittest.TestCase): @patch('dashboard.model.ZuulBuildSet.get_for_pipeline') def test_create_buildsets_history_object(self, get_for_pipeline): buildsets = BuildSetsPaginated(pipeline="foo", per_page=20) self.assertEqual(buildsets.per_page, 20) @patch('dashboard.model.ZuulBuildSet.get_for_pipeline') def test_create_query(self, get_for_pipeline): BuildSetsPaginated(pipeline="foo", per_page=20) get_for_pipeline.assert_called_with("foo") @patch('dashboard.model.ZuulBuildSet.get_for_pipeline') def test_fetch_raises_when_page_is_out_of_range(self, get_for_pipeline): get_for_pipeline.return_value = [ 'first_element', 'second_element', 'third_element'] buildsets = BuildSetsPaginated(pipeline="foo", per_page=20) with self.assertRaises(PageOutOfRange): buildsets.fetch_page(2) @patch('dashboard.model.ZuulBuildSet.get_for_pipeline') def test_fetch_set_correct_page(self, get_for_pipeline): data = ['first_element', 'second_element', 'third_element'] query = self._query_mock(data) get_for_pipeline.return_value = query buildset = BuildSetsPaginated(pipeline="foo", per_page=20) buildset.fetch_page(page=1) self.assertEqual(buildset.page, data) query.page.assert_called_with(1, 20) def _query_mock(self, data): query = MagicMock() query.__len__ = lambda x: len(data) query.page = MagicMock() query.page.return_value = data return query
34.509804
76
0.715909
import unittest from unittest.mock import MagicMock, patch from dashboard.exceptions import PageOutOfRange from dashboard.history import BuildSetsPaginated class TestBuildSets(unittest.TestCase): @patch('dashboard.model.ZuulBuildSet.get_for_pipeline') def test_create_buildsets_history_object(self, get_for_pipeline): buildsets = BuildSetsPaginated(pipeline="foo", per_page=20) self.assertEqual(buildsets.per_page, 20) @patch('dashboard.model.ZuulBuildSet.get_for_pipeline') def test_create_query(self, get_for_pipeline): BuildSetsPaginated(pipeline="foo", per_page=20) get_for_pipeline.assert_called_with("foo") @patch('dashboard.model.ZuulBuildSet.get_for_pipeline') def test_fetch_raises_when_page_is_out_of_range(self, get_for_pipeline): get_for_pipeline.return_value = [ 'first_element', 'second_element', 'third_element'] buildsets = BuildSetsPaginated(pipeline="foo", per_page=20) with self.assertRaises(PageOutOfRange): buildsets.fetch_page(2) @patch('dashboard.model.ZuulBuildSet.get_for_pipeline') def test_fetch_set_correct_page(self, get_for_pipeline): data = ['first_element', 'second_element', 'third_element'] query = self._query_mock(data) get_for_pipeline.return_value = query buildset = BuildSetsPaginated(pipeline="foo", per_page=20) buildset.fetch_page(page=1) self.assertEqual(buildset.page, data) query.page.assert_called_with(1, 20) def _query_mock(self, data): query = MagicMock() query.__len__ = lambda x: len(data) query.page = MagicMock() query.page.return_value = data return query
true
true
f72a484fe9c2c76a51236db7ad5259bebcb0d8f6
4,602
py
Python
dataservice/api/outcome/resources.py
ConnorBarnhill/kf-api-dataservice
547df467a307788882469a25c947a14965a26336
[ "Apache-2.0" ]
6
2018-01-25T13:49:24.000Z
2020-03-07T16:25:09.000Z
dataservice/api/outcome/resources.py
ConnorBarnhill/kf-api-dataservice
547df467a307788882469a25c947a14965a26336
[ "Apache-2.0" ]
369
2018-01-17T15:22:18.000Z
2022-03-10T19:14:56.000Z
dataservice/api/outcome/resources.py
ConnorBarnhill/kf-api-dataservice
547df467a307788882469a25c947a14965a26336
[ "Apache-2.0" ]
3
2018-04-11T14:18:37.000Z
2018-10-31T19:09:48.000Z
from flask import abort, request from marshmallow import ValidationError from webargs.flaskparser import use_args from dataservice.extensions import db from dataservice.api.common.pagination import paginated, Pagination from dataservice.api.outcome.models import Outcome from dataservice.api.outcome.schemas import OutcomeSchema from dataservice.api.common.views import CRUDView from dataservice.api.common.schemas import filter_schema_factory class OutcomeListAPI(CRUDView): """ Outcome REST API """ endpoint = 'outcomes_list' rule = '/outcomes' schemas = {'Outcome': OutcomeSchema} @paginated @use_args(filter_schema_factory(OutcomeSchema), locations=('query',)) def get(self, filter_params, after, limit): """ Get all outcomes --- description: Get all outcomes template: path: get_list.yml properties: resource: Outcome """ # Get study id and remove from model filter params study_id = filter_params.pop('study_id', None) q = Outcome.query.filter_by(**filter_params) # Filter by study from dataservice.api.participant.models import Participant if study_id: q = (q.join(Participant.outcomes) .filter(Participant.study_id == study_id)) return (OutcomeSchema(many=True) .jsonify(Pagination(q, after, limit))) def post(self): """ Create a new outcome --- template: path: new_resource.yml properties: resource: Outcome """ body = request.get_json(force=True) # Deserialize try: o = OutcomeSchema(strict=True).load(body).data # Request body not valid except ValidationError as e: abort(400, 'could not create outcome: {}'.format(e.messages)) # Add to and save in database db.session.add(o) db.session.commit() return OutcomeSchema(201, 'outcome {} created' .format(o.kf_id)).jsonify(o), 201 class OutcomeAPI(CRUDView): """ Outcome REST API """ endpoint = 'outcomes' rule = '/outcomes/<string:kf_id>' schemas = {'Outcome': OutcomeSchema} def get(self, kf_id): """ Get a outcome by id --- template: path: get_by_id.yml properties: resource: Outcome """ # Get one o = Outcome.query.get(kf_id) # Not found in database if o is None: abort(404, 'could not find {} `{}`' .format('outcome', kf_id)) return OutcomeSchema().jsonify(o) def patch(self, kf_id): """ Update an existing outcome Allows partial update of resource --- template: path: update_by_id.yml properties: resource: Outcome """ # Check if outcome exists o = Outcome.query.get(kf_id) # Not found in database if o is None: abort(404, 'could not find {} `{}`'.format('outcome', kf_id)) # Partial update - validate but allow missing required fields body = request.get_json(force=True) or {} # Validation only try: o = OutcomeSchema(strict=True).load(body, instance=o, partial=True).data # Request body not valid except ValidationError as e: abort(400, 'could not update outcome: {}'.format(e.messages)) # Save to database db.session.add(o) db.session.commit() return OutcomeSchema(200, 'outcome {} updated' .format(o.kf_id)).jsonify(o), 200 def delete(self, kf_id): """ Delete outcome by id Deletes a outcome given a Kids First id --- template: path: delete_by_id.yml properties: resource: Outcome """ # Check if outcome exists o = Outcome.query.get(kf_id) # Not found in database if o is None: abort(404, 'could not find {} `{}`'.format('outcome', kf_id)) # Save in database db.session.delete(o) db.session.commit() return OutcomeSchema(200, 'outcome {} deleted' .format(o.kf_id)).jsonify(o), 200
27.556886
73
0.548457
from flask import abort, request from marshmallow import ValidationError from webargs.flaskparser import use_args from dataservice.extensions import db from dataservice.api.common.pagination import paginated, Pagination from dataservice.api.outcome.models import Outcome from dataservice.api.outcome.schemas import OutcomeSchema from dataservice.api.common.views import CRUDView from dataservice.api.common.schemas import filter_schema_factory class OutcomeListAPI(CRUDView): endpoint = 'outcomes_list' rule = '/outcomes' schemas = {'Outcome': OutcomeSchema} @paginated @use_args(filter_schema_factory(OutcomeSchema), locations=('query',)) def get(self, filter_params, after, limit): study_id = filter_params.pop('study_id', None) q = Outcome.query.filter_by(**filter_params) from dataservice.api.participant.models import Participant if study_id: q = (q.join(Participant.outcomes) .filter(Participant.study_id == study_id)) return (OutcomeSchema(many=True) .jsonify(Pagination(q, after, limit))) def post(self): body = request.get_json(force=True) try: o = OutcomeSchema(strict=True).load(body).data except ValidationError as e: abort(400, 'could not create outcome: {}'.format(e.messages)) db.session.add(o) db.session.commit() return OutcomeSchema(201, 'outcome {} created' .format(o.kf_id)).jsonify(o), 201 class OutcomeAPI(CRUDView): endpoint = 'outcomes' rule = '/outcomes/<string:kf_id>' schemas = {'Outcome': OutcomeSchema} def get(self, kf_id): o = Outcome.query.get(kf_id) if o is None: abort(404, 'could not find {} `{}`' .format('outcome', kf_id)) return OutcomeSchema().jsonify(o) def patch(self, kf_id): o = Outcome.query.get(kf_id) if o is None: abort(404, 'could not find {} `{}`'.format('outcome', kf_id)) body = request.get_json(force=True) or {} try: o = OutcomeSchema(strict=True).load(body, instance=o, partial=True).data except ValidationError as e: abort(400, 'could not update outcome: {}'.format(e.messages)) db.session.add(o) db.session.commit() return OutcomeSchema(200, 'outcome {} updated' .format(o.kf_id)).jsonify(o), 200 def delete(self, kf_id): o = Outcome.query.get(kf_id) if o is None: abort(404, 'could not find {} `{}`'.format('outcome', kf_id)) db.session.delete(o) db.session.commit() return OutcomeSchema(200, 'outcome {} deleted' .format(o.kf_id)).jsonify(o), 200
true
true
f72a48ddc595ceca85ebaf70bdc5761b2632240d
630
py
Python
level.py
FernandoCamousseigt/testapp
d7466584f5eb5c96463178c21ede571d6ea33510
[ "MIT" ]
null
null
null
level.py
FernandoCamousseigt/testapp
d7466584f5eb5c96463178c21ede571d6ea33510
[ "MIT" ]
null
null
null
level.py
FernandoCamousseigt/testapp
d7466584f5eb5c96463178c21ede571d6ea33510
[ "MIT" ]
null
null
null
def choose_level(n_pregunta, p_level): # Construir lógica para escoger el nivel ################################################## #pass if n_pregunta <= int(p_level): level = "basicas" elif n_pregunta <= 2 * p_level: level = "intermedias" else: level = "avanzadas" ################################################## return level if __name__ == '__main__': # verificar resultados print(choose_level(2, 2)) # básicas print(choose_level(3, 2)) # intermedias print(choose_level(7, 2)) # avanzadas print(choose_level(4, 3)) # intermedias
27.391304
54
0.509524
def choose_level(n_pregunta, p_level):
true
true
f72a4969cc9a1aedd1ca60e296ba23ac682ec15b
3,433
py
Python
verde/tests/test_scipy.py
djhoese/verde
ad14acf94717ee5c6672559f40576f65989753a5
[ "BSD-3-Clause" ]
null
null
null
verde/tests/test_scipy.py
djhoese/verde
ad14acf94717ee5c6672559f40576f65989753a5
[ "BSD-3-Clause" ]
null
null
null
verde/tests/test_scipy.py
djhoese/verde
ad14acf94717ee5c6672559f40576f65989753a5
[ "BSD-3-Clause" ]
null
null
null
""" Test the scipy based interpolator. """ import warnings import pytest import pandas as pd import numpy as np import numpy.testing as npt from ..scipygridder import ScipyGridder from ..coordinates import grid_coordinates from ..datasets.synthetic import CheckerBoard def test_scipy_gridder_same_points(): "See if the gridder recovers known points." region = (1000, 5000, -8000, -7000) synth = CheckerBoard(region=region) data = synth.scatter(size=1000, random_state=0) coords = (data.easting, data.northing) # The interpolation should be perfect on top of the data points for method in ["nearest", "linear", "cubic"]: grd = ScipyGridder(method=method) grd.fit(coords, data.scalars) predicted = grd.predict(coords) npt.assert_allclose(predicted, data.scalars) npt.assert_allclose(grd.score(coords, data.scalars), 1) def test_scipy_gridder(): "See if the gridder recovers known points." synth = CheckerBoard(region=(1000, 5000, -8000, -6000)) data = synth.scatter(size=20000, random_state=0) coords = (data.easting, data.northing) pt_coords = (3000, -7000) true_data = synth.predict(pt_coords) # nearest will never be too close to the truth grd = ScipyGridder("cubic").fit(coords, data.scalars) npt.assert_almost_equal(grd.predict(pt_coords), true_data, decimal=2) grd = ScipyGridder("linear").fit(coords, data.scalars) npt.assert_almost_equal(grd.predict(pt_coords), true_data, decimal=1) def test_scipy_gridder_region(): "See if the region is gotten from the data is correct." region = (1000, 5000, -8000, -6000) synth = CheckerBoard(region=region) # Test using xarray objects grid = synth.grid() coords = grid_coordinates(region, grid.scalars.shape) grd = ScipyGridder().fit(coords, grid.scalars) npt.assert_allclose(grd.region_, region) # Test using pandas objects data = pd.DataFrame( { "easting": coords[0].ravel(), "northing": coords[1].ravel(), "scalars": grid.scalars.values.ravel(), } ) grd = ScipyGridder().fit((data.easting, data.northing), data.scalars) npt.assert_allclose(grd.region_, region) def test_scipy_gridder_extra_args(): "Passing in extra arguments to scipy" data = CheckerBoard().scatter(random_state=100) coords = (data.easting, data.northing) grd = ScipyGridder(method="linear", extra_args=dict(rescale=True)) grd.fit(coords, data.scalars) predicted = grd.predict(coords) npt.assert_allclose(predicted, data.scalars) def test_scipy_gridder_fails(): "fit should fail for invalid method name" data = CheckerBoard().scatter(random_state=0) grd = ScipyGridder(method="some invalid method name") with pytest.raises(ValueError): grd.fit((data.easting, data.northing), data.scalars) def test_scipy_gridder_warns(): "Check that a warning is issued when using weights." data = CheckerBoard().scatter(random_state=100) weights = np.ones_like(data.scalars) grd = ScipyGridder() msg = "ScipyGridder does not support weights and they will be ignored." with warnings.catch_warnings(record=True) as warn: grd.fit((data.easting, data.northing), data.scalars, weights=weights) assert len(warn) == 1 assert issubclass(warn[-1].category, UserWarning) assert str(warn[-1].message) == msg
36.136842
77
0.696767
import warnings import pytest import pandas as pd import numpy as np import numpy.testing as npt from ..scipygridder import ScipyGridder from ..coordinates import grid_coordinates from ..datasets.synthetic import CheckerBoard def test_scipy_gridder_same_points(): region = (1000, 5000, -8000, -7000) synth = CheckerBoard(region=region) data = synth.scatter(size=1000, random_state=0) coords = (data.easting, data.northing) for method in ["nearest", "linear", "cubic"]: grd = ScipyGridder(method=method) grd.fit(coords, data.scalars) predicted = grd.predict(coords) npt.assert_allclose(predicted, data.scalars) npt.assert_allclose(grd.score(coords, data.scalars), 1) def test_scipy_gridder(): synth = CheckerBoard(region=(1000, 5000, -8000, -6000)) data = synth.scatter(size=20000, random_state=0) coords = (data.easting, data.northing) pt_coords = (3000, -7000) true_data = synth.predict(pt_coords) grd = ScipyGridder("cubic").fit(coords, data.scalars) npt.assert_almost_equal(grd.predict(pt_coords), true_data, decimal=2) grd = ScipyGridder("linear").fit(coords, data.scalars) npt.assert_almost_equal(grd.predict(pt_coords), true_data, decimal=1) def test_scipy_gridder_region(): region = (1000, 5000, -8000, -6000) synth = CheckerBoard(region=region) grid = synth.grid() coords = grid_coordinates(region, grid.scalars.shape) grd = ScipyGridder().fit(coords, grid.scalars) npt.assert_allclose(grd.region_, region) data = pd.DataFrame( { "easting": coords[0].ravel(), "northing": coords[1].ravel(), "scalars": grid.scalars.values.ravel(), } ) grd = ScipyGridder().fit((data.easting, data.northing), data.scalars) npt.assert_allclose(grd.region_, region) def test_scipy_gridder_extra_args(): data = CheckerBoard().scatter(random_state=100) coords = (data.easting, data.northing) grd = ScipyGridder(method="linear", extra_args=dict(rescale=True)) grd.fit(coords, data.scalars) predicted = grd.predict(coords) npt.assert_allclose(predicted, data.scalars) def test_scipy_gridder_fails(): data = CheckerBoard().scatter(random_state=0) grd = ScipyGridder(method="some invalid method name") with pytest.raises(ValueError): grd.fit((data.easting, data.northing), data.scalars) def test_scipy_gridder_warns(): data = CheckerBoard().scatter(random_state=100) weights = np.ones_like(data.scalars) grd = ScipyGridder() msg = "ScipyGridder does not support weights and they will be ignored." with warnings.catch_warnings(record=True) as warn: grd.fit((data.easting, data.northing), data.scalars, weights=weights) assert len(warn) == 1 assert issubclass(warn[-1].category, UserWarning) assert str(warn[-1].message) == msg
true
true
f72a4a1445d38081650f42268e4ec5cd183fd71f
776
py
Python
test/azure/Expected/AcceptanceTests/Lro/lro/__init__.py
tasherif-msft/autorest.python
5b0121bcfa802aedaeda36990e8bcaa2b7e26b14
[ "MIT" ]
null
null
null
test/azure/Expected/AcceptanceTests/Lro/lro/__init__.py
tasherif-msft/autorest.python
5b0121bcfa802aedaeda36990e8bcaa2b7e26b14
[ "MIT" ]
null
null
null
test/azure/Expected/AcceptanceTests/Lro/lro/__init__.py
tasherif-msft/autorest.python
5b0121bcfa802aedaeda36990e8bcaa2b7e26b14
[ "MIT" ]
null
null
null
# 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. # -------------------------------------------------------------------------- from ._auto_rest_long_running_operation_test_service import AutoRestLongRunningOperationTestService from ._version import VERSION __version__ = VERSION __all__ = ['AutoRestLongRunningOperationTestService'] try: from ._patch import patch_sdk # type: ignore patch_sdk() except ImportError: pass
38.8
99
0.641753
from ._auto_rest_long_running_operation_test_service import AutoRestLongRunningOperationTestService from ._version import VERSION __version__ = VERSION __all__ = ['AutoRestLongRunningOperationTestService'] try: from ._patch import patch_sdk patch_sdk() except ImportError: pass
true
true
f72a4bc72168d2050ab7b6bbeddb4ba77db329b8
5,324
py
Python
python_modules/libraries/dagster-mssql/dagster_mssql/utils.py
nc-sika/dagster
ee56ee6ee26eb25cb03dd229716ed9af2cad0538
[ "Apache-2.0" ]
null
null
null
python_modules/libraries/dagster-mssql/dagster_mssql/utils.py
nc-sika/dagster
ee56ee6ee26eb25cb03dd229716ed9af2cad0538
[ "Apache-2.0" ]
null
null
null
python_modules/libraries/dagster-mssql/dagster_mssql/utils.py
nc-sika/dagster
ee56ee6ee26eb25cb03dd229716ed9af2cad0538
[ "Apache-2.0" ]
null
null
null
import logging import time import urllib from contextlib import contextmanager import pyodbc import sqlalchemy as db from dagster import Field, IntSource, StringSource, check from dagster.core.storage.sql import get_alembic_config, handle_schema_errors from sqlalchemy.ext.compiler import compiles MSSQL_POOL_RECYCLE = 3600 class DagsterMSSQLException(Exception): pass def mssql_config(): return { "mssql_url": Field(StringSource, is_required=False), "mssql_db": Field( { "username": StringSource, "password": StringSource, "hostname": StringSource, "db_name": StringSource, "port": Field(IntSource, is_required=False, default_value=1433), "driver": Field(StringSource, is_required=False, default_value="{ODBC Driver 17 for SQL Server}"), "driver_opts": Field(StringSource, is_required=False, default_value="") }, is_required=False, ), "should_autocreate_tables": Field(bool, is_required=False, default_value=True), } def mssql_url_from_config(config_value): if config_value.get("mssql_url"): check.invariant( not "mssql_db" in config_value, "mssql storage config must have exactly one of `mssql_url` or `mssql_db`", ) return config_value["mssql_url"] else: check.invariant( "mssql_db" in config_value, "mssql storage config must have exactly one of `mssql_url` or `mssql_db`", ) return get_conn_string(**config_value["mssql_db"]) def get_conn_string(username, password, hostname, db_name, port="1433", driver="{ODBC Driver 17 for SQL Server}", driver_opts=""): params = urllib.parse.quote_plus(f"DRIVER={driver};" f"SERVER={hostname};" f"DATABASE={db_name};" f"UID={username};" f"PWD={password};" f"PORT={port};" f"{driver_opts}") return f"mssql+pyodbc:///?odbc_connect={params}" def retry_mssql_creation_fn(fn, retry_limit=5, retry_wait=0.2): # Retry logic to recover from the case where two processes are creating # tables at the same time using sqlalchemy check.callable_param(fn, "fn") check.int_param(retry_limit, "retry_limit") check.numeric_param(retry_wait, "retry_wait") while True: try: return fn() except ( pyodbc.ProgrammingError, pyodbc.IntegrityError, db.exc.ProgrammingError, db.exc.IntegrityError, ) as exc: logging.warning("Retrying failed database creation") if retry_limit == 0: raise DagsterMSSQLException("too many retries for DB creation") from exc time.sleep(retry_wait) retry_limit -= 1 def retry_mssql_connection_fn(fn, retry_limit=5, retry_wait=0.2): """Reusable retry logic for any MSSQL connection functions that may fail. Intended to be used anywhere we connect to MSSQL, to gracefully handle transient connection issues. """ check.callable_param(fn, "fn") check.int_param(retry_limit, "retry_limit") check.numeric_param(retry_wait, "retry_wait") while True: try: return fn() except ( pyodbc.DatabaseError, pyodbc.OperationalError, db.exc.DatabaseError, db.exc.OperationalError, ) as exc: logging.warning("Retrying failed database connection") if retry_limit == 0: raise DagsterMSSQLException("too many retries for DB connection") from exc time.sleep(retry_wait) retry_limit -= 1 def wait_for_connection(conn_string, retry_limit=5, retry_wait=0.2): retry_mssql_connection_fn( lambda: pyodbc.connect(conn_string), retry_limit=retry_limit, retry_wait=retry_wait, ) return True def mssql_alembic_config(dunder_file): return get_alembic_config( dunder_file, config_path="../alembic/alembic.ini", script_path="../alembic/" ) @contextmanager def create_mssql_connection(engine, dunder_file, storage_type_desc=None): check.inst_param(engine, "engine", db.engine.Engine) check.str_param(dunder_file, "dunder_file") check.opt_str_param(storage_type_desc, "storage_type_desc", "") if storage_type_desc: storage_type_desc += " " else: storage_type_desc = "" conn = None try: # Retry connection to gracefully handle transient connection issues conn = retry_mssql_connection_fn(engine.connect) with handle_schema_errors( conn, mssql_alembic_config(dunder_file), msg="MSSQL {}storage requires migration".format(storage_type_desc), ): yield conn finally: if conn: conn.close() @compiles(db.types.TIMESTAMP, "mssql") def compile_timestamp_mssql(_element, _compiler, **_kw): return f"DATETIME2" @compiles(db.DateTime, "mssql") def compile_datetime_mssql(_element, _compiler, **_kw): return f"DATETIME2"
32.072289
114
0.628475
import logging import time import urllib from contextlib import contextmanager import pyodbc import sqlalchemy as db from dagster import Field, IntSource, StringSource, check from dagster.core.storage.sql import get_alembic_config, handle_schema_errors from sqlalchemy.ext.compiler import compiles MSSQL_POOL_RECYCLE = 3600 class DagsterMSSQLException(Exception): pass def mssql_config(): return { "mssql_url": Field(StringSource, is_required=False), "mssql_db": Field( { "username": StringSource, "password": StringSource, "hostname": StringSource, "db_name": StringSource, "port": Field(IntSource, is_required=False, default_value=1433), "driver": Field(StringSource, is_required=False, default_value="{ODBC Driver 17 for SQL Server}"), "driver_opts": Field(StringSource, is_required=False, default_value="") }, is_required=False, ), "should_autocreate_tables": Field(bool, is_required=False, default_value=True), } def mssql_url_from_config(config_value): if config_value.get("mssql_url"): check.invariant( not "mssql_db" in config_value, "mssql storage config must have exactly one of `mssql_url` or `mssql_db`", ) return config_value["mssql_url"] else: check.invariant( "mssql_db" in config_value, "mssql storage config must have exactly one of `mssql_url` or `mssql_db`", ) return get_conn_string(**config_value["mssql_db"]) def get_conn_string(username, password, hostname, db_name, port="1433", driver="{ODBC Driver 17 for SQL Server}", driver_opts=""): params = urllib.parse.quote_plus(f"DRIVER={driver};" f"SERVER={hostname};" f"DATABASE={db_name};" f"UID={username};" f"PWD={password};" f"PORT={port};" f"{driver_opts}") return f"mssql+pyodbc:///?odbc_connect={params}" def retry_mssql_creation_fn(fn, retry_limit=5, retry_wait=0.2): check.callable_param(fn, "fn") check.int_param(retry_limit, "retry_limit") check.numeric_param(retry_wait, "retry_wait") while True: try: return fn() except ( pyodbc.ProgrammingError, pyodbc.IntegrityError, db.exc.ProgrammingError, db.exc.IntegrityError, ) as exc: logging.warning("Retrying failed database creation") if retry_limit == 0: raise DagsterMSSQLException("too many retries for DB creation") from exc time.sleep(retry_wait) retry_limit -= 1 def retry_mssql_connection_fn(fn, retry_limit=5, retry_wait=0.2): check.callable_param(fn, "fn") check.int_param(retry_limit, "retry_limit") check.numeric_param(retry_wait, "retry_wait") while True: try: return fn() except ( pyodbc.DatabaseError, pyodbc.OperationalError, db.exc.DatabaseError, db.exc.OperationalError, ) as exc: logging.warning("Retrying failed database connection") if retry_limit == 0: raise DagsterMSSQLException("too many retries for DB connection") from exc time.sleep(retry_wait) retry_limit -= 1 def wait_for_connection(conn_string, retry_limit=5, retry_wait=0.2): retry_mssql_connection_fn( lambda: pyodbc.connect(conn_string), retry_limit=retry_limit, retry_wait=retry_wait, ) return True def mssql_alembic_config(dunder_file): return get_alembic_config( dunder_file, config_path="../alembic/alembic.ini", script_path="../alembic/" ) @contextmanager def create_mssql_connection(engine, dunder_file, storage_type_desc=None): check.inst_param(engine, "engine", db.engine.Engine) check.str_param(dunder_file, "dunder_file") check.opt_str_param(storage_type_desc, "storage_type_desc", "") if storage_type_desc: storage_type_desc += " " else: storage_type_desc = "" conn = None try: conn = retry_mssql_connection_fn(engine.connect) with handle_schema_errors( conn, mssql_alembic_config(dunder_file), msg="MSSQL {}storage requires migration".format(storage_type_desc), ): yield conn finally: if conn: conn.close() @compiles(db.types.TIMESTAMP, "mssql") def compile_timestamp_mssql(_element, _compiler, **_kw): return f"DATETIME2" @compiles(db.DateTime, "mssql") def compile_datetime_mssql(_element, _compiler, **_kw): return f"DATETIME2"
true
true
f72a4bffa2fd94ea50df6697d9321a5dbb611f66
5,120
py
Python
instrumentation/opentelemetry-instrumentation-elasticsearch/src/opentelemetry/instrumentation/elasticsearch/__init__.py
willarmiros/opentelemetry-python-contrib
0d34ef26b75f9a3bc275bf828b5a806d39ba1a40
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
instrumentation/opentelemetry-instrumentation-elasticsearch/src/opentelemetry/instrumentation/elasticsearch/__init__.py
willarmiros/opentelemetry-python-contrib
0d34ef26b75f9a3bc275bf828b5a806d39ba1a40
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
instrumentation/opentelemetry-instrumentation-elasticsearch/src/opentelemetry/instrumentation/elasticsearch/__init__.py
willarmiros/opentelemetry-python-contrib
0d34ef26b75f9a3bc275bf828b5a806d39ba1a40
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
# Copyright The OpenTelemetry Authors # # 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. """ This library allows tracing HTTP elasticsearch made by the `elasticsearch <https://elasticsearch-py.readthedocs.io/en/master/>`_ library. Usage ----- .. code-block:: python from opentelemetry.instrumentation.elasticsearch import ElasticsearchInstrumentor import elasticsearch # instrument elasticsearch ElasticsearchInstrumentor().instrument() # Using elasticsearch as normal now will automatically generate spans es = elasticsearch.Elasticsearch() es.index(index='my-index', doc_type='my-type', id=1, body={'my': 'data', 'timestamp': datetime.now()}) es.get(index='my-index', doc_type='my-type', id=1) API --- Elasticsearch instrumentation prefixes operation names with the string "Elasticsearch". This can be changed to a different string by either setting the `OTEL_PYTHON_ELASTICSEARCH_NAME_PREFIX` environment variable or by passing the prefix as an argument to the instrumentor. For example, .. code-block:: python ElasticsearchInstrumentor("my-custom-prefix").instrument() """ from logging import getLogger from os import environ from typing import Collection import elasticsearch import elasticsearch.exceptions from wrapt import wrap_function_wrapper as _wrap from opentelemetry.instrumentation.elasticsearch.package import _instruments from opentelemetry.instrumentation.elasticsearch.version import __version__ from opentelemetry.instrumentation.instrumentor import BaseInstrumentor from opentelemetry.instrumentation.utils import unwrap from opentelemetry.semconv.trace import SpanAttributes from opentelemetry.trace import SpanKind, get_tracer logger = getLogger(__name__) # Values to add as tags from the actual # payload returned by Elasticsearch, if any. _ATTRIBUTES_FROM_RESULT = [ "found", "timed_out", "took", ] _DEFALT_OP_NAME = "request" class ElasticsearchInstrumentor(BaseInstrumentor): """An instrumentor for elasticsearch See `BaseInstrumentor` """ def __init__(self, span_name_prefix=None): if not span_name_prefix: span_name_prefix = environ.get( "OTEL_PYTHON_ELASTICSEARCH_NAME_PREFIX", "Elasticsearch", ) self._span_name_prefix = span_name_prefix.strip() super().__init__() def instrumentation_dependencies(self) -> Collection[str]: return _instruments def _instrument(self, **kwargs): """ Instruments elasticsarch module """ tracer_provider = kwargs.get("tracer_provider") tracer = get_tracer(__name__, __version__, tracer_provider) _wrap( elasticsearch, "Transport.perform_request", _wrap_perform_request(tracer, self._span_name_prefix), ) def _uninstrument(self, **kwargs): unwrap(elasticsearch.Transport, "perform_request") def _wrap_perform_request(tracer, span_name_prefix): # pylint: disable=R0912 def wrapper(wrapped, _, args, kwargs): method = url = None try: method, url, *_ = args except IndexError: logger.warning( "expected perform_request to receive two positional arguments. " "Got %d", len(args), ) op_name = span_name_prefix + (url or method or _DEFALT_OP_NAME) params = kwargs.get("params", {}) body = kwargs.get("body", None) with tracer.start_as_current_span( op_name, kind=SpanKind.CLIENT, ) as span: if span.is_recording(): attributes = { SpanAttributes.DB_SYSTEM: "elasticsearch", } if url: attributes["elasticsearch.url"] = url if method: attributes["elasticsearch.method"] = method if body: attributes[SpanAttributes.DB_STATEMENT] = str(body) if params: attributes["elasticsearch.params"] = str(params) for key, value in attributes.items(): span.set_attribute(key, value) rv = wrapped(*args, **kwargs) if isinstance(rv, dict) and span.is_recording(): for member in _ATTRIBUTES_FROM_RESULT: if member in rv: span.set_attribute( "elasticsearch.{0}".format(member), str(rv[member]), ) return rv return wrapper
32.820513
106
0.659766
from logging import getLogger from os import environ from typing import Collection import elasticsearch import elasticsearch.exceptions from wrapt import wrap_function_wrapper as _wrap from opentelemetry.instrumentation.elasticsearch.package import _instruments from opentelemetry.instrumentation.elasticsearch.version import __version__ from opentelemetry.instrumentation.instrumentor import BaseInstrumentor from opentelemetry.instrumentation.utils import unwrap from opentelemetry.semconv.trace import SpanAttributes from opentelemetry.trace import SpanKind, get_tracer logger = getLogger(__name__) _ATTRIBUTES_FROM_RESULT = [ "found", "timed_out", "took", ] _DEFALT_OP_NAME = "request" class ElasticsearchInstrumentor(BaseInstrumentor): def __init__(self, span_name_prefix=None): if not span_name_prefix: span_name_prefix = environ.get( "OTEL_PYTHON_ELASTICSEARCH_NAME_PREFIX", "Elasticsearch", ) self._span_name_prefix = span_name_prefix.strip() super().__init__() def instrumentation_dependencies(self) -> Collection[str]: return _instruments def _instrument(self, **kwargs): tracer_provider = kwargs.get("tracer_provider") tracer = get_tracer(__name__, __version__, tracer_provider) _wrap( elasticsearch, "Transport.perform_request", _wrap_perform_request(tracer, self._span_name_prefix), ) def _uninstrument(self, **kwargs): unwrap(elasticsearch.Transport, "perform_request") def _wrap_perform_request(tracer, span_name_prefix): def wrapper(wrapped, _, args, kwargs): method = url = None try: method, url, *_ = args except IndexError: logger.warning( "expected perform_request to receive two positional arguments. " "Got %d", len(args), ) op_name = span_name_prefix + (url or method or _DEFALT_OP_NAME) params = kwargs.get("params", {}) body = kwargs.get("body", None) with tracer.start_as_current_span( op_name, kind=SpanKind.CLIENT, ) as span: if span.is_recording(): attributes = { SpanAttributes.DB_SYSTEM: "elasticsearch", } if url: attributes["elasticsearch.url"] = url if method: attributes["elasticsearch.method"] = method if body: attributes[SpanAttributes.DB_STATEMENT] = str(body) if params: attributes["elasticsearch.params"] = str(params) for key, value in attributes.items(): span.set_attribute(key, value) rv = wrapped(*args, **kwargs) if isinstance(rv, dict) and span.is_recording(): for member in _ATTRIBUTES_FROM_RESULT: if member in rv: span.set_attribute( "elasticsearch.{0}".format(member), str(rv[member]), ) return rv return wrapper
true
true
f72a4c06bbd80f8c7dad227a0878c7eb28b2829d
7,421
py
Python
examples/ex_binding_textures.py
SebastianRodriguezR/grafica
c87d6d1906a4cf49520ef213f1e4ba6e1ead8c4e
[ "MIT" ]
12
2021-08-17T12:57:39.000Z
2022-03-28T02:52:30.000Z
examples/ex_binding_textures.py
SebastianRodriguezR/grafica
c87d6d1906a4cf49520ef213f1e4ba6e1ead8c4e
[ "MIT" ]
null
null
null
examples/ex_binding_textures.py
SebastianRodriguezR/grafica
c87d6d1906a4cf49520ef213f1e4ba6e1ead8c4e
[ "MIT" ]
13
2021-08-17T03:23:21.000Z
2022-03-20T21:40:16.000Z
# coding=utf-8 """Using 2 different textures in the same Fragment Shader""" import glfw from OpenGL.GL import * import OpenGL.GL.shaders import numpy as np import sys import os.path sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import grafica.transformations as tr import grafica.basic_shapes as bs import grafica.easy_shaders as es from grafica.assets_path import getAssetPath from grafica.gpu_shape import GPUShape, SIZE_IN_BYTES __author__ = "Sebastián Olmos" __license__ = "MIT" # We extend the functionality of a GPUShape with an additional texture. class TexGPUShape(GPUShape): def __init__(self): """VAO, VBO, EBO and texture handlers to GPU memory""" super().__init__() self.texture2 = None def __str__(self): return super().__str__() + " tex=" + str(self.texture2) def clear(self): """Freeing GPU memory""" super().clear() if self.texture2 != None: glDeleteTextures(1, [self.texture2]) # Shader that handles two textures class DoubleTextureTransformShaderProgram: def __init__(self): vertex_shader = """ #version 330 uniform mat4 transform; in vec3 position; in vec2 texCoords; out vec2 outTexCoords; void main() { gl_Position = transform * vec4(position, 1.0f); outTexCoords = texCoords; } """ fragment_shader = """ #version 330 // gl_FragCoord contains the (x,y) fragment coordinates of the window. // We also set the origin to the upper left corner layout(origin_upper_left) in vec4 gl_FragCoord; in vec2 outTexCoords; out vec4 outColor; uniform sampler2D upTexture; uniform sampler2D downTexture; uniform float mousePosY; void main() { vec4 finalColor; if ( gl_FragCoord.y > mousePosY){ finalColor = texture(downTexture, outTexCoords); } else { finalColor = texture(upTexture, outTexCoords); } outColor = finalColor; } """ # Binding artificial vertex array object for validation VAO = glGenVertexArrays(1) glBindVertexArray(VAO) # Compiling our shader program self.shaderProgram = OpenGL.GL.shaders.compileProgram( OpenGL.GL.shaders.compileShader(vertex_shader, GL_VERTEX_SHADER), OpenGL.GL.shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER)) def setupVAO(self, gpuShape): glBindVertexArray(gpuShape.vao) glBindBuffer(GL_ARRAY_BUFFER, gpuShape.vbo) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, gpuShape.ebo) # 3d vertices + 2d texture coordinates => 3*4 + 2*4 = 20 bytes position = glGetAttribLocation(self.shaderProgram, "position") glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, 20, ctypes.c_void_p(0)) glEnableVertexAttribArray(position) texCoords = glGetAttribLocation(self.shaderProgram, "texCoords") glVertexAttribPointer(texCoords, 2, GL_FLOAT, GL_FALSE, 20, ctypes.c_void_p(3 * SIZE_IN_BYTES)) glEnableVertexAttribArray(texCoords) # Unbinding current vao glBindVertexArray(0) def drawCall(self, gpuShape, mode=GL_TRIANGLES): assert isinstance(gpuShape, TexGPUShape) glBindVertexArray(gpuShape.vao) # Binding the first texture glActiveTexture(GL_TEXTURE0 + 0) glBindTexture(GL_TEXTURE_2D, gpuShape.texture) # Binding the second texture glActiveTexture(GL_TEXTURE0 + 1) glBindTexture(GL_TEXTURE_2D, gpuShape.texture2) glDrawElements(mode, gpuShape.size, GL_UNSIGNED_INT, None) # Unbind the current VAO glBindVertexArray(0) # A class to store the application control class Controller: def __init__(self): self.fillPolygon = True self.mousePos = (0.0, 0.0) # global controller as communication with the callback function controller = Controller() def on_key(window, key, scancode, action, mods): if action != glfw.PRESS: return global controller if key == glfw.KEY_SPACE: controller.fillPolygon = not controller.fillPolygon elif key == glfw.KEY_ESCAPE: glfw.set_window_should_close(window, True) else: print('Unknown key') def cursor_pos_callback(window, x, y): global controller controller.mousePos = (x,y) if __name__ == "__main__": # Initialize glfw if not glfw.init(): sys.exit(1) width = 600 height = 600 window = glfw.create_window(width, height, "Double binding", None, None) if not window: glfw.terminate() glfw.set_window_should_close(window, True) glfw.make_context_current(window) # Connecting the callback function 'on_key' to handle keyboard events glfw.set_key_callback(window, on_key) glfw.set_cursor_pos_callback(window, cursor_pos_callback) # A simple shader program with position and texture coordinates as inputs. pipeline = DoubleTextureTransformShaderProgram() # Telling OpenGL to use our shader program # Setting up the clear screen color glClearColor(0.25, 0.25, 0.25, 1.0) # Creating shapes on GPU memory shape = bs.createTextureQuad(1, 1) gpuShape = TexGPUShape().initBuffers() pipeline.setupVAO(gpuShape) gpuShape.fillBuffers(shape.vertices, shape.indices, GL_STATIC_DRAW) gpuShape.texture = es.textureSimpleSetup( getAssetPath("torres-del-paine-sq.jpg"), GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, GL_LINEAR, GL_LINEAR) gpuShape.texture2 = es.textureSimpleSetup( getAssetPath("red_woodpecker.jpg"), GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, GL_LINEAR, GL_LINEAR) currentMousePos = [width/2, height/2] while not glfw.window_should_close(window): # Using GLFW to check for input events glfw.poll_events() if (controller.fillPolygon): glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) else: glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) theta = 0.3 * np.sin(glfw.get_time()) # Clearing the screen in both, color and depth glClear(GL_COLOR_BUFFER_BIT) glUseProgram(pipeline.shaderProgram) # Drawing the shapes glUniformMatrix4fv(glGetUniformLocation(pipeline.shaderProgram, "transform"), 1, GL_TRUE, np.matmul( tr.shearing(0,theta,0,0,0,0), tr.uniformScale(1.5) ) ) # Binding samplers to both texture units glUniform1i(glGetUniformLocation(pipeline.shaderProgram, "upTexture"), 0) glUniform1i(glGetUniformLocation(pipeline.shaderProgram, "downTexture"), 1) # Sending the mouse vertical location to our shader glUniform1f(glGetUniformLocation(pipeline.shaderProgram, "mousePosY"), controller.mousePos[1]) pipeline.drawCall(gpuShape) # Once the render is done, buffers are swapped, showing only the complete scene. glfw.swap_buffers(window) # freeing GPU memory gpuShape.clear() glfw.terminate()
30.413934
106
0.650721
import glfw from OpenGL.GL import * import OpenGL.GL.shaders import numpy as np import sys import os.path sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import grafica.transformations as tr import grafica.basic_shapes as bs import grafica.easy_shaders as es from grafica.assets_path import getAssetPath from grafica.gpu_shape import GPUShape, SIZE_IN_BYTES __author__ = "Sebastián Olmos" __license__ = "MIT" class TexGPUShape(GPUShape): def __init__(self): super().__init__() self.texture2 = None def __str__(self): return super().__str__() + " tex=" + str(self.texture2) def clear(self): super().clear() if self.texture2 != None: glDeleteTextures(1, [self.texture2]) class DoubleTextureTransformShaderProgram: def __init__(self): vertex_shader = """ #version 330 uniform mat4 transform; in vec3 position; in vec2 texCoords; out vec2 outTexCoords; void main() { gl_Position = transform * vec4(position, 1.0f); outTexCoords = texCoords; } """ fragment_shader = """ #version 330 // gl_FragCoord contains the (x,y) fragment coordinates of the window. // We also set the origin to the upper left corner layout(origin_upper_left) in vec4 gl_FragCoord; in vec2 outTexCoords; out vec4 outColor; uniform sampler2D upTexture; uniform sampler2D downTexture; uniform float mousePosY; void main() { vec4 finalColor; if ( gl_FragCoord.y > mousePosY){ finalColor = texture(downTexture, outTexCoords); } else { finalColor = texture(upTexture, outTexCoords); } outColor = finalColor; } """ VAO = glGenVertexArrays(1) glBindVertexArray(VAO) self.shaderProgram = OpenGL.GL.shaders.compileProgram( OpenGL.GL.shaders.compileShader(vertex_shader, GL_VERTEX_SHADER), OpenGL.GL.shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER)) def setupVAO(self, gpuShape): glBindVertexArray(gpuShape.vao) glBindBuffer(GL_ARRAY_BUFFER, gpuShape.vbo) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, gpuShape.ebo) position = glGetAttribLocation(self.shaderProgram, "position") glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, 20, ctypes.c_void_p(0)) glEnableVertexAttribArray(position) texCoords = glGetAttribLocation(self.shaderProgram, "texCoords") glVertexAttribPointer(texCoords, 2, GL_FLOAT, GL_FALSE, 20, ctypes.c_void_p(3 * SIZE_IN_BYTES)) glEnableVertexAttribArray(texCoords) glBindVertexArray(0) def drawCall(self, gpuShape, mode=GL_TRIANGLES): assert isinstance(gpuShape, TexGPUShape) glBindVertexArray(gpuShape.vao) glActiveTexture(GL_TEXTURE0 + 0) glBindTexture(GL_TEXTURE_2D, gpuShape.texture) glActiveTexture(GL_TEXTURE0 + 1) glBindTexture(GL_TEXTURE_2D, gpuShape.texture2) glDrawElements(mode, gpuShape.size, GL_UNSIGNED_INT, None) glBindVertexArray(0) class Controller: def __init__(self): self.fillPolygon = True self.mousePos = (0.0, 0.0) controller = Controller() def on_key(window, key, scancode, action, mods): if action != glfw.PRESS: return global controller if key == glfw.KEY_SPACE: controller.fillPolygon = not controller.fillPolygon elif key == glfw.KEY_ESCAPE: glfw.set_window_should_close(window, True) else: print('Unknown key') def cursor_pos_callback(window, x, y): global controller controller.mousePos = (x,y) if __name__ == "__main__": if not glfw.init(): sys.exit(1) width = 600 height = 600 window = glfw.create_window(width, height, "Double binding", None, None) if not window: glfw.terminate() glfw.set_window_should_close(window, True) glfw.make_context_current(window) glfw.set_key_callback(window, on_key) glfw.set_cursor_pos_callback(window, cursor_pos_callback) pipeline = DoubleTextureTransformShaderProgram() glClearColor(0.25, 0.25, 0.25, 1.0) shape = bs.createTextureQuad(1, 1) gpuShape = TexGPUShape().initBuffers() pipeline.setupVAO(gpuShape) gpuShape.fillBuffers(shape.vertices, shape.indices, GL_STATIC_DRAW) gpuShape.texture = es.textureSimpleSetup( getAssetPath("torres-del-paine-sq.jpg"), GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, GL_LINEAR, GL_LINEAR) gpuShape.texture2 = es.textureSimpleSetup( getAssetPath("red_woodpecker.jpg"), GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE, GL_LINEAR, GL_LINEAR) currentMousePos = [width/2, height/2] while not glfw.window_should_close(window): glfw.poll_events() if (controller.fillPolygon): glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) else: glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) theta = 0.3 * np.sin(glfw.get_time()) glClear(GL_COLOR_BUFFER_BIT) glUseProgram(pipeline.shaderProgram) glUniformMatrix4fv(glGetUniformLocation(pipeline.shaderProgram, "transform"), 1, GL_TRUE, np.matmul( tr.shearing(0,theta,0,0,0,0), tr.uniformScale(1.5) ) ) glUniform1i(glGetUniformLocation(pipeline.shaderProgram, "upTexture"), 0) glUniform1i(glGetUniformLocation(pipeline.shaderProgram, "downTexture"), 1) glUniform1f(glGetUniformLocation(pipeline.shaderProgram, "mousePosY"), controller.mousePos[1]) pipeline.drawCall(gpuShape) glfw.swap_buffers(window) gpuShape.clear() glfw.terminate()
true
true
f72a4c25bda8e56afb5812475a76671822928e38
4,267
py
Python
src/run_evaluation.py
liushulinle/CRACSpell
faff01521b08032c4efa89bbb2dc942a6327bc53
[ "MIT" ]
2
2022-03-23T07:17:02.000Z
2022-03-24T07:09:04.000Z
src/run_evaluation.py
liushulinle/CRASpell
e0b495ed8424be7fdbd7fc3ef8c2919ab195b0e4
[ "MIT" ]
null
null
null
src/run_evaluation.py
liushulinle/CRASpell
e0b495ed8424be7fdbd7fc3ef8c2919ab195b0e4
[ "MIT" ]
null
null
null
import sys, os import numpy as np import tensorflow as tf from bert_tagging import DataProcessor, BertTagging import modeling import optimization import time from tagging_eval import score_f tf.logging.set_verbosity(tf.logging.ERROR) DEBUG = False def evaluate(FLAGS, label_list=None): gpuid = FLAGS.gpuid max_sen_len = FLAGS.max_sen_len test_file = FLAGS.test_path out_dir = FLAGS.output_dir model_dir = FLAGS.model_dir batch_size = FLAGS.batch_size bert_config_path = './conf/bert_config.json' vocob_file = './conf/vocab.txt' os.environ["CUDA_VISIBLE_DEVICES"] = gpuid # data processor data_processor = DataProcessor(test_file, max_sen_len, vocob_file, out_dir, label_list=None, is_training=False) test_num = data_processor.num_examples test_data = data_processor.build_data_generator(batch_size) iterator = test_data.make_one_shot_iterator() input_ids, input_mask, segment_ids, lmask, label_ids, masked_sample = iterator.get_next() #load model model = BertTagging(bert_config_path, num_class=len(data_processor.get_label_list()), max_sen_len=max_sen_len) (pred_loss, pred_result, gold_result, gold_mask, r_loss) = model.create_model(input_ids, input_mask, segment_ids, lmask, label_ids, batch_size=batch_size, masked_sample=masked_sample, is_training=False) tf_config = tf.ConfigProto(log_device_placement=False) tf_config.gpu_options.allow_growth = True sess = tf.Session(config=tf_config) ckpt = tf.train.get_checkpoint_state(model_dir) saver = tf.train.Saver() saver.restore(sess, ckpt.model_checkpoint_path) label_list = data_processor.label_list ans = [] all_inputs, all_golds, all_preds = [], [], [] all_py_inputs, all_py_golds, all_py_preds = [], [], [] all_fusion_preds = [] all_inputs_sent, all_golds_sent, all_preds_sent = [], [], [] for step in range(test_num // batch_size): inputs, loss_value, preds, golds, gmask = sess.run([input_ids, pred_loss, pred_result, gold_result, gold_mask]) for k in range(batch_size): gsent, psent, isent = [], [], [] for j in range(max_sen_len): if gmask[k][j] == 0: continue all_golds.append(golds[k][j]) all_preds.append(preds[k][j]) all_inputs.append(inputs[k][j]) gsent.append(label_list[golds[k][j]]) psent.append(label_list[preds[k][j]]) isent.append(label_list[inputs[k][j]]) all_golds_sent.append(gsent) all_preds_sent.append(psent) all_inputs_sent.append(isent) if DEBUG and step > 5: break fout = open('%s/pred_sent.txt' % out_dir, 'w', encoding='utf-8') fout.writelines('## input/gold/pred TAB ... ...\n') for k in range(len(all_inputs_sent)): for j in range(len(all_inputs_sent[k])): ic = all_inputs_sent[k][j] pc = all_preds_sent[k][j] gc = all_golds_sent[k][j] fout.writelines('%s/%s/%s\t' % (ic, gc, pc)) fout.writelines('\n') fout.close() all_golds = [label_list[k] for k in all_golds] all_preds = [label_list[k] for k in all_preds] all_inputs = [label_list[k] for k in all_inputs] print ('ALL LEN:%d' % len(all_preds)) print('zi result:') p, r, f = score_f((all_inputs, all_golds, all_preds), only_check=False, out_dir=out_dir) return f if __name__ == '__main__': flags = tf.flags ## Required parameters flags.DEFINE_string("gpuid", '0', "The gpu NO. ") ## Optional flags.DEFINE_string("test_path", '', "train path ") flags.DEFINE_string("output_dir", '', "out dir ") flags.DEFINE_string("model_dir", '', "out dir ") flags.DEFINE_integer("batch_size", '1', "out dir ") flags.DEFINE_integer("max_sen_len", 64, 'max_sen_len') flags.mark_flag_as_required('gpuid') flags.mark_flag_as_required('test_path') flags.mark_flag_as_required('output_dir') flags.mark_flag_as_required('max_sen_len') FLAGS = flags.FLAGS print ('Confings:') print ('\tgpuid=', FLAGS.gpuid) print ('\ttest_path=', FLAGS.test_path) print ('\toutput_dir=', FLAGS.output_dir) evaluate(FLAGS, FLAGS.test_path)
38.098214
206
0.668854
import sys, os import numpy as np import tensorflow as tf from bert_tagging import DataProcessor, BertTagging import modeling import optimization import time from tagging_eval import score_f tf.logging.set_verbosity(tf.logging.ERROR) DEBUG = False def evaluate(FLAGS, label_list=None): gpuid = FLAGS.gpuid max_sen_len = FLAGS.max_sen_len test_file = FLAGS.test_path out_dir = FLAGS.output_dir model_dir = FLAGS.model_dir batch_size = FLAGS.batch_size bert_config_path = './conf/bert_config.json' vocob_file = './conf/vocab.txt' os.environ["CUDA_VISIBLE_DEVICES"] = gpuid data_processor = DataProcessor(test_file, max_sen_len, vocob_file, out_dir, label_list=None, is_training=False) test_num = data_processor.num_examples test_data = data_processor.build_data_generator(batch_size) iterator = test_data.make_one_shot_iterator() input_ids, input_mask, segment_ids, lmask, label_ids, masked_sample = iterator.get_next() model = BertTagging(bert_config_path, num_class=len(data_processor.get_label_list()), max_sen_len=max_sen_len) (pred_loss, pred_result, gold_result, gold_mask, r_loss) = model.create_model(input_ids, input_mask, segment_ids, lmask, label_ids, batch_size=batch_size, masked_sample=masked_sample, is_training=False) tf_config = tf.ConfigProto(log_device_placement=False) tf_config.gpu_options.allow_growth = True sess = tf.Session(config=tf_config) ckpt = tf.train.get_checkpoint_state(model_dir) saver = tf.train.Saver() saver.restore(sess, ckpt.model_checkpoint_path) label_list = data_processor.label_list ans = [] all_inputs, all_golds, all_preds = [], [], [] all_py_inputs, all_py_golds, all_py_preds = [], [], [] all_fusion_preds = [] all_inputs_sent, all_golds_sent, all_preds_sent = [], [], [] for step in range(test_num // batch_size): inputs, loss_value, preds, golds, gmask = sess.run([input_ids, pred_loss, pred_result, gold_result, gold_mask]) for k in range(batch_size): gsent, psent, isent = [], [], [] for j in range(max_sen_len): if gmask[k][j] == 0: continue all_golds.append(golds[k][j]) all_preds.append(preds[k][j]) all_inputs.append(inputs[k][j]) gsent.append(label_list[golds[k][j]]) psent.append(label_list[preds[k][j]]) isent.append(label_list[inputs[k][j]]) all_golds_sent.append(gsent) all_preds_sent.append(psent) all_inputs_sent.append(isent) if DEBUG and step > 5: break fout = open('%s/pred_sent.txt' % out_dir, 'w', encoding='utf-8') fout.writelines('## input/gold/pred TAB ... ...\n') for k in range(len(all_inputs_sent)): for j in range(len(all_inputs_sent[k])): ic = all_inputs_sent[k][j] pc = all_preds_sent[k][j] gc = all_golds_sent[k][j] fout.writelines('%s/%s/%s\t' % (ic, gc, pc)) fout.writelines('\n') fout.close() all_golds = [label_list[k] for k in all_golds] all_preds = [label_list[k] for k in all_preds] all_inputs = [label_list[k] for k in all_inputs] print ('ALL LEN:%d' % len(all_preds)) print('zi result:') p, r, f = score_f((all_inputs, all_golds, all_preds), only_check=False, out_dir=out_dir) return f if __name__ == '__main__': flags = tf.flags ing("gpuid", '0', "The gpu NO. ") .DEFINE_string("test_path", '', "train path ") flags.DEFINE_string("output_dir", '', "out dir ") flags.DEFINE_string("model_dir", '', "out dir ") flags.DEFINE_integer("batch_size", '1', "out dir ") flags.DEFINE_integer("max_sen_len", 64, 'max_sen_len') flags.mark_flag_as_required('gpuid') flags.mark_flag_as_required('test_path') flags.mark_flag_as_required('output_dir') flags.mark_flag_as_required('max_sen_len') FLAGS = flags.FLAGS print ('Confings:') print ('\tgpuid=', FLAGS.gpuid) print ('\ttest_path=', FLAGS.test_path) print ('\toutput_dir=', FLAGS.output_dir) evaluate(FLAGS, FLAGS.test_path)
true
true
f72a4c3a75bd42077f335838511586ea852c2671
3,899
py
Python
run.py
ntraut/example
5b7501ee7c8ad4e7c61b3ff8e9b1d3c0380c33de
[ "Apache-2.0" ]
13
2017-04-03T12:09:35.000Z
2021-06-07T09:40:31.000Z
run.py
ntraut/example
5b7501ee7c8ad4e7c61b3ff8e9b1d3c0380c33de
[ "Apache-2.0" ]
13
2016-08-02T18:56:13.000Z
2020-05-15T10:39:19.000Z
run.py
ntraut/example
5b7501ee7c8ad4e7c61b3ff8e9b1d3c0380c33de
[ "Apache-2.0" ]
31
2016-07-28T22:32:58.000Z
2022-01-05T09:13:03.000Z
#!/usr/bin/env python3 import argparse import os import subprocess import nibabel import numpy from glob import glob __version__ = open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'version')).read() def run(command, env={}): merged_env = os.environ merged_env.update(env) process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, env=merged_env) while True: line = process.stdout.readline() line = str(line, 'utf-8')[:-1] print(line) if line == '' and process.poll() != None: break if process.returncode != 0: raise Exception("Non zero return code: %d"%process.returncode) parser = argparse.ArgumentParser(description='Example BIDS App entrypoint script.') parser.add_argument('bids_dir', help='The directory with the input dataset ' 'formatted according to the BIDS standard.') parser.add_argument('output_dir', help='The directory where the output files ' 'should be stored. If you are running group level analysis ' 'this folder should be prepopulated with the results of the' 'participant level analysis.') parser.add_argument('analysis_level', help='Level of the analysis that will be performed. ' 'Multiple participant level analyses can be run independently ' '(in parallel) using the same output_dir.', choices=['participant', 'group']) parser.add_argument('--participant_label', help='The label(s) of the participant(s) that should be analyzed. The label ' 'corresponds to sub-<participant_label> from the BIDS spec ' '(so it does not include "sub-"). If this parameter is not ' 'provided all subjects should be analyzed. Multiple ' 'participants can be specified with a space separated list.', nargs="+") parser.add_argument('--skip_bids_validator', help='Whether or not to perform BIDS dataset validation', action='store_true') parser.add_argument('-v', '--version', action='version', version='BIDS-App example version {}'.format(__version__)) args = parser.parse_args() if not args.skip_bids_validator: run('bids-validator %s'%args.bids_dir) subjects_to_analyze = [] # only for a subset of subjects if args.participant_label: subjects_to_analyze = args.participant_label # for all subjects else: subject_dirs = glob(os.path.join(args.bids_dir, "sub-*")) subjects_to_analyze = [subject_dir.split("-")[-1] for subject_dir in subject_dirs] # running participant level if args.analysis_level == "participant": # find all T1s and skullstrip them for subject_label in subjects_to_analyze: for T1_file in glob(os.path.join(args.bids_dir, "sub-%s"%subject_label, "anat", "*_T1w.nii*")) + glob(os.path.join(args.bids_dir,"sub-%s"%subject_label,"ses-*","anat", "*_T1w.nii*")): out_file = os.path.split(T1_file)[-1].replace("_T1w.", "_brain.") cmd = "bet %s %s"%(T1_file, os.path.join(args.output_dir, out_file)) print(cmd) run(cmd) # running group level elif args.analysis_level == "group": brain_sizes = [] for subject_label in subjects_to_analyze: for brain_file in glob(os.path.join(args.output_dir, "sub-%s*.nii*"%subject_label)): data = nibabel.load(brain_file).get_data() # calcualte average mask size in voxels brain_sizes.append((data != 0).sum()) with open(os.path.join(args.output_dir, "avg_brain_size.txt"), 'w') as fp: fp.write("Average brain size is %g voxels"%numpy.array(brain_sizes).mean())
44.816092
152
0.633496
import argparse import os import subprocess import nibabel import numpy from glob import glob __version__ = open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'version')).read() def run(command, env={}): merged_env = os.environ merged_env.update(env) process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, env=merged_env) while True: line = process.stdout.readline() line = str(line, 'utf-8')[:-1] print(line) if line == '' and process.poll() != None: break if process.returncode != 0: raise Exception("Non zero return code: %d"%process.returncode) parser = argparse.ArgumentParser(description='Example BIDS App entrypoint script.') parser.add_argument('bids_dir', help='The directory with the input dataset ' 'formatted according to the BIDS standard.') parser.add_argument('output_dir', help='The directory where the output files ' 'should be stored. If you are running group level analysis ' 'this folder should be prepopulated with the results of the' 'participant level analysis.') parser.add_argument('analysis_level', help='Level of the analysis that will be performed. ' 'Multiple participant level analyses can be run independently ' '(in parallel) using the same output_dir.', choices=['participant', 'group']) parser.add_argument('--participant_label', help='The label(s) of the participant(s) that should be analyzed. The label ' 'corresponds to sub-<participant_label> from the BIDS spec ' '(so it does not include "sub-"). If this parameter is not ' 'provided all subjects should be analyzed. Multiple ' 'participants can be specified with a space separated list.', nargs="+") parser.add_argument('--skip_bids_validator', help='Whether or not to perform BIDS dataset validation', action='store_true') parser.add_argument('-v', '--version', action='version', version='BIDS-App example version {}'.format(__version__)) args = parser.parse_args() if not args.skip_bids_validator: run('bids-validator %s'%args.bids_dir) subjects_to_analyze = [] if args.participant_label: subjects_to_analyze = args.participant_label else: subject_dirs = glob(os.path.join(args.bids_dir, "sub-*")) subjects_to_analyze = [subject_dir.split("-")[-1] for subject_dir in subject_dirs] if args.analysis_level == "participant": for subject_label in subjects_to_analyze: for T1_file in glob(os.path.join(args.bids_dir, "sub-%s"%subject_label, "anat", "*_T1w.nii*")) + glob(os.path.join(args.bids_dir,"sub-%s"%subject_label,"ses-*","anat", "*_T1w.nii*")): out_file = os.path.split(T1_file)[-1].replace("_T1w.", "_brain.") cmd = "bet %s %s"%(T1_file, os.path.join(args.output_dir, out_file)) print(cmd) run(cmd) elif args.analysis_level == "group": brain_sizes = [] for subject_label in subjects_to_analyze: for brain_file in glob(os.path.join(args.output_dir, "sub-%s*.nii*"%subject_label)): data = nibabel.load(brain_file).get_data() brain_sizes.append((data != 0).sum()) with open(os.path.join(args.output_dir, "avg_brain_size.txt"), 'w') as fp: fp.write("Average brain size is %g voxels"%numpy.array(brain_sizes).mean())
true
true
f72a4c44918d4818263c7f5a892eaf25465b4fda
4,108
py
Python
homeassistant/components/azure_devops/__init__.py
tbarbette/core
8e58c3aa7bc8d2c2b09b6bd329daa1c092d52d3c
[ "Apache-2.0" ]
6
2016-11-25T06:36:27.000Z
2021-11-16T11:20:23.000Z
homeassistant/components/azure_devops/__init__.py
tbarbette/core
8e58c3aa7bc8d2c2b09b6bd329daa1c092d52d3c
[ "Apache-2.0" ]
58
2020-08-03T07:33:02.000Z
2022-03-31T06:02:05.000Z
homeassistant/components/azure_devops/__init__.py
tbarbette/core
8e58c3aa7bc8d2c2b09b6bd329daa1c092d52d3c
[ "Apache-2.0" ]
14
2018-08-19T16:28:26.000Z
2021-09-02T18:26:53.000Z
"""Support for Azure DevOps.""" import logging from typing import Any, Dict from aioazuredevops.client import DevOpsClient import aiohttp from homeassistant.components.azure_devops.const import ( CONF_ORG, CONF_PAT, CONF_PROJECT, DATA_AZURE_DEVOPS_CLIENT, DOMAIN, ) from homeassistant.config_entries import ConfigEntry from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers.entity import Entity from homeassistant.helpers.typing import ConfigType, HomeAssistantType _LOGGER = logging.getLogger(__name__) async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool: """Set up the Azure DevOps components.""" return True async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool: """Set up Azure DevOps from a config entry.""" client = DevOpsClient() try: if entry.data[CONF_PAT] is not None: await client.authorize(entry.data[CONF_PAT], entry.data[CONF_ORG]) if not client.authorized: _LOGGER.warning( "Could not authorize with Azure DevOps. You may need to update your token" ) hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth"}, data=entry.data, ) ) return False await client.get_project(entry.data[CONF_ORG], entry.data[CONF_PROJECT]) except aiohttp.ClientError as exception: _LOGGER.warning(exception) raise ConfigEntryNotReady from exception instance_key = f"{DOMAIN}_{entry.data[CONF_ORG]}_{entry.data[CONF_PROJECT]}" hass.data.setdefault(instance_key, {})[DATA_AZURE_DEVOPS_CLIENT] = client # Setup components hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, "sensor") ) return True async def async_unload_entry(hass: HomeAssistantType, entry: ConfigType) -> bool: """Unload Azure DevOps config entry.""" del hass.data[f"{DOMAIN}_{entry.data[CONF_ORG]}_{entry.data[CONF_PROJECT]}"] return await hass.config_entries.async_forward_entry_unload(entry, "sensor") class AzureDevOpsEntity(Entity): """Defines a base Azure DevOps entity.""" def __init__(self, organization: str, project: str, name: str, icon: str) -> None: """Initialize the Azure DevOps entity.""" self._name = name self._icon = icon self._available = True self.organization = organization self.project = project @property def name(self) -> str: """Return the name of the entity.""" return self._name @property def icon(self) -> str: """Return the mdi icon of the entity.""" return self._icon @property def available(self) -> bool: """Return True if entity is available.""" return self._available async def async_update(self) -> None: """Update Azure DevOps entity.""" if await self._azure_devops_update(): self._available = True else: if self._available: _LOGGER.debug( "An error occurred while updating Azure DevOps sensor.", exc_info=True, ) self._available = False async def _azure_devops_update(self) -> None: """Update Azure DevOps entity.""" raise NotImplementedError() class AzureDevOpsDeviceEntity(AzureDevOpsEntity): """Defines a Azure DevOps device entity.""" @property def device_info(self) -> Dict[str, Any]: """Return device information about this Azure DevOps instance.""" return { "identifiers": { ( DOMAIN, self.organization, self.project, ) }, "manufacturer": self.organization, "name": self.project, "entry_type": "service", }
31.358779
94
0.619523
import logging from typing import Any, Dict from aioazuredevops.client import DevOpsClient import aiohttp from homeassistant.components.azure_devops.const import ( CONF_ORG, CONF_PAT, CONF_PROJECT, DATA_AZURE_DEVOPS_CLIENT, DOMAIN, ) from homeassistant.config_entries import ConfigEntry from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers.entity import Entity from homeassistant.helpers.typing import ConfigType, HomeAssistantType _LOGGER = logging.getLogger(__name__) async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool: return True async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool: client = DevOpsClient() try: if entry.data[CONF_PAT] is not None: await client.authorize(entry.data[CONF_PAT], entry.data[CONF_ORG]) if not client.authorized: _LOGGER.warning( "Could not authorize with Azure DevOps. You may need to update your token" ) hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": "reauth"}, data=entry.data, ) ) return False await client.get_project(entry.data[CONF_ORG], entry.data[CONF_PROJECT]) except aiohttp.ClientError as exception: _LOGGER.warning(exception) raise ConfigEntryNotReady from exception instance_key = f"{DOMAIN}_{entry.data[CONF_ORG]}_{entry.data[CONF_PROJECT]}" hass.data.setdefault(instance_key, {})[DATA_AZURE_DEVOPS_CLIENT] = client hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, "sensor") ) return True async def async_unload_entry(hass: HomeAssistantType, entry: ConfigType) -> bool: del hass.data[f"{DOMAIN}_{entry.data[CONF_ORG]}_{entry.data[CONF_PROJECT]}"] return await hass.config_entries.async_forward_entry_unload(entry, "sensor") class AzureDevOpsEntity(Entity): def __init__(self, organization: str, project: str, name: str, icon: str) -> None: self._name = name self._icon = icon self._available = True self.organization = organization self.project = project @property def name(self) -> str: return self._name @property def icon(self) -> str: return self._icon @property def available(self) -> bool: return self._available async def async_update(self) -> None: if await self._azure_devops_update(): self._available = True else: if self._available: _LOGGER.debug( "An error occurred while updating Azure DevOps sensor.", exc_info=True, ) self._available = False async def _azure_devops_update(self) -> None: raise NotImplementedError() class AzureDevOpsDeviceEntity(AzureDevOpsEntity): @property def device_info(self) -> Dict[str, Any]: return { "identifiers": { ( DOMAIN, self.organization, self.project, ) }, "manufacturer": self.organization, "name": self.project, "entry_type": "service", }
true
true
f72a4c55620436228ce86fa539585fab1397d008
2,698
py
Python
dprs/get_contents_file_list.py
kaan-keskin/debian-package-repository-statistics
ef70f4a9914b8baa4799a36217832a5cbdc8b7d3
[ "MIT" ]
1
2022-03-21T19:08:43.000Z
2022-03-21T19:08:43.000Z
dprs/get_contents_file_list.py
kaan-keskin/debian-package-repository-statistics
ef70f4a9914b8baa4799a36217832a5cbdc8b7d3
[ "MIT" ]
null
null
null
dprs/get_contents_file_list.py
kaan-keskin/debian-package-repository-statistics
ef70f4a9914b8baa4799a36217832a5cbdc8b7d3
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # Extensible library for opening URLs # https://docs.python.org/3/library/urllib.request.html import urllib.request from urllib.error import URLError from dprs.default_variables import DEFAULT_MIRROR_URL from dprs.exceptions import MirrorURLNotAccessible def get_contents_file_list(mirror_url: str = DEFAULT_MIRROR_URL) -> list: """ This function returns a list of dictionaries extracted from Contents-*.gz file in the given Debian Package Repository Address. Arguments: mirror_url: Debian Package Repository Address Returns: list: List of dictionaries with the following structure: [ { "architecture": "amd64", "filename": "Contents-amd64.gz", "url": http://ftp.uk.debian.org/debian/dists/stable/main/Contents-amd64.gz" }, { "architecture": "arm64", "filename": "Contents-arm64.gz", "url": http://ftp.uk.debian.org/debian/dists/stable/main/Contents-arm64.gz" }, { "architecture": "i386", "filename": "Contents-i386.gz", "url": http://ftp.uk.debian.org/debian/dists/stable/main/Contents-i386.gz" }, ... ] """ try: with urllib.request.urlopen(mirror_url) as url_opener_response: raw_html = url_opener_response.read() except URLError: # TODO: Add more functionality. Doing nothing for now! raise MirrorURLNotAccessible("Debian Package Repository URL is not accessible!") html = raw_html.decode() """ HTML content will be similar to the following structure: ... <a href="Contents-all.gz">Contents-all.gz</a> <a href="Contents-amd64.gz">Contents-amd64.gz</a> <a href="Contents-arm64.gz">Contents-arm64.gz</a> <a href="Contents-i386.gz">Contents-i386.gz</a> ... <a href="Contents-udeb-all.gz">Contents-udeb-all.gz</a> <a href="Contents-udeb-amd64.gz">Contents-udeb-amd64.gz</a> <a href="Contents-udeb-arm64.gz">Contents-udeb-arm64.gz</a> <a href="Contents-udeb-i386.gz">Contents-udeb-i386.gz</a> ... """ contents_file_list = [] for line in html.split("\r\n"): if line.startswith("<a href=\"Contents-"): filename = line[line.find("Contents-"):line.find(".gz")+3] architecture = filename[filename.rfind("-") + 1:filename.rfind(".gz")] url = f"{mirror_url}{filename}" if mirror_url.endswith("/") else f"{mirror_url}/{filename}" contents_file_list.append(dict(architecture=architecture, filename=filename, url=url)) return contents_file_list
38.542857
103
0.627502
import urllib.request from urllib.error import URLError from dprs.default_variables import DEFAULT_MIRROR_URL from dprs.exceptions import MirrorURLNotAccessible def get_contents_file_list(mirror_url: str = DEFAULT_MIRROR_URL) -> list: try: with urllib.request.urlopen(mirror_url) as url_opener_response: raw_html = url_opener_response.read() except URLError: raise MirrorURLNotAccessible("Debian Package Repository URL is not accessible!") html = raw_html.decode() contents_file_list = [] for line in html.split("\r\n"): if line.startswith("<a href=\"Contents-"): filename = line[line.find("Contents-"):line.find(".gz")+3] architecture = filename[filename.rfind("-") + 1:filename.rfind(".gz")] url = f"{mirror_url}{filename}" if mirror_url.endswith("/") else f"{mirror_url}/{filename}" contents_file_list.append(dict(architecture=architecture, filename=filename, url=url)) return contents_file_list
true
true
f72a4c7097a99eefb13c041d6192064e857a4dfb
1,277
py
Python
tests/conftest.py
benbenti/fuzzyclustering
f67224105528d82f6d950ec7692a50d927ca0621
[ "MIT" ]
null
null
null
tests/conftest.py
benbenti/fuzzyclustering
f67224105528d82f6d950ec7692a50d927ca0621
[ "MIT" ]
3
2021-04-22T15:20:32.000Z
2021-04-22T15:21:41.000Z
tests/conftest.py
benbenti/fuzzyclustering
f67224105528d82f6d950ec7692a50d927ca0621
[ "MIT" ]
null
null
null
import pytest import random import numpy as np from numpy.random import rand import lib.algorithms as al @pytest.fixture(scope="session") def unif_1D(): """ Test case: one dimension, samples evenly distributed. """ data = np.array([[0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12] ] ) return data @pytest.fixture(scope="session") def rng(): return random.Random() @pytest.fixture def dataset(rng): n_samples = rng.randint(100, 1000) n_features = rng.randint(10, 100) feature_range = rng.randint(1, 10) return (rand(n_samples, n_features) - 1/2) * feature_range @pytest.fixture def nc(rng): return rng.randint(2, 50) @pytest.fixture def FC_random(rng, dataset, nc): p = 1 + rng.random() * 2 return al.FuzzyClustering(dataset, p, nc) # @pytest.fixture # def FCP_random(rng, dataset, nc): # p = rng.random() # return al.FuzzyClusteringPoly(dataset, p, nc) # @pytest.fixture # def FCRS_random(rng, dataset, nc): # p = rng.random() * 5 # return al.FuzzyClusteringRegulSh(dataset, p, nc) # @pytest.fixture # def FCRQ_random(rng, dataset, nc): # p = rng.random() * 5 # return al.FuzzyClusteringRegulQuad(dataset, p, nc)
24.557692
62
0.617071
import pytest import random import numpy as np from numpy.random import rand import lib.algorithms as al @pytest.fixture(scope="session") def unif_1D(): data = np.array([[0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12] ] ) return data @pytest.fixture(scope="session") def rng(): return random.Random() @pytest.fixture def dataset(rng): n_samples = rng.randint(100, 1000) n_features = rng.randint(10, 100) feature_range = rng.randint(1, 10) return (rand(n_samples, n_features) - 1/2) * feature_range @pytest.fixture def nc(rng): return rng.randint(2, 50) @pytest.fixture def FC_random(rng, dataset, nc): p = 1 + rng.random() * 2 return al.FuzzyClustering(dataset, p, nc)
true
true
f72a4c86c1a569849d3b8f3e318a9e9d83312722
3,322
py
Python
2 semester/PP/10_2/Code/3.py
kurpenok/Labs
069c92b7964a1445d093313b38ebdc56318d2a73
[ "MIT" ]
null
null
null
2 semester/PP/10_2/Code/3.py
kurpenok/Labs
069c92b7964a1445d093313b38ebdc56318d2a73
[ "MIT" ]
null
null
null
2 semester/PP/10_2/Code/3.py
kurpenok/Labs
069c92b7964a1445d093313b38ebdc56318d2a73
[ "MIT" ]
null
null
null
from math import sqrt, sin, pi class Liked: def __init__(self, *args) -> None: self.data = [] for arg in args: for line in arg: self.data.append(line) def likes(self) -> dict: self.emojis = [":)", ";)", ")", ":(", ";(", "("] output = dict() for line in self.data: for emoji in self.emojis: count = line.count(emoji) if count: if emoji in output: output[emoji] += count else: output[emoji] = count return output class MiMiMi(Liked): def __init__(self, *args) -> None: super().__init__(*args) def likes(self) -> dict: self.emojis = [":)", ";)", ")", ":(", ";(", "("] output = dict() for line in self.data: if ["cat", "kitten"] in line: for emoji in self.emojis: count = line.count(emoji) if count: if emoji in output: output[emoji] += count else: output[emoji] = count return output class Mosquito: def __init__(self, age: int) -> None: self.age = age def __str__(self) -> str: return f"Mosquito, {self.age} age" class MaleMosquito(Mosquito): def __init__(self, age: int, lives: str) -> None: self.age = age self.lives = lives def __str__(self) -> str: return f"I hear and see everything {self.lives}" class FemaleMosquito(Mosquito): def __init__(self, age: int, feed: str) -> None: self.age = age self.feed = feed def __str__(self) -> str: return f"The thin squeak of a mosquito after eating {self.feed}" class MosquitoLarva(Mosquito): def __str__(self) -> str: return f"" class Oscillations: def __init__(self, a: int) -> None: self.a = a class SpringPendulum(Oscillations): def __init__(self, a: int, m: int, k: int) -> None: self.a = a self.m = m self.k = k def period(self) -> float: return 2 * pi * sqrt(self.m / self.k) def cyclic_frequeny(self, w: int) -> float: return 2 * pi / w def __str__(self, t: int, w: int) -> str: return f"X = {self.a * sin(w * t)}" class MathPendulum(Oscillations): def __init__(self, a: int, l: int, g: int) -> None: self.a = a self.l = l self.g = g def period(self) -> float: return 2 * pi * sqrt(self.l / self.g) def cyclic_frequeny(self, w: int) -> float: return 2 * pi / w def __str__(self, t: int, w: int) -> str: return f"X = {self.a * sin(w * t)}" class EMPendulum(Oscillations): def __init__(self, a: int, l: int, c: int) -> None: self.a = a self.l = l self.c = c def period(self) -> float: return 2 * pi * sqrt(self.l * self.c) def cyclic_frequeny(self, w: int) -> float: return 2 * pi / w def __str__(self, t: int, w: int) -> str: return f"X = {self.a * sin(w * t)}" if __name__ == "__main__": liked = Liked(["Hi, Kuat! :)", "Well ;)", "How are you?))"]) print(liked.likes())
24.248175
72
0.494883
from math import sqrt, sin, pi class Liked: def __init__(self, *args) -> None: self.data = [] for arg in args: for line in arg: self.data.append(line) def likes(self) -> dict: self.emojis = [":)", ";)", ")", ":(", ";(", "("] output = dict() for line in self.data: for emoji in self.emojis: count = line.count(emoji) if count: if emoji in output: output[emoji] += count else: output[emoji] = count return output class MiMiMi(Liked): def __init__(self, *args) -> None: super().__init__(*args) def likes(self) -> dict: self.emojis = [":)", ";)", ")", ":(", ";(", "("] output = dict() for line in self.data: if ["cat", "kitten"] in line: for emoji in self.emojis: count = line.count(emoji) if count: if emoji in output: output[emoji] += count else: output[emoji] = count return output class Mosquito: def __init__(self, age: int) -> None: self.age = age def __str__(self) -> str: return f"Mosquito, {self.age} age" class MaleMosquito(Mosquito): def __init__(self, age: int, lives: str) -> None: self.age = age self.lives = lives def __str__(self) -> str: return f"I hear and see everything {self.lives}" class FemaleMosquito(Mosquito): def __init__(self, age: int, feed: str) -> None: self.age = age self.feed = feed def __str__(self) -> str: return f"The thin squeak of a mosquito after eating {self.feed}" class MosquitoLarva(Mosquito): def __str__(self) -> str: return f"" class Oscillations: def __init__(self, a: int) -> None: self.a = a class SpringPendulum(Oscillations): def __init__(self, a: int, m: int, k: int) -> None: self.a = a self.m = m self.k = k def period(self) -> float: return 2 * pi * sqrt(self.m / self.k) def cyclic_frequeny(self, w: int) -> float: return 2 * pi / w def __str__(self, t: int, w: int) -> str: return f"X = {self.a * sin(w * t)}" class MathPendulum(Oscillations): def __init__(self, a: int, l: int, g: int) -> None: self.a = a self.l = l self.g = g def period(self) -> float: return 2 * pi * sqrt(self.l / self.g) def cyclic_frequeny(self, w: int) -> float: return 2 * pi / w def __str__(self, t: int, w: int) -> str: return f"X = {self.a * sin(w * t)}" class EMPendulum(Oscillations): def __init__(self, a: int, l: int, c: int) -> None: self.a = a self.l = l self.c = c def period(self) -> float: return 2 * pi * sqrt(self.l * self.c) def cyclic_frequeny(self, w: int) -> float: return 2 * pi / w def __str__(self, t: int, w: int) -> str: return f"X = {self.a * sin(w * t)}" if __name__ == "__main__": liked = Liked(["Hi, Kuat! :)", "Well ;)", "How are you?))"]) print(liked.likes())
true
true
f72a4cbccdd5ee4e79941efbf501b57e0fc9d10f
6,514
py
Python
test.py
jssprz/video_captioning_with_visual_syntactic_embedding
0687772b22c56f448dabbe46932422363964abd4
[ "MIT" ]
23
2021-01-04T07:09:40.000Z
2022-01-12T22:54:33.000Z
test.py
jssprz/video_captioning_with_visual_syntactic_embedding
0687772b22c56f448dabbe46932422363964abd4
[ "MIT" ]
7
2021-01-14T07:48:22.000Z
2022-02-01T04:30:05.000Z
test.py
jssprz/video_captioning_with_visual_syntactic_embedding
0687772b22c56f448dabbe46932422363964abd4
[ "MIT" ]
7
2021-03-20T15:03:53.000Z
2022-03-09T09:18:10.000Z
import os import argparse import pickle from utils import decode_from_tokens from vocabulary import Vocabulary from configuration_file import ConfigurationFile from model.encoder import SCNEncoder from model.decoder import SemSynANDecoder import h5py import torch import numpy as np if __name__ == '__main__': parser = argparse.ArgumentParser(description='Generate captions por test samples') parser.add_argument('-chckpt', '--checkpoint_path', type=str, default='pretrain/chckpt.pt', help='Set the path to pre-trained model (default is pretrain/chckpt.pt).') parser.add_argument('-data', '--dataset_folder', type=str, default='data/MSVD', help='Set the path to dataset folder (default is data/MSVD).') parser.add_argument('-out', '--output_folder', type=str, default='results/MSVD', help='Set the path to output folder (default is results/MSVD).') args = parser.parse_args() # load vocabulary with open(os.path.join(args.dataset_folder, 'corpus.pkl'), "rb") as f: corpus = pickle.load(f) idx2word_dict = corpus[4] vocab = Vocabulary.from_idx2word_dict(idx2word_dict, False) print('Size of vocabulary: {}'.format(len(vocab))) # Pretrained Embedding pretrained_embedding = torch.Tensor(corpus[5]) cnn_feature_size = 2048 c3d_feature_size = 4096 i3d_feature_size = 400 eco_feature_size = 1536 res_eco_features_size = 3584 cnn_global_size = 512 projected_size = 512 hidden_size = 1024 # Number of hidden layer units of the cyclic network mid_size = 128 # The middle of the boundary detection layer represents the dimension n_tags = 300 global_tagger_hidden_size = 1024 specific_tagger_hidden_size = 128 hidden_size = 1024 embedding_size = 300 #1024 rnn_in_size = 300 #1024 rnn_hidden_size = 1024 config = ConfigurationFile(os.path.join(args.dataset_folder, 'config.ini'), 'sem-syn-cn-max') # Models encoder = SCNEncoder(cnn_feature_size=cnn_feature_size, c3d_feature_size=c3d_feature_size, i3d_feature_size=i3d_feature_size, eco_feature_size=eco_feature_size, res_eco_features_size=res_eco_features_size, n_tags=n_tags, hidden_size=hidden_size, global_tagger_hidden_size=global_tagger_hidden_size, specific_tagger_hidden_size=specific_tagger_hidden_size, n_layers=config.encoder_num_layers, input_dropout_p=config.encoder_dropout_p, rnn_dropout_p=config.encoder_dropout_p, bidirectional=config.encoder_bidirectional, rnn_cell=config.encoder_rnn_cell, device='cpu') decoder = SemSynANDecoder(in_seq_length=config.max_frames, out_seq_length=config.max_words, n_feats=res_eco_features_size + cnn_global_size, # n_feats=cnn_feature_size+c3d_feature_size, n_tags=n_tags + 400, #+ 174, n_pos_emb=512, embedding_size=embedding_size, pretrained_embedding=pretrained_embedding, hidden_size=hidden_size, rnn_in_size=rnn_in_size, rnn_hidden_size=rnn_hidden_size, vocab=vocab, device='cpu', rnn_cell=config.decoder_rnn_cell, encoder_num_layers=config.encoder_num_layers, encoder_bidirectional=config.encoder_bidirectional, num_layers=config.decoder_num_layers, dropout_p=config.decoder_dropout_p, beam_size=config.decoder_beam_size, temperature=config.decoder_temperature, train_sample_max=config.decoder_train_sample_max, test_sample_max=config.decoder_test_sample_max, beam_search_logic=config.decoder_beam_search_logic, dataset_name=config.dataset_name) # Checkpoint checkpoint = torch.load(args.checkpoint_path, map_location='cpu') # 1. filter out unnecessary keys for encoder chckpt_dict = {k: v for k, v in checkpoint['encoder'].items() if k not in ['fc1.weight', 'fc1.bias', 'fc2.weight', 'fc2.bias']} encoder_dict = encoder.state_dict() encoder_dict.update(chckpt_dict) encoder.load_state_dict(encoder_dict) decoder.load_state_dict(checkpoint['decoder']) #load test set features test_vidxs = sorted(list(set(corpus[2][1]))) with h5py.File(os.path.join(args.dataset_folder, config.features_path), 'r') as feats_file: print('loading visual feats...') dataset = feats_file[config.dataset_name] cnn_feats = torch.from_numpy(dataset['cnn_features'][test_vidxs]).float() c3d_feats = torch.from_numpy(dataset['c3d_features'][test_vidxs]).float() cnn_globals = torch.zeros(cnn_feats.size(0), 512) # torch.from_numpy(dataset['cnn_globals'][test_vidxs]).float() cnn_sem_globals = torch.from_numpy(dataset['cnn_sem_globals'][test_vidxs]).float() f_counts = dataset['count_features'][test_vidxs] print('visual feats loaded') res_eco_globals = torch.from_numpy(np.load(os.path.join(args.dataset_folder, 'resnext_eco.npy'))[test_vidxs]) tags_globals = torch.from_numpy(np.load(os.path.join(args.dataset_folder, 'tag_feats.npy'))[test_vidxs]) encoder.eval() decoder.eval() with torch.no_grad(): video_encoded = encoder(cnn_feats, c3d_feats, cnn_globals, cnn_sem_globals, tags_globals, res_eco_globals) logits, tokens = decoder(video_encoded, None, teacher_forcing_ratio=0) scores = logits.max(dim=2)[0].mean(dim=1) confidences, sentences = [], [] for score, seq in zip(scores, tokens): s = decode_from_tokens(seq, vocab) print(score, s) sentences.append(s) confidences.append(score) if not os.path.exists(args.output_folder): os.makedirs(args.output_folder) with open(os.path.join(args.output_folder, 'predictions.txt'), 'w') as fo: for vidx, sentence in zip(test_vidxs, sentences): fo.write(f'{vidx}\t{sentence}\n')
44.312925
129
0.646147
import os import argparse import pickle from utils import decode_from_tokens from vocabulary import Vocabulary from configuration_file import ConfigurationFile from model.encoder import SCNEncoder from model.decoder import SemSynANDecoder import h5py import torch import numpy as np if __name__ == '__main__': parser = argparse.ArgumentParser(description='Generate captions por test samples') parser.add_argument('-chckpt', '--checkpoint_path', type=str, default='pretrain/chckpt.pt', help='Set the path to pre-trained model (default is pretrain/chckpt.pt).') parser.add_argument('-data', '--dataset_folder', type=str, default='data/MSVD', help='Set the path to dataset folder (default is data/MSVD).') parser.add_argument('-out', '--output_folder', type=str, default='results/MSVD', help='Set the path to output folder (default is results/MSVD).') args = parser.parse_args() with open(os.path.join(args.dataset_folder, 'corpus.pkl'), "rb") as f: corpus = pickle.load(f) idx2word_dict = corpus[4] vocab = Vocabulary.from_idx2word_dict(idx2word_dict, False) print('Size of vocabulary: {}'.format(len(vocab))) pretrained_embedding = torch.Tensor(corpus[5]) cnn_feature_size = 2048 c3d_feature_size = 4096 i3d_feature_size = 400 eco_feature_size = 1536 res_eco_features_size = 3584 cnn_global_size = 512 projected_size = 512 hidden_size = 1024 mid_size = 128 n_tags = 300 global_tagger_hidden_size = 1024 specific_tagger_hidden_size = 128 hidden_size = 1024 embedding_size = 300 rnn_in_size = 300 rnn_hidden_size = 1024 config = ConfigurationFile(os.path.join(args.dataset_folder, 'config.ini'), 'sem-syn-cn-max') encoder = SCNEncoder(cnn_feature_size=cnn_feature_size, c3d_feature_size=c3d_feature_size, i3d_feature_size=i3d_feature_size, eco_feature_size=eco_feature_size, res_eco_features_size=res_eco_features_size, n_tags=n_tags, hidden_size=hidden_size, global_tagger_hidden_size=global_tagger_hidden_size, specific_tagger_hidden_size=specific_tagger_hidden_size, n_layers=config.encoder_num_layers, input_dropout_p=config.encoder_dropout_p, rnn_dropout_p=config.encoder_dropout_p, bidirectional=config.encoder_bidirectional, rnn_cell=config.encoder_rnn_cell, device='cpu') decoder = SemSynANDecoder(in_seq_length=config.max_frames, out_seq_length=config.max_words, n_feats=res_eco_features_size + cnn_global_size, n_tags=n_tags + 400, n_pos_emb=512, embedding_size=embedding_size, pretrained_embedding=pretrained_embedding, hidden_size=hidden_size, rnn_in_size=rnn_in_size, rnn_hidden_size=rnn_hidden_size, vocab=vocab, device='cpu', rnn_cell=config.decoder_rnn_cell, encoder_num_layers=config.encoder_num_layers, encoder_bidirectional=config.encoder_bidirectional, num_layers=config.decoder_num_layers, dropout_p=config.decoder_dropout_p, beam_size=config.decoder_beam_size, temperature=config.decoder_temperature, train_sample_max=config.decoder_train_sample_max, test_sample_max=config.decoder_test_sample_max, beam_search_logic=config.decoder_beam_search_logic, dataset_name=config.dataset_name) checkpoint = torch.load(args.checkpoint_path, map_location='cpu') chckpt_dict = {k: v for k, v in checkpoint['encoder'].items() if k not in ['fc1.weight', 'fc1.bias', 'fc2.weight', 'fc2.bias']} encoder_dict = encoder.state_dict() encoder_dict.update(chckpt_dict) encoder.load_state_dict(encoder_dict) decoder.load_state_dict(checkpoint['decoder']) test_vidxs = sorted(list(set(corpus[2][1]))) with h5py.File(os.path.join(args.dataset_folder, config.features_path), 'r') as feats_file: print('loading visual feats...') dataset = feats_file[config.dataset_name] cnn_feats = torch.from_numpy(dataset['cnn_features'][test_vidxs]).float() c3d_feats = torch.from_numpy(dataset['c3d_features'][test_vidxs]).float() cnn_globals = torch.zeros(cnn_feats.size(0), 512) cnn_sem_globals = torch.from_numpy(dataset['cnn_sem_globals'][test_vidxs]).float() f_counts = dataset['count_features'][test_vidxs] print('visual feats loaded') res_eco_globals = torch.from_numpy(np.load(os.path.join(args.dataset_folder, 'resnext_eco.npy'))[test_vidxs]) tags_globals = torch.from_numpy(np.load(os.path.join(args.dataset_folder, 'tag_feats.npy'))[test_vidxs]) encoder.eval() decoder.eval() with torch.no_grad(): video_encoded = encoder(cnn_feats, c3d_feats, cnn_globals, cnn_sem_globals, tags_globals, res_eco_globals) logits, tokens = decoder(video_encoded, None, teacher_forcing_ratio=0) scores = logits.max(dim=2)[0].mean(dim=1) confidences, sentences = [], [] for score, seq in zip(scores, tokens): s = decode_from_tokens(seq, vocab) print(score, s) sentences.append(s) confidences.append(score) if not os.path.exists(args.output_folder): os.makedirs(args.output_folder) with open(os.path.join(args.output_folder, 'predictions.txt'), 'w') as fo: for vidx, sentence in zip(test_vidxs, sentences): fo.write(f'{vidx}\t{sentence}\n')
true
true
f72a4d13a6ccfb3a394f61f2c8c520771408032b
3,484
py
Python
app/routers/images.py
vncsna/mirror
0de84de6fa4f8a4569beed0bf2e313901d95a17d
[ "MIT" ]
null
null
null
app/routers/images.py
vncsna/mirror
0de84de6fa4f8a4569beed0bf2e313901d95a17d
[ "MIT" ]
null
null
null
app/routers/images.py
vncsna/mirror
0de84de6fa4f8a4569beed0bf2e313901d95a17d
[ "MIT" ]
null
null
null
# TODO: Add exception checking # TODO: Use wrong uuids as input import os import cv2 import shutil import numpy as np from enum import Enum from uuid import uuid4 from pathlib import Path from dotenv import load_dotenv from fastapi import APIRouter, File, UploadFile from fastapi.responses import FileResponse load_dotenv() DATABASE_IMGE = os.environ['DATABASE_IMGE'] DATABASE_TEXT = os.environ['DATABASE_TEXT'] HAAR_CLF_PATH = os.environ['HAAR_CLF_PATH'] CASCADE_CLASSIFIER = cv2.CascadeClassifier(HAAR_CLF_PATH) # --------------------------------------- class FilterName(str, Enum): blur = "blur" cover = "cover" pixelate = "pixelate" # --------------------------------------- router = APIRouter(tags=['Image']) @router.post('/image') def create_image(image: UploadFile = File(...)): uuid = uuid4() with open(f'{DATABASE_IMGE}/{uuid}.png', 'wb') as buffer: shutil.copyfileobj(image.file, buffer) return {'uuid': uuid} @router.get('/image/{uuid}') def read_image(uuid: str): filepath = Path(f'{DATABASE_IMGE}/{uuid}.png') return FileResponse(filepath) @router.put('/image/{uuid}') def update_image(uuid: str, image: UploadFile = File(...)): with open(f'{DATABASE_IMGE}/{uuid}.png', 'wb') as buffer: shutil.copyfileobj(image.file, buffer) return {'uuid': uuid} @router.delete('/image/{uuid}') def delete_image(uuid: str): filepath = Path(f'{DATABASE_IMGE}/{uuid}.png') filepath.unlink() return {'uuid': uuid} @router.get('/image/{uuid}/{filter_}') def transform_image(uuid: str, filter_: FilterName): filepath = f'{DATABASE_IMGE}/{uuid}.png' image = cv2.imread(str(filepath)) if filter_ == FilterName.blur: anonymized_image = anonymize_faces(image, blur) elif filter_ == FilterName.cover: anonymized_image = anonymize_faces(image, cover) elif filter_ == FilterName.pixelate: anonymized_image = anonymize_faces(image, pixelate) new_filepath = f'{DATABASE_IMGE}/{uuid}-{filter_}.png' cv2.imwrite(new_filepath, anonymized_image) return FileResponse(new_filepath) @router.get('/images') def read_images(): uuids = Path(f'{DATABASE_IMGE}').glob('*') uuids = [uuid.stem for uuid in uuids] return {'uuids': uuids} # --------------------------------------- def blur(img, factor=3.0): # auto determine the size of blurring kernel (h, w) = img.shape[:2] kW = int(w / factor) kH = int(h / factor) # ensure that width and height are odd kW = kW if kW % 2 != 0 else kW - 1 kH = kH if kH % 2 != 0 else kH - 1 # apply a gaussian blue to image return cv2.GaussianBlur(img, (kW, kH), 0) def cover(img): return np.zeros_like(img) def pixelate(img): height, width = img.shape[:2] # downscale image output = cv2.resize( img, (6, 6), interpolation=cv2.INTER_LINEAR) # upscale image output = cv2.resize( output, (width, height), interpolation=cv2.INTER_NEAREST) return output def anonymize_faces(img, filtr): # transform color to gray gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # detect region of interest with # a haar cascade feature classifier faces = CASCADE_CLASSIFIER.detectMultiScale(gray, 1.1, 4) # loop faces and apply filter for (x0, y0, width, height) in faces: face = img[x0:x0 + width, y0:y0 + height, :] img[x0:x0 + width, y0:y0 + height, :] = filtr(face) return img
28.325203
65
0.642078
import os import cv2 import shutil import numpy as np from enum import Enum from uuid import uuid4 from pathlib import Path from dotenv import load_dotenv from fastapi import APIRouter, File, UploadFile from fastapi.responses import FileResponse load_dotenv() DATABASE_IMGE = os.environ['DATABASE_IMGE'] DATABASE_TEXT = os.environ['DATABASE_TEXT'] HAAR_CLF_PATH = os.environ['HAAR_CLF_PATH'] CASCADE_CLASSIFIER = cv2.CascadeClassifier(HAAR_CLF_PATH) class FilterName(str, Enum): blur = "blur" cover = "cover" pixelate = "pixelate" router = APIRouter(tags=['Image']) @router.post('/image') def create_image(image: UploadFile = File(...)): uuid = uuid4() with open(f'{DATABASE_IMGE}/{uuid}.png', 'wb') as buffer: shutil.copyfileobj(image.file, buffer) return {'uuid': uuid} @router.get('/image/{uuid}') def read_image(uuid: str): filepath = Path(f'{DATABASE_IMGE}/{uuid}.png') return FileResponse(filepath) @router.put('/image/{uuid}') def update_image(uuid: str, image: UploadFile = File(...)): with open(f'{DATABASE_IMGE}/{uuid}.png', 'wb') as buffer: shutil.copyfileobj(image.file, buffer) return {'uuid': uuid} @router.delete('/image/{uuid}') def delete_image(uuid: str): filepath = Path(f'{DATABASE_IMGE}/{uuid}.png') filepath.unlink() return {'uuid': uuid} @router.get('/image/{uuid}/{filter_}') def transform_image(uuid: str, filter_: FilterName): filepath = f'{DATABASE_IMGE}/{uuid}.png' image = cv2.imread(str(filepath)) if filter_ == FilterName.blur: anonymized_image = anonymize_faces(image, blur) elif filter_ == FilterName.cover: anonymized_image = anonymize_faces(image, cover) elif filter_ == FilterName.pixelate: anonymized_image = anonymize_faces(image, pixelate) new_filepath = f'{DATABASE_IMGE}/{uuid}-{filter_}.png' cv2.imwrite(new_filepath, anonymized_image) return FileResponse(new_filepath) @router.get('/images') def read_images(): uuids = Path(f'{DATABASE_IMGE}').glob('*') uuids = [uuid.stem for uuid in uuids] return {'uuids': uuids} def blur(img, factor=3.0): (h, w) = img.shape[:2] kW = int(w / factor) kH = int(h / factor) kW = kW if kW % 2 != 0 else kW - 1 kH = kH if kH % 2 != 0 else kH - 1 return cv2.GaussianBlur(img, (kW, kH), 0) def cover(img): return np.zeros_like(img) def pixelate(img): height, width = img.shape[:2] output = cv2.resize( img, (6, 6), interpolation=cv2.INTER_LINEAR) output = cv2.resize( output, (width, height), interpolation=cv2.INTER_NEAREST) return output def anonymize_faces(img, filtr): gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = CASCADE_CLASSIFIER.detectMultiScale(gray, 1.1, 4) for (x0, y0, width, height) in faces: face = img[x0:x0 + width, y0:y0 + height, :] img[x0:x0 + width, y0:y0 + height, :] = filtr(face) return img
true
true
f72a4dac3ecef7e475c42ce8919f2ec459aa9f6e
1,352
py
Python
Chapter05_Serial-IO/serialOrgan/scaleGenerator.py
ONEV2/AVR-Programming
31ac43d0ea353a6878079e15c1e1bda6a31da4c0
[ "MIT" ]
608
2015-01-01T23:22:28.000Z
2022-03-25T23:40:47.000Z
Chapter05_Serial-IO/serialOrgan/scaleGenerator.py
Omsingh24/AVR-Programming
8a9ad403ccf2f6cceef955e3813e476da3df7f62
[ "MIT" ]
41
2015-01-14T05:49:48.000Z
2022-01-22T07:07:24.000Z
Chapter05_Serial-IO/serialOrgan/scaleGenerator.py
Omsingh24/AVR-Programming
8a9ad403ccf2f6cceef955e3813e476da3df7f62
[ "MIT" ]
340
2015-01-06T18:32:28.000Z
2022-03-31T18:20:44.000Z
# scaleGenerator.py # Scales are in terms of times per cycle (period) rather # than pitch. # import math SCALE = ['C', 'Cx', 'D', 'Dx', 'E', 'F', 'Fx', 'G', 'Gx', 'A', 'Ax', 'B'] def calculateOctave(baseLength): periods = [baseLength / math.exp(x*math.log(2)/12) for x in range(0, 12)] periods = [int(round(x)) for x in periods] return( zip(SCALE, periods) ) def makePitches(basePitch, numOctaves): pitchList = [] for octave in range(0, numOctaves): for note, period in calculateOctave(basePitch / 2**octave): if period < 65500: noteString = note + str(octave) pitchList.append((noteString,period)) return(pitchList) def makeDefines(basePitch, numOctaves): pitchList = makePitches(basePitch, numOctaves) defineString = "// Scale in the key of {} \n".format(basePitch) defineString += "// Automatically generated by scaleGenerator.py \n\n" for (note, length) in pitchList: defineString += "#define {:<5}{:>6}\n".format(note, length) return(defineString) if __name__ == "__main__": ## Change these if you like BASEPITCH = 25000 OCTAVES = 8 OUTFILE = "scale16.h" ## Write it out to a file out = open(OUTFILE, "w") out.write(makeDefines(BASEPITCH, OCTAVES)) out.close()
28.765957
77
0.607988
import math SCALE = ['C', 'Cx', 'D', 'Dx', 'E', 'F', 'Fx', 'G', 'Gx', 'A', 'Ax', 'B'] def calculateOctave(baseLength): periods = [baseLength / math.exp(x*math.log(2)/12) for x in range(0, 12)] periods = [int(round(x)) for x in periods] return( zip(SCALE, periods) ) def makePitches(basePitch, numOctaves): pitchList = [] for octave in range(0, numOctaves): for note, period in calculateOctave(basePitch / 2**octave): if period < 65500: noteString = note + str(octave) pitchList.append((noteString,period)) return(pitchList) def makeDefines(basePitch, numOctaves): pitchList = makePitches(basePitch, numOctaves) defineString = "// Scale in the key of {} \n".format(basePitch) defineString += "// Automatically generated by scaleGenerator.py \n\n" for (note, length) in pitchList: defineString += "#define {:<5}{:>6}\n".format(note, length) return(defineString) if __name__ == "__main__": OCTAVES = 8 OUTFILE = "scale16.h" "w") out.write(makeDefines(BASEPITCH, OCTAVES)) out.close()
true
true
f72a4dfe4c34ef1aa9ab86723b47cf9341cad810
3,823
py
Python
scripts/o3de/tests/unit_test_project_properties.py
sandeel31/o3de
db88812d61eef77c6f4451b7f8c7605d6db07412
[ "Apache-2.0", "MIT" ]
1
2021-08-04T00:43:18.000Z
2021-08-04T00:43:18.000Z
scripts/o3de/tests/unit_test_project_properties.py
sandeel31/o3de
db88812d61eef77c6f4451b7f8c7605d6db07412
[ "Apache-2.0", "MIT" ]
null
null
null
scripts/o3de/tests/unit_test_project_properties.py
sandeel31/o3de
db88812d61eef77c6f4451b7f8c7605d6db07412
[ "Apache-2.0", "MIT" ]
null
null
null
# # Copyright (c) Contributors to the Open 3D Engine Project. # For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # # import pytest import pathlib from unittest.mock import patch from o3de import project_properties TEST_DEFAULT_PROJECT_DATA = { "template_name": "DefaultProject", "restricted_name": "o3de", "restricted_platform_relative_path": "Templates", "origin": "The primary repo for DefaultProject goes here: i.e. http://www.mydomain.com", "license": "What license DefaultProject uses goes here: i.e. https://opensource.org/licenses/MIT", "display_name": "Default", "summary": "A short description of DefaultProject.", "included_gems": ["Atom","Camera","EMotionFX","UI","Maestro","Input","ImGui"], "canonical_tags": [], "user_tags": [ "DefaultProject" ], "icon_path": "preview.png" } @pytest.fixture(scope='class') def init_project_json_data(request): class ProjectJsonData: def __init__(self): self.data = TEST_DEFAULT_PROJECT_DATA request.cls.project_json = ProjectJsonData() @pytest.mark.usefixtures('init_project_json_data') class TestEditProjectProperties: @pytest.mark.parametrize("project_path, project_name, project_new_name, project_origin, project_display,\ project_summary, project_icon, add_tags, delete_tags,\ replace_tags, expected_result", [ pytest.param(pathlib.PurePath('E:/TestProject'), 'test', 'test', 'editing by pytest', 'Unit Test', 'pyTest project', 'pytest.bmp', 'A B C', 'B', 'D E F', 0), pytest.param('', 'test', 'test', 'editing by pytest', 'Unit Test', 'pyTest project', 'pytest.bmp', 'A B C', 'B', 'D E F', 1) ] ) def test_edit_project_properties(self, project_path, project_name, project_new_name, project_origin, project_display, project_summary, project_icon, add_tags, delete_tags, replace_tags, expected_result): def get_project_json_data(project_name: str, project_path) -> dict: if not project_path: self.project_json.data = None return None return self.project_json.data def save_o3de_manifest(new_proj_data: dict, project_path) -> bool: self.project_json.data = new_proj_data return True with patch('o3de.manifest.get_project_json_data', side_effect=get_project_json_data) as get_project_json_data_patch, \ patch('o3de.manifest.save_o3de_manifest', side_effect=save_o3de_manifest) as save_o3de_manifest_patch: result = project_properties.edit_project_props(project_path, project_name, project_new_name, project_origin, project_display, project_summary, project_icon, add_tags, delete_tags, replace_tags) assert result == expected_result if project_path: assert self.project_json.data assert self.project_json.data.get('origin', '') == project_origin assert self.project_json.data.get('display_name', '') == project_display assert self.project_json.data.get('summary', '') == project_summary assert self.project_json.data.get('icon_path', '') == project_icon expected_tag_set = set(replace_tags.split()) project_json_tag_set = set(self.project_json.data.get('user_tags', [])) assert project_json_tag_set == expected_tag_set else: assert not self.project_json.data
46.621951
126
0.637719
import pytest import pathlib from unittest.mock import patch from o3de import project_properties TEST_DEFAULT_PROJECT_DATA = { "template_name": "DefaultProject", "restricted_name": "o3de", "restricted_platform_relative_path": "Templates", "origin": "The primary repo for DefaultProject goes here: i.e. http://www.mydomain.com", "license": "What license DefaultProject uses goes here: i.e. https://opensource.org/licenses/MIT", "display_name": "Default", "summary": "A short description of DefaultProject.", "included_gems": ["Atom","Camera","EMotionFX","UI","Maestro","Input","ImGui"], "canonical_tags": [], "user_tags": [ "DefaultProject" ], "icon_path": "preview.png" } @pytest.fixture(scope='class') def init_project_json_data(request): class ProjectJsonData: def __init__(self): self.data = TEST_DEFAULT_PROJECT_DATA request.cls.project_json = ProjectJsonData() @pytest.mark.usefixtures('init_project_json_data') class TestEditProjectProperties: @pytest.mark.parametrize("project_path, project_name, project_new_name, project_origin, project_display,\ project_summary, project_icon, add_tags, delete_tags,\ replace_tags, expected_result", [ pytest.param(pathlib.PurePath('E:/TestProject'), 'test', 'test', 'editing by pytest', 'Unit Test', 'pyTest project', 'pytest.bmp', 'A B C', 'B', 'D E F', 0), pytest.param('', 'test', 'test', 'editing by pytest', 'Unit Test', 'pyTest project', 'pytest.bmp', 'A B C', 'B', 'D E F', 1) ] ) def test_edit_project_properties(self, project_path, project_name, project_new_name, project_origin, project_display, project_summary, project_icon, add_tags, delete_tags, replace_tags, expected_result): def get_project_json_data(project_name: str, project_path) -> dict: if not project_path: self.project_json.data = None return None return self.project_json.data def save_o3de_manifest(new_proj_data: dict, project_path) -> bool: self.project_json.data = new_proj_data return True with patch('o3de.manifest.get_project_json_data', side_effect=get_project_json_data) as get_project_json_data_patch, \ patch('o3de.manifest.save_o3de_manifest', side_effect=save_o3de_manifest) as save_o3de_manifest_patch: result = project_properties.edit_project_props(project_path, project_name, project_new_name, project_origin, project_display, project_summary, project_icon, add_tags, delete_tags, replace_tags) assert result == expected_result if project_path: assert self.project_json.data assert self.project_json.data.get('origin', '') == project_origin assert self.project_json.data.get('display_name', '') == project_display assert self.project_json.data.get('summary', '') == project_summary assert self.project_json.data.get('icon_path', '') == project_icon expected_tag_set = set(replace_tags.split()) project_json_tag_set = set(self.project_json.data.get('user_tags', [])) assert project_json_tag_set == expected_tag_set else: assert not self.project_json.data
true
true
f72a4e0d8cbc89c9de5ee0df61f78d7d32bde73e
73,927
py
Python
tensorflow/contrib/lite/testing/generate_examples.py
noahl/tensorflow
b95d8cce7323d328565378e0d60d72603393f87d
[ "Apache-2.0" ]
5
2018-09-22T20:16:46.000Z
2022-02-28T10:35:19.000Z
tensorflow/contrib/lite/testing/generate_examples.py
noahl/tensorflow
b95d8cce7323d328565378e0d60d72603393f87d
[ "Apache-2.0" ]
null
null
null
tensorflow/contrib/lite/testing/generate_examples.py
noahl/tensorflow
b95d8cce7323d328565378e0d60d72603393f87d
[ "Apache-2.0" ]
2
2019-08-14T09:04:37.000Z
2022-02-02T20:08:02.000Z
# Copyright 2017 The TensorFlow Authors. 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. # ============================================================================== """Generate a series of TensorFlow graphs that become tflite test cases. Usage: generate_examples <output directory> bazel run //tensorflow/contrib/lite/testing:generate_examples """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import itertools import os import re import sys import tempfile import traceback import zipfile import numpy as np from six import StringIO from six.moves import xrange # TODO(aselle): Disable GPU for now os.environ["CUDA_VISIBLE_DEVICES"] = "-1" # pylint: disable=g-import-not-at-top import tensorflow as tf from google.protobuf import text_format # TODO(aselle): switch to TensorFlow's resource_loader from tensorflow.contrib.lite.testing import generate_examples_report as report_lib from tensorflow.python.framework import graph_util as tf_graph_util from tensorflow.python.ops import rnn parser = argparse.ArgumentParser(description="Script to generate TFLite tests.") parser.add_argument("output_path", help="Directory where the outputs will be go.") parser.add_argument("--zip_to_output", type=str, help="Particular zip to output.", required=False) parser.add_argument("--toco", type=str, help="Path to toco tool.", required=True) parser.add_argument( "--known_bugs_are_errors", action="store_true", help=("If a particular model is affected by a known bug," " count it as a toco error.")) parser.add_argument( "--ignore_toco_errors", action="store_true", help="Raise an exception if any toco error is encountered.") parser.add_argument( "--save_graphdefs", action="store_true", help="Include intermediate graphdefs in the output zip files.") RANDOM_SEED = 342 TEST_INPUT_DEPTH = 3 # A map from regular expression to bug number. Any test failure with label # matching the expression will be considered due to the corresponding bug. KNOWN_BUGS = { # TOCO doesn't support scalars as input. r"relu.*input_shape=\[\]": "67587484", r"sigmoid.*input_shape=\[\]": "67645668", # Concat doesn't work with a single input tensor r"concat.*num_tensors=1": "67378344", # Transposition in MatMul is not supported. r"fully_connected.*transpose_.=True": "67586970", # Softmax graphs are too complex. r"softmax.*dim=0": "67749831", r"softmax.*input_shape=\[1,3,4,3\]": "67749831", # SpaceToDepth only supports float32. r"space_to_depth.*(float16|int32|uint8|int64)": "68018134", # BatchToSpaceND only supports 4D tensors. r"batch_to_space_nd.*input_shape=\[8,2,2,2,1,1\]": "70594733", # Div will use floordiv. r"div.*int32": "72051395", # TOCO require matching dimensions in strided_slice. r"strided_slice.*begin=\[0\].*end=\[1\].*": "73170889", # No support for SplitV r"split.*num_or_size_splits=\[2,2\]": "73377559", # Needs support for dimensions other than the last one in argmax. r"arg_max.*axis=0.*": "77546240", r"arg_max.*axis=1.*": "77546240", r"arg_max.*axis=2.*": "77546240", } class ExtraTocoOptions(object): """Additonal toco options besides input, output, shape.""" def __init__(self): # Whether to ignore control dependency nodes. self.drop_control_dependency = False # Allow custom ops in the toco conversion. self.allow_custom_ops = False # Rnn states that are used to support rnn / lstm cells. self.rnn_states = None def toco_options(data_types, input_arrays, output_arrays, shapes, extra_toco_options=ExtraTocoOptions()): """Create TOCO options to process a model. Args: data_types: input and inference types used by TOCO. input_arrays: names of the input tensors output_arrays: name of the output tensors shapes: shapes of the input tensors extra_toco_options: additional toco options Returns: the options in a string. """ shape_str = ":".join([",".join(str(y) for y in x) for x in shapes]) inference_type = "FLOAT" # TODO(ahentz): if we get multi-input quantization to work we need this # to change if data_types[0] == "QUANTIZED_UINT8": inference_type = "QUANTIZED_UINT8" s = (" --input_data_types=%s" % ",".join(data_types) + " --inference_type=%s" % inference_type + " --input_format=TENSORFLOW_GRAPHDEF" + " --output_format=TFLITE" + " --input_arrays=%s" % ",".join(input_arrays) + " --input_shapes=%s" % shape_str + " --output_arrays=%s" % ",".join(output_arrays)) if extra_toco_options.drop_control_dependency: s += " --drop_control_dependency" if extra_toco_options.allow_custom_ops: s += " --allow_custom_ops" if extra_toco_options.rnn_states: s += (" --rnn_states='" + extra_toco_options.rnn_states + "'") return s def write_examples(fp, examples): """Given a list `examples`, write a text format representation. The file format is csv like with a simple repeated pattern. We would ike to use proto here, but we can't yet due to interfacing with the Android team using this format. Args: fp: File-like object to write to. examples: Example dictionary consiting of keys "inputs" and "outputs" """ def write_tensor(fp, x): """Write tensor in file format supported by TFLITE example.""" fp.write("dtype,%s\n" % x.dtype) fp.write("shape," + ",".join(map(str, x.shape)) + "\n") # Output 9 digits after the point to ensure the precision is good enough. values = ["{:.9f}".format(value) for value in list(x.flatten())] fp.write("values," + ",".join(values) + "\n") fp.write("test_cases,%d\n" % len(examples)) for example in examples: fp.write("inputs,%d\n" % len(example["inputs"])) for i in example["inputs"]: write_tensor(fp, i) fp.write("outputs,%d\n" % len(example["outputs"])) for i in example["outputs"]: write_tensor(fp, i) def write_test_cases(fp, model_name, examples): """Given a dictionary of `examples`, write a text format representation. The file format is protocol-buffer-like, even though we don't use proto due to the needs of the Android team. Args: fp: File-like object to write to. model_name: Filename where the model was written to, relative to filename. examples: Example dictionary consiting of keys "inputs" and "outputs" """ fp.write("load_model: %s\n" % os.path.basename(model_name)) for example in examples: fp.write("reshape {\n") for t in example["inputs"]: fp.write(" input: \"" + ",".join(map(str, t.shape)) + "\"\n") fp.write("}\n") fp.write("invoke {\n") for t in example["inputs"]: values = ["{:.9f}".format(value) for value in list(t.flatten())] fp.write(" input: \"" + ",".join(values) + "\"\n") for t in example["outputs"]: values = ["{:.9f}".format(value) for value in list(t.flatten())] fp.write(" output: \"" + ",".join(values) + "\"\n") fp.write("}\n") _TF_TYPE_INFO = { tf.float32: (np.float32, "FLOAT"), tf.float16: (np.float16, "FLOAT"), tf.int32: (np.int32, "INT32"), tf.uint8: (np.uint8, "QUANTIZED_UINT8"), tf.int64: (np.int64, "INT64"), } def create_tensor_data(dtype, shape, min_value=-100, max_value=100): """Build tensor data spreading the range [min_value, max_value).""" if dtype in _TF_TYPE_INFO: dtype = _TF_TYPE_INFO[dtype][0] if dtype in (tf.float32, tf.float16): value = (max_value-min_value)*np.random.random_sample(shape)+min_value elif dtype in (tf.int32, tf.uint8, tf.int64): value = np.random.randint(min_value, max_value+1, shape) return value.astype(dtype) def freeze_graph(session, outputs): """Freeze the current graph. Args: session: Tensorflow sessions containing the graph outputs: List of output tensors Returns: The frozen graph_def. """ return tf_graph_util.convert_variables_to_constants( session, session.graph.as_graph_def(), [x.op.name for x in outputs]) def make_control_dep_tests(zip_path): """Make a set of tests that use control dependencies.""" test_parameters = [{ "input_shape": [[], [1, 1, 1, 1], [1, 15, 14, 1], [3, 15, 14, 3]], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) filter_value = tf.zeros((3, 3, TEST_INPUT_DEPTH, 8), tf.float32) assert_op = tf.assert_greater_equal(input_tensor, input_tensor - 1) with tf.control_dependencies([assert_op]): out = tf.nn.conv2d(input_tensor, filter_value, strides=(1, 1, 1, 1), padding="SAME") return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(tf.float32, parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) extra_toco_options = ExtraTocoOptions() extra_toco_options.drop_control_dependency = True make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs, extra_toco_options) def toco_convert(graph_def_str, input_tensors, output_tensors, extra_toco_options): """Convert a model's graph def into a tflite model. NOTE: this currently shells out to the toco binary, but we would like convert to Python API tooling in the future. Args: graph_def_str: Graph def proto in serialized string format. input_tensors: List of input tensor tuples `(name, shape, type)`. output_tensors: List of output tensors (names). extra_toco_options: Additional toco options. Returns: output tflite model, log_txt from conversion or None, log_txt if it did not convert properly. """ data_types = [_TF_TYPE_INFO[x[2]][1] for x in input_tensors] opts = toco_options( data_types=data_types, input_arrays=[x[0] for x in input_tensors], shapes=[x[1] for x in input_tensors], output_arrays=output_tensors, extra_toco_options=extra_toco_options) with tempfile.NamedTemporaryFile() as graphdef_file, \ tempfile.NamedTemporaryFile() as output_file, \ tempfile.NamedTemporaryFile("w+") as stdout_file: graphdef_file.write(graph_def_str) graphdef_file.flush() # TODO(aselle): Switch this to subprocess at some point. cmd = ("%s --input_file=%s --output_file=%s %s > %s 2>&1" % (bin_path, graphdef_file.name, output_file.name, opts, stdout_file.name)) exit_code = os.system(cmd) log = ( cmd + "exited with code %d" % exit_code + "\n------------------\n" + stdout_file.read()) return (None if exit_code != 0 else output_file.read()), log def normalize_output_name(output_name): """Remove :0 suffix from tensor names.""" return output_name.split(":")[0] if output_name.endswith( ":0") else output_name def make_zip_of_tests(zip_path, test_parameters, make_graph, make_test_inputs, extra_toco_options=ExtraTocoOptions(), use_frozen_graph=False): """Helper to make a zip file of a bunch of TensorFlow models. This does a cartestian product of the dictionary of test_parameters and calls make_graph() for each item in the cartestian product set. If the graph is built successfully, then make_test_inputs() is called to build expected input/output value pairs. The model is then converted to tflite with toco, and the examples are serialized with the tflite model into a zip file (2 files per item in the cartesian product set). Args: zip_path: Path of zip file to write test_parameters: Dictionary mapping to lists for each parameter. e.g. `{"strides": [[1,3,3,1], [1,2,2,1]], "foo": [1.2, 1.3]}` make_graph: function that takes current parameters and returns tuple `[input1, input2, ...], [output1, output2, ...]` make_test_inputs: function taking `curr_params`, `session`, `input_tensors`, `output_tensors` and returns tuple `(input_values, output_values)`. extra_toco_options: Additional toco options. use_frozen_graph: Whether or not freeze graph before toco converter. Raises: RuntimeError: if there are toco errors that can't be ignored. """ # TODO(aselle): Make this allow multiple inputs outputs. archive = zipfile.PyZipFile(zip_path, "w") zip_manifest = [] convert_report = [] toco_errors = 0 for parameters in test_parameters: keys = parameters.keys() for curr in itertools.product(*parameters.values()): label = zip_path.replace(".zip", "") + (",".join( "%s=%r" % z for z in sorted(zip(keys, curr))).replace(" ", "")) if label[0] == "/": label = label[1:] param_dict = dict(zip(keys, curr)) def build_example(label, param_dict_real): """Build the model with parameter values set in param_dict_real. Args: label: Label of the model (i.e. the filename in the zip). param_dict_real: Parameter dictionary (arguments to the factories make_graph and make_test_inputs) Returns: (tflite_model_binary, report) where tflite_model_binary is the serialized flatbuffer as a string and report is a dictionary with keys `toco_log` (log of toco conversion), `tf_log` (log of tf conversion), `toco` (a string of success status of the conversion), `tf` (a string success status of the conversion). """ np.random.seed(RANDOM_SEED) report = {"toco": report_lib.NOTRUN, "tf": report_lib.FAILED} # Build graph report["tf_log"] = "" report["toco_log"] = "" tf.reset_default_graph() with tf.device("/cpu:0"): try: inputs, outputs = make_graph(param_dict_real) except (tf.errors.UnimplementedError, tf.errors.InvalidArgumentError, ValueError): report["tf_log"] += traceback.format_exc() return None, report sess = tf.Session() try: baseline_inputs, baseline_outputs = (make_test_inputs( param_dict_real, sess, inputs, outputs)) except (tf.errors.UnimplementedError, tf.errors.InvalidArgumentError, ValueError): report["tf_log"] += traceback.format_exc() return None, report report["toco"] = report_lib.FAILED report["tf"] = report_lib.SUCCESS # Convert graph to toco input_tensors = [(input_tensor.name.split(":")[0], input_tensor.get_shape(), input_tensor.dtype) for input_tensor in inputs] output_tensors = [normalize_output_name(out.name) for out in outputs] graph_def = freeze_graph( sess, tf.global_variables() + inputs + outputs) if use_frozen_graph else sess.graph_def tflite_model_binary, toco_log = toco_convert( graph_def.SerializeToString(), input_tensors, output_tensors, extra_toco_options) report["toco"] = (report_lib.SUCCESS if tflite_model_binary is not None else report_lib.FAILED) report["toco_log"] = toco_log if FLAGS.save_graphdefs: archive.writestr(label + ".pb", text_format.MessageToString(graph_def), zipfile.ZIP_DEFLATED) if tflite_model_binary: archive.writestr(label + ".bin", tflite_model_binary, zipfile.ZIP_DEFLATED) example = {"inputs": baseline_inputs, "outputs": baseline_outputs} example_fp = StringIO() write_examples(example_fp, [example]) archive.writestr(label + ".inputs", example_fp.getvalue(), zipfile.ZIP_DEFLATED) example_fp2 = StringIO() write_test_cases(example_fp2, label + ".bin", [example]) archive.writestr(label + "_tests.txt", example_fp2.getvalue(), zipfile.ZIP_DEFLATED) zip_manifest.append(label + "\n") return tflite_model_binary, report _, report = build_example(label, param_dict) if report["toco"] == report_lib.FAILED: ignore_error = False if not FLAGS.known_bugs_are_errors: for pattern, bug_number in KNOWN_BUGS.items(): if re.search(pattern, label): print("Ignored TOCO error due to bug %s" % bug_number) ignore_error = True if not ignore_error: toco_errors += 1 print("-----------------\ntoco error!\n%s\n-----------------\n" % report["toco_log"]) convert_report.append((param_dict, report)) report_io = StringIO() report_lib.make_report_table(report_io, zip_path, convert_report) archive.writestr("report.html", report_io.getvalue()) archive.writestr("manifest.txt", "".join(zip_manifest), zipfile.ZIP_DEFLATED) # Log statistics of what succeeded total_conversions = len(convert_report) tf_success = sum(1 for x in convert_report if x[1]["tf"] == report_lib.SUCCESS) toco_success = sum(1 for x in convert_report if x[1]["toco"] == report_lib.SUCCESS) percent = 0 if tf_success > 0: percent = float(toco_success) / float(tf_success) * 100. tf.logging.info(("Archive %s Considered %d graphs, %d TF evaluated graphs " " and %d TOCO converted graphs (%.1f%%"), zip_path, total_conversions, tf_success, toco_success, percent) if not FLAGS.ignore_toco_errors and toco_errors > 0: raise RuntimeError( "Found %d errors while generating toco models" % toco_errors) def make_pool_tests(pool_op_in): """Make a set of tests to do average pooling. Args: pool_op_in: TensorFlow pooling operation to test i.e. `tf.nn.avg_pool`. Returns: A function representing the true generator (after curried pool_op_in). """ pool_op = pool_op_in def f(zip_path): """Actual function that generates examples. Args: zip_path: path to write zip to. """ # Chose a set of parameters test_parameters = [{ "ksize": [[2, 1, 1, 2], [1, 1, 1, 1], [1, 1, 2, 1], [1, 10, 11, 1]], "strides": [[2, 1, 1, 2], [1, 1, 1, 1], [1, 1, 2, 1], [1, 10, 11, 1]], # TODO(aselle): should add in a degenerate shape (e.g. [1, 0, 1, 1]). "input_shape": [[], [1, 1, 1, 1], [1, 15, 14, 1], [3, 15, 14, 3]], "padding": ["SAME", "VALID"], "data_format": ["NHWC"], # TODO(aselle): NCHW would be good }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) out = pool_op( input_tensor, ksize=parameters["ksize"], strides=parameters["strides"], data_format=parameters["data_format"], padding=parameters["padding"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(tf.float32, parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) return f def make_l2_pool_tests(zip_path): make_pool_tests(make_l2_pool)(zip_path) def make_avg_pool_tests(zip_path): make_pool_tests(tf.nn.avg_pool)(zip_path) def make_max_pool_tests(zip_path): make_pool_tests(tf.nn.max_pool)(zip_path) def make_relu_tests(zip_path): """Make a set of tests to do relu.""" # Chose a set of parameters test_parameters = [{ "input_shape": [[], [1], [2, 3], [1, 1, 1, 1], [1, 3, 4, 3], [3, 15, 14, 3], [3, 1, 2, 4, 6], [2, 2, 3, 4, 5, 6]], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) out = tf.nn.relu(input_tensor) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data( np.float32, parameters["input_shape"], min_value=-4, max_value=10) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_relu1_tests(zip_path): """Make a set of tests to do relu1.""" # Chose a set of parameters test_parameters = [{ "input_shape": [[], [1, 1, 1, 1], [1, 3, 4, 3], [3, 15, 14, 3], [3, 1, 2, 4, 6], [2, 2, 3, 4, 5, 6]], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) # Note that the following is not supported: # out = tf.maximum(-1.0, tf.minimum(input_tensor, 1.0)) out = tf.minimum(1.0, tf.maximum(input_tensor, -1.0)) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data( np.float32, parameters["input_shape"], min_value=-3, max_value=10) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_relu6_tests(zip_path): """Make a set of tests to do relu6.""" # Chose a set of parameters test_parameters = [{ "input_shape": [[], [1, 1, 1, 1], [1, 3, 4, 3], [3, 15, 14, 3], [3, 1, 2, 4, 6], [2, 2, 3, 4, 5, 6]], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) out = tf.nn.relu(input_tensor) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data( np.float32, parameters["input_shape"], min_value=-3, max_value=10) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) # This function tests various TensorFLow functions that generates Const op, # including `tf.ones`, `tf.zeros` and random functions. def make_constant_tests(zip_path): """Make a set of tests to do constant ops.""" test_parameters = [{ "dtype": [tf.float32, tf.int32], "input_shape": [[1], [2], [1, 1, 1, 1], [2, 2, 2, 2]], }] def build_graph(parameters): # Since Toco & Tflite can't have a single constant op in the entire graph, # this test adds a zero tensor with a constant op tensor. input1 = tf.placeholder(dtype=parameters["dtype"], name="input1", shape=parameters["input_shape"]) out = tf.ones(parameters["input_shape"], dtype=parameters["dtype"]) + input1 return [input1], [out] def build_inputs(parameters, sess, inputs, outputs): input1 = np.zeros(parameters["input_shape"], dtype=_TF_TYPE_INFO[parameters["dtype"]][0]) return [input1], sess.run(outputs, feed_dict={inputs[0]: input1}) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_binary_op_tests(zip_path, binary_operator): """Make a set of tests to do add with and without broadcast.""" # These parameters are split because we don't support broadcasting. test_parameters = [{ "dtype": [tf.float32, tf.int32], "input_shape_1": [[1, 3, 4, 3]], "input_shape_2": [[1, 3, 4, 3]], "activation": [True] }, { "dtype": [tf.float32], "input_shape_1": [[5]], "input_shape_2": [[5]], "activation": [False, True] }, { "dtype": [tf.float32], "input_shape_1": [[1, 3, 4, 3]], "input_shape_2": [[3]], "activation": [True] }] def build_graph(parameters): """Builds the graph given the current parameters.""" input1 = tf.placeholder( dtype=parameters["dtype"], name="input1", shape=parameters["input_shape_1"]) input2 = tf.placeholder( dtype=parameters["dtype"], name="input2", shape=parameters["input_shape_2"]) out = binary_operator(input1, input2) if parameters["activation"]: out = tf.nn.relu(out) return [input1, input2], [out] def build_inputs(parameters, sess, inputs, outputs): """Builds operand inputs for op.""" input1 = create_tensor_data(parameters["dtype"], parameters["input_shape_1"]) input2 = create_tensor_data(parameters["dtype"], parameters["input_shape_2"]) return [input1, input2], sess.run( outputs, feed_dict={ inputs[0]: input1, inputs[1]: input2 }) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_mean_tests(zip_path): """Make a set of tests to do mean.""" test_parameters = [{ "input_dtype": [tf.float32, tf.int32, tf.int64], "input_shape": [[3, 2, 4]], "axis": [ None, 0, 1, 2, [0, 1], [0, 2], [1, 2], [0, 1, 2], [1, 0], [2, 0], [2, 1], [2, 1, 0], [2, 0, 1], -1, -2, -3, [1, -1], [0, -1], [-1, 0], [-1, -2, -3], [0, 0, 0], [2, 2, 0], [1, 0, -3, -3] ], "const_axis": [True, False], "keepdims": [True, False], }, { "input_dtype": [tf.float32, tf.int32, tf.int64], "input_shape": [[1, 224, 224, 3]], "axis": [ None, 0, 1, 2, 3, [1, 2], [0, 3], [1, 2, 3], [0, 1, 2, 3], [3, 2, 1, 0], [3, 1, 0, 2], [2, 0], [3, 0], [3, 1], [1, 0], -1, -2, -3, -4, [0, -2], [2, 3, -1, 0], [3, 1, 2, -3], [3, -4], [2, 2, 2], [2, 2, 3], [-3, -3, -4], [-3, 2, 1] ], "const_axis": [True, False], "keepdims": [True, False], }] def build_graph(parameters): """Build the mean op testing graph.""" input_tensor = tf.placeholder( dtype=parameters["input_dtype"], name="input", shape=parameters["input_shape"]) # Get axis as either a placeholder or constants. if parameters["const_axis"]: axis = parameters["axis"] input_tensors = [input_tensor] else: if isinstance(parameters["axis"], list): shape = [len(parameters["axis"])] else: shape = [0] # shape for None or integers. axis = tf.placeholder(dtype=tf.int32, name="axis", shape=shape) input_tensors = [input_tensor, axis] out = tf.reduce_mean( input_tensor, axis=axis, keepdims=parameters["keepdims"]) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["input_dtype"], parameters["input_shape"]) ] if not parameters["const_axis"]: if parameters["axis"]: values.append(np.array(parameters["axis"])) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_exp_tests(zip_path): """Make a set of tests to do exp.""" test_parameters = [{ "input_dtype": [tf.float32], "input_shape": [[3], [1, 100], [4, 2, 3], [5, 224, 224, 3]], }] def build_graph(parameters): """Build the exp op testing graph.""" input_tensor = tf.placeholder( dtype=parameters["input_dtype"], name="input", shape=parameters["input_shape"]) out = tf.exp(input_tensor) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["input_dtype"], parameters["input_shape"], min_value=-100, max_value=9) ] return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_log_softmax_tests(zip_path): """Make a set of tests to do log_softmax.""" test_parameters = [{ "input_dtype": [tf.float32], "input_shape": [[1, 100], [4, 2], [5, 224]], }] def build_graph(parameters): """Build the log_softmax op testing graph.""" input_tensor = tf.placeholder( dtype=parameters["input_dtype"], name="input", shape=parameters["input_shape"]) out = tf.nn.log_softmax(input_tensor) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data( parameters["input_dtype"], parameters["input_shape"], min_value=-100, max_value=9) ] return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_maximum_tests(zip_path): """Make a set of tests to do maximum.""" test_parameters = [{ "input_dtype": [tf.float32], "input_shape_1": [[3], [1, 100], [4, 2, 3], [5, 224, 224, 3]], "input_shape_2": [[3], [1, 100], [4, 2, 3], [5, 224, 224, 3]], }] def build_graph(parameters): """Build the maximum op testing graph.""" input_tensor_1 = tf.placeholder( dtype=parameters["input_dtype"], name="input_1", shape=parameters["input_shape_1"]) input_tensor_2 = tf.placeholder( dtype=parameters["input_dtype"], name="input_2", shape=parameters["input_shape_2"]) out = tf.maximum(input_tensor_1, input_tensor_2) return [input_tensor_1, input_tensor_2], [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["input_dtype"], parameters["input_shape_1"]), create_tensor_data(parameters["input_dtype"], parameters["input_shape_2"]) ] return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_minimum_tests(zip_path): """Make a set of tests to do minimum.""" test_parameters = [{ "input_dtype": [tf.float32], "input_shape_1": [[3], [1, 100], [4, 2, 3], [5, 224, 224, 3]], "input_shape_2": [[3], [1, 100], [4, 2, 3], [5, 224, 224, 3]], }] def build_graph(parameters): """Build the minimum op testing graph.""" input_tensor_1 = tf.placeholder( dtype=parameters["input_dtype"], name="input_1", shape=parameters["input_shape_1"]) input_tensor_2 = tf.placeholder( dtype=parameters["input_dtype"], name="input_2", shape=parameters["input_shape_2"]) out = tf.minimum(input_tensor_1, input_tensor_2) return [input_tensor_1, input_tensor_2], [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["input_dtype"], parameters["input_shape_1"]), create_tensor_data(parameters["input_dtype"], parameters["input_shape_2"]) ] return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_binary_op_tests_func(binary_operator): """Return a function that does a test on a binary operator.""" return lambda zip_path: make_binary_op_tests(zip_path, binary_operator) def make_add_tests(zip_path): make_binary_op_tests(zip_path, tf.add) def make_div_tests(zip_path): make_binary_op_tests(zip_path, tf.div) def make_sub_tests(zip_path): make_binary_op_tests(zip_path, tf.subtract) def make_mul_tests(zip_path): make_binary_op_tests(zip_path, tf.multiply) def make_gather_tests(zip_path): """Make a set of tests to do gather.""" test_parameters = [{ # TODO(mgubin): add string tests when they are supported by Toco. # TODO(mgubin): add tests for Nd indices when they are supported by # TfLite. "params_dtype": [tf.float32, tf.int32], "params_shape": [[10], [1, 2, 20]], "indices_dtype": [tf.int32], "indices_shape": [[3], [5]], "axis": [0, 1], }] def build_graph(parameters): """Build the gather op testing graph.""" params = tf.placeholder( dtype=parameters["params_dtype"], name="params", shape=parameters["params_shape"]) indices = tf.placeholder( dtype=parameters["indices_dtype"], name="indices", shape=parameters["indices_shape"]) out = tf.gather(params, indices, axis=parameters["axis"]) return [params, indices], [out] def build_inputs(parameters, sess, inputs, outputs): params = create_tensor_data(parameters["params_dtype"], parameters["params_shape"]) indices = create_tensor_data(parameters["indices_dtype"], parameters["indices_shape"], 0, parameters["params_shape"][0] - 1) return [params, indices], sess.run( outputs, feed_dict=dict(zip(inputs, [params, indices]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_global_batch_norm_tests(zip_path): """Make a set of tests to do batch_norm_with_global_normalization.""" test_parameters = [{ "dtype": [tf.float32], "input_shape": [[1, 1, 6, 2], [3, 4, 5, 4]], "epsilon": [0.1, 0.0001], "scale_after": [True, False], }] def build_graph(parameters): """Build the global batch norm testing graph.""" input_shape = parameters["input_shape"] scale_shape = input_shape[3] scale = create_tensor_data(parameters["dtype"], scale_shape) offset = create_tensor_data(parameters["dtype"], scale_shape) mean = create_tensor_data(parameters["dtype"], scale_shape) variance = create_tensor_data(parameters["dtype"], scale_shape) x = create_tensor_data(parameters["dtype"], parameters["input_shape"]) x_norm = tf.nn.batch_norm_with_global_normalization( x, mean, variance, scale, offset, parameters["epsilon"], parameters["scale_after"]) input_tensor = tf.placeholder(dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.add(input_tensor, x_norm) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_value = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_value], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_fused_batch_norm_tests(zip_path): """Make a set of tests to do fused_batch_norm.""" test_parameters = [{ "dtype": [tf.float32], "input_shape": [[1, 1, 6, 2]], "epsilon": [0.001, 0.1], }] def build_graph(parameters): """Build the testing graph for fused batch normalization.""" input_shape = parameters["input_shape"] scale_shape = input_shape[3] scale = create_tensor_data(parameters["dtype"], scale_shape) offset = create_tensor_data(parameters["dtype"], scale_shape) mean = create_tensor_data(parameters["dtype"], scale_shape) variance = create_tensor_data(parameters["dtype"], scale_shape) x = create_tensor_data(parameters["dtype"], parameters["input_shape"]) [x_norm, _, _] = tf.nn.fused_batch_norm( x, scale, offset, mean, variance, parameters["epsilon"], data_format="NHWC", is_training=False) input_tensor = tf.placeholder(dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.add(input_tensor, x_norm) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_value = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_value], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_conv_tests(zip_path): """Make a set of tests to do convolution.""" test_parameters = [ { "input_shape": [[1, 3, 4, 3]], "filter_shape": [[1, 1, 3, 2]], "strides": [[1, 1, 1, 1], [1, 2, 3, 1]], "dilations": [[1, 1, 1, 1], [1, 3, 2, 1], [1, 2, 2, 1]], "padding": ["SAME", "VALID"], "data_format": ["NHWC"], # TODO(aselle): NCHW would be good "constant_filter": [True, False], }, { "input_shape": [[2, 14, 14, 2]], "filter_shape": [[6, 6, 2, 2]], "strides": [[1, 1, 1, 1], [1, 2, 3, 1]], "dilations": [[1, 1, 1, 1], [1, 2, 2, 1]], "padding": ["SAME", "VALID"], "data_format": ["NHWC"], # TODO(aselle): NCHW would be good "constant_filter": [True, False], } ] def build_graph(parameters): """Build a conv graph given `parameters`.""" input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) # Get filter input either as a placeholder or constants. Also get a list of # the input tensors that are represented as placeholders. if parameters["constant_filter"]: filter_input = create_tensor_data(np.float32, parameters["filter_shape"]) input_tensors = [input_tensor] else: filter_input = tf.placeholder( dtype=tf.float32, name="filter", shape=parameters["filter_shape"]) input_tensors = [input_tensor, filter_input] out = tf.nn.conv2d( input_tensor, filter_input, strides=parameters["strides"], dilations=parameters["dilations"], padding=parameters["padding"], data_format=parameters["data_format"]) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): # Build list of input values either containing 1 tensor (input) or 2 tensors # (input, filter) based on whether filter is constant or variable input. values = [create_tensor_data(np.float32, parameters["input_shape"])] if not parameters["constant_filter"]: values.append(create_tensor_data(np.float32, parameters["filter_shape"])) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_depthwiseconv_tests(zip_path): """Make a set of tests to do convolution.""" # Tensorflow only supports equal strides test_parameters = [ { "input_shape": [[1, 3, 4, 3], [1, 10, 10, 3]], "filter_size": [[1, 1], [1, 2], [3, 3]], "strides": [[1, 1, 1, 1], [1, 3, 3, 1]], "channel_multiplier": [1, 2], "rate": [[1, 1]], "padding": ["SAME", "VALID"], "data_format": ["NHWC"], "constant_filter": [True, False], }, { "input_shape": [[1, 3, 4, 3]], "filter_size": [[1, 1]], "strides": [[1, 1, 2, 1]], # TF needs [1, x, x, 1] "channel_multiplier": [2], "rate": [[2, 2]], # Only [1, 1] is supported "padding": ["SAME"], "data_format": ["NHWC"], "constant_filter": [True, False], } ] def get_tensor_shapes(parameters): input_shape = parameters["input_shape"] filter_size = parameters["filter_size"] filter_shape = filter_size + [ input_shape[3], parameters["channel_multiplier"] ] return [input_shape, filter_shape] def build_graph(parameters): """Build a depthwise conv graph given `parameters`.""" input_shape, filter_shape = get_tensor_shapes(parameters) input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=input_shape) # Get filter input either as a placeholder or constants. Also get a list of # the input tensors that are represented as placeholders. if parameters["constant_filter"]: filter_input = create_tensor_data(np.float32, filter_shape) input_tensors = [input_tensor] else: filter_input = tf.placeholder( dtype=tf.float32, name="filter", shape=filter_shape) input_tensors = [input_tensor, filter_input] out = tf.nn.depthwise_conv2d( input_tensor, filter_input, strides=parameters["strides"], rate=parameters["rate"], padding=parameters["padding"], data_format=parameters["data_format"]) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): # Build list of input values either containing 1 tensor (input) or 2 tensors # (input, filter) based on whether filter is constant or variable input. input_shape, filter_shape = get_tensor_shapes(parameters) values = [create_tensor_data(np.float32, input_shape)] if not parameters["constant_filter"]: values.append(create_tensor_data(np.float32, filter_shape)) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_split_tests(zip_path): """Make a set of tests to do tf.split.""" test_parameters = [{ "input_shape": [[1, 3, 4, 6], [2, 4, 1], [6, 4], [8]], "num_or_size_splits": [1, 2, 3, 4, 5, [2, 2]], "axis": [0, 1, 2, 3, -4, -3, -2, -1], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) out = tf.split( input_tensor, parameters["num_or_size_splits"], parameters["axis"]) return [input_tensor], out def build_inputs(parameters, sess, inputs, outputs): values = [create_tensor_data(np.float32, parameters["input_shape"])] return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_concat_tests(zip_path): """Make a set of tests to do concatenation.""" test_parameters = [{ "base_shape": [[1, 3, 4, 3], [3, 4]], "num_tensors": [1, 2, 3, 4, 5, 6], "axis": [0, 1, 2, 3, -3, -2, -1], }] def get_shape(parameters, delta): """Return a tweaked version of 'base_shape'.""" axis = parameters["axis"] shape = parameters["base_shape"][:] if axis < 0: axis += len(shape) if axis < len(shape): shape[axis] += delta return shape def build_graph(parameters): all_tensors = [] for n in range(0, parameters["num_tensors"]): input_tensor = tf.placeholder(dtype=tf.float32, name=("input%d" % n), shape=get_shape(parameters, n)) all_tensors.append(input_tensor) out = tf.concat(all_tensors, parameters["axis"]) return all_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): all_values = [] for n in range(0, parameters["num_tensors"]): input_values = create_tensor_data(np.float32, get_shape(parameters, n)) all_values.append(input_values) return all_values, sess.run( outputs, feed_dict=dict(zip(inputs, all_values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_fully_connected_tests(zip_path): """Make a set of tests to do fully_connected.""" test_parameters = [{ "shape1": [[3, 3]], "shape2": [[3, 3]], "transpose_a": [True, False], "transpose_b": [True, False], "constant_filter": [True, False], }, { "shape1": [[4, 4], [1, 4], [4]], "shape2": [[4, 4], [4, 1], [4]], "transpose_a": [False], "transpose_b": [False], "constant_filter": [True, False], }, { "shape1": [[40, 37]], "shape2": [[37, 40]], "transpose_a": [False], "transpose_b": [False], "constant_filter": [True, False], }] def build_graph(parameters): """Build a matmul graph given `parameters`.""" input_tensor1 = tf.placeholder(dtype=tf.float32, name="input1", shape=parameters["shape1"]) # Get input_tensor2 either as a placeholder or constants. Also get a list of # the input tensors that are represented as placeholders. if parameters["constant_filter"]: input_tensor2 = create_tensor_data(np.float32, parameters["shape2"]) input_tensors = [input_tensor1] else: input_tensor2 = tf.placeholder( dtype=tf.float32, name="input2", shape=parameters["shape2"]) input_tensors = [input_tensor1, input_tensor2] out = tf.matmul(input_tensor1, input_tensor2, transpose_a=parameters["transpose_a"], transpose_b=parameters["transpose_b"]) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): # Build list of input values either containing 1 tensor (input_values1) or 2 # tensors (input_values1, input_values2) based on whether the second input # is a constant or variable input. values = [create_tensor_data(np.float32, shape=parameters["shape1"])] if not parameters["constant_filter"]: values.append(create_tensor_data(np.float32, parameters["shape2"])) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_l2norm_tests(zip_path): """Make a set of tests to do l2norm.""" # Chose a set of parameters test_parameters = [{ "input_shape": [[5, 7], [1, 1, 1, 1], [1, 3, 4, 3], [3, 15, 14, 3], [3, 1, 2, 4, 6], [2, 2, 3, 4, 5, 6]], "dim": [0, 1, 2, 3, [2, 3], -2], "epsilon": [None, 1e-12, 1e-3], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) if parameters["epsilon"]: out = tf.nn.l2_normalize( input_tensor, parameters["dim"], epsilon=parameters["epsilon"]) else: out = tf.nn.l2_normalize(input_tensor, parameters["dim"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data( np.float32, parameters["input_shape"], min_value=-4, max_value=10) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_local_response_norm_tests(zip_path): """Make a set of tests to do local_response_norm.""" # Chose a set of parameters test_parameters = [{ "input_shape": [[1, 1, 1, 1], [1, 3, 4, 3], [3, 15, 14, 3]], "depth_radius": [None, 0, 1, 3, 4, 5], "bias": [None, 0.1, 0.3, -0.1], "alpha": [None, 1, 2, -3], "beta": [None, 0.5, 0.25, 2], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) out = tf.nn.local_response_normalization( input_tensor, depth_radius=parameters["depth_radius"], bias=parameters["bias"], alpha=parameters["alpha"], beta=parameters["beta"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data( np.float32, parameters["input_shape"], min_value=-4, max_value=10) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_pad_tests(zip_path): """Make a set of tests to do pad.""" # TODO(nupurgarg): Add test for tf.uint8. test_parameters = [ { "dtype": [tf.int32, tf.int64, tf.float32], "input_shape": [[1, 1, 2, 1], [2, 1, 1, 1]], "paddings": [[[0, 0], [0, 1], [2, 3], [0, 0]], [[0, 1], [0, 0], [0, 0], [2, 3]]], "constant_paddings": [True, False], }, # Non-4D use case. { "dtype": [tf.int32, tf.int64, tf.float32], "input_shape": [[1, 2], [0, 1, 2]], "paddings": [[[0, 1], [2, 3]]], "constant_paddings": [True, False], }, ] def build_graph(parameters): """Build a pad graph given `parameters`.""" input_tensor = tf.placeholder( dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) # Get paddings as either a placeholder or constants. if parameters["constant_paddings"]: paddings = parameters["paddings"] input_tensors = [input_tensor] else: shape = [len(parameters["paddings"]), 2] paddings = tf.placeholder(dtype=tf.int32, name="padding", shape=shape) input_tensors = [input_tensor, paddings] out = tf.pad(input_tensor, paddings=paddings) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["dtype"], parameters["input_shape"]) ] if not parameters["constant_paddings"]: values.append(np.array(parameters["paddings"])) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_reshape_tests(zip_path): """Make a set of tests to do reshape.""" # All shapes below are suitable for tensors with 420 elements. test_parameters = [{ "dtype": [tf.float32, tf.int32], "input_shape": [[3, 4, 5, 7], [4, 105], [21, 5, 2, 2], [420]], "output_shape": [[15, 28], [420], [1, -1, 5, 7], [-1]], }] def build_graph(parameters): input_tensor = tf.placeholder(dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.reshape(input_tensor, shape=parameters["output_shape"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_resize_bilinear_tests(zip_path): """Make a set of tests to do resize_bilinear.""" test_parameters = [{ "dtype": [tf.float32, tf.int32], "input_shape": [[1, 3, 4, 3], [1, 10, 2, 1]], "size": [[1, 1], [4, 3], [2, 2], [5, 6]], "align_corners": [None, True, False], }] def build_graph(parameters): input_tensor = tf.placeholder(dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.image.resize_bilinear(input_tensor, size=parameters["size"], align_corners=parameters["align_corners"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_sigmoid_tests(zip_path): """Make a set of tests to do sigmoid.""" test_parameters = [{ "dtype": [tf.float32], "input_shape": [[1, 3, 4, 3], [4], [], [1, 2, 3, 4, 5, 6]], }] def build_graph(parameters): input_tensor = tf.placeholder(dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.sigmoid(input_tensor) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_softmax_tests(zip_path): """Make a set of tests to do softmax.""" test_parameters = [{ "dtype": [tf.float32], "input_shape": [[1, 3, 4, 3], [2, 3]], "dim": [-1, 0], }, { "dtype": [tf.float32], "input_shape": [[4, 7]], "dim": [-1, 1], }] def build_graph(parameters): input_tensor = tf.placeholder(dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.nn.softmax(input_tensor, dim=parameters["dim"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_space_to_depth_tests(zip_path): """Make a set of tests to do space_to_depth.""" test_parameters = [{ "dtype": [tf.float32, tf.float16, tf.int32, tf.uint8, tf.int64], "input_shape": [[2, 12, 24, 1]], "block_size": [2, 3, 4], }] def build_graph(parameters): input_tensor = tf.placeholder(dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.space_to_depth(input_tensor, block_size=parameters["block_size"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_space_to_batch_nd_tests(zip_path): """Make a set of tests to do space_to_batch_nd.""" # TODO(nupurgarg): Add test for uint8. test_parameters = [ { "dtype": [tf.int32, tf.int64, tf.float32], "input_shape": [[1, 2, 2, 3], [2, 2, 4, 1]], "block_shape": [[1, 3], [2, 2]], "paddings": [[[0, 0], [0, 0]], [[0, 0], [2, 0]], [[1, 1], [1, 1]]], "constant_block_shape": [True, False], "constant_paddings": [True, False], }, { "dtype": [tf.float32], "input_shape": [[2, 3, 7, 3]], "block_shape": [[1, 3], [2, 2]], "paddings": [[[0, 0], [2, 0]], [[1, 0], [1, 0]]], "constant_block_shape": [True, False], "constant_paddings": [True, False], }, # Non-4D use case: 1 bath dimension, 3 spatial dimensions, 2 others. { "dtype": [tf.float32], "input_shape": [[1, 4, 4, 4, 1, 1]], "block_shape": [[2, 2, 2]], "paddings": [[[0, 0], [0, 0], [0, 0]]], "constant_block_shape": [True, False], "constant_paddings": [True, False], }, ] def build_graph(parameters): """Build a space_to_batch graph given `parameters`.""" input_tensor = tf.placeholder( dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) input_tensors = [input_tensor] # Get block_shape either as a const or as a placeholder (tensor). if parameters["constant_block_shape"]: block_shape = parameters["block_shape"] else: shape = [len(parameters["block_shape"])] block_shape = tf.placeholder(dtype=tf.int32, name="shape", shape=shape) input_tensors.append(block_shape) # Get paddings either as a const or as a placeholder (tensor). if parameters["constant_paddings"]: paddings = parameters["paddings"] else: shape = [len(parameters["paddings"]), 2] paddings = tf.placeholder(dtype=tf.int32, name="paddings", shape=shape) input_tensors.append(paddings) out = tf.space_to_batch_nd(input_tensor, block_shape, paddings) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["dtype"], parameters["input_shape"]) ] if not parameters["constant_block_shape"]: values.append(np.array(parameters["block_shape"])) if not parameters["constant_paddings"]: values.append(np.array(parameters["paddings"])) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_batch_to_space_nd_tests(zip_path): """Make a set of tests to do batch_to_space_nd.""" test_parameters = [ { "dtype": [tf.float32, tf.int64, tf.int32], "input_shape": [[12, 3, 3, 1]], "block_shape": [[1, 4], [2, 2], [3, 4]], "crops": [[[0, 0], [0, 0]], [[1, 1], [1, 1]]], "constant_block_shape": [True, False], "constant_crops": [True, False], }, # Non-4D use case: 1 bath dimension, 3 spatial dimensions, 2 others. { "dtype": [tf.float32], "input_shape": [[8, 2, 2, 2, 1, 1]], "block_shape": [[2, 2, 2]], "crops": [[[0, 0], [0, 0], [0, 0]]], "constant_block_shape": [True, False], "constant_crops": [True, False], }, ] def build_graph(parameters): """Build a batch_to_space graph given `parameters`.""" input_tensor = tf.placeholder( dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) input_tensors = [input_tensor] # Get block_shape either as a const or as a placeholder (tensor). if parameters["constant_block_shape"]: block_shape = parameters["block_shape"] else: shape = [len(parameters["block_shape"])] block_shape = tf.placeholder(dtype=tf.int32, name="shape", shape=shape) input_tensors.append(block_shape) # Get crops either as a const or as a placeholder (tensor). if parameters["constant_crops"]: crops = parameters["crops"] else: shape = [len(parameters["crops"]), 2] crops = tf.placeholder(dtype=tf.int32, name="crops", shape=shape) input_tensors.append(crops) out = tf.batch_to_space_nd(input_tensor, block_shape, crops) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["dtype"], parameters["input_shape"]) ] if not parameters["constant_block_shape"]: values.append(np.array(parameters["block_shape"])) if not parameters["constant_crops"]: values.append(np.array(parameters["crops"])) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_transpose_tests(zip_path): """Make a set of tests to do transpose.""" # TODO(nupurgarg): Add test for uint8. test_parameters = [{ "dtype": [tf.int32, tf.int64, tf.float32], "input_shape": [[2, 2, 3]], "perm": [[0, 1, 2], [0, 2, 1]], "constant_perm": [True, False], }, { "dtype": [tf.float32], "input_shape": [[1, 2, 3, 4]], "perm": [[0, 1, 2, 3], [3, 0, 1, 2]], "constant_perm": [True, False], }, { "dtype": [tf.float32], "input_shape": [[1, 2, 3, 4, 5]], "perm": [[4, 3, 2, 1, 0]], "constant_perm": [True, False], }] def build_graph(parameters): """Build a transpose graph given `parameters`.""" input_tensor = tf.placeholder( dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) if parameters["constant_perm"]: perm = parameters["perm"] input_tensors = [input_tensor] else: shape = [len(parameters["perm"]), 2] perm = tf.placeholder(dtype=tf.int32, name="perm", shape=shape) input_tensors = [input_tensor, perm] out = tf.transpose(input_tensor, perm=perm) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["dtype"], parameters["input_shape"]) ] if not parameters["constant_perm"]: values.append(np.array(parameters["perm"])) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_squeeze_tests(zip_path): """Make a set of tests to do squeeze.""" test_parameters = [{ "dtype": [tf.int32, tf.float32, tf.int64], "input_shape": [[1, 2, 1, 3, 1, 4, 1, 1]], "axis": [ None, [], [0, 2], [4, 7], [-1, 0, 2, 0, 7, -6], [1], [2, 3, 2], [-1, -2, -4, -6, -8], [0, 2, 4, 6, 7], [7, 6, 4, 2, 0], [6, 6], [0, 1, 2, 3, 4, 5, 6, 7], [-2, -3, 1, 0, 7, -5] ], }, { "dtype": [tf.int32, tf.float32, tf.int64], "input_shape": [[1]], "axis": [None, [], [0], [-1]], }, { "dtype": [tf.int32, tf.float32, tf.int64], "input_shape": [[1, 1, 1, 1, 1]], "axis": [None, [], [0], [3, 0], [-2, 0, 3, 2]], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.squeeze(input_tensor, axis=parameters["axis"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_strided_slice_tests(zip_path): """Make a set of tests to do strided_slice.""" # TODO(soroosh): add test/support for uint8. test_parameters = [ # 4-D { "dtype": [tf.float32, tf.int32, tf.int64], "index_type": [tf.int32], "input_shape": [[12, 2, 2, 5]], "begin": [[0, 0, 0, 0], [1, 0, 1, 0]], "end": [[8, 2, 2, 3], [12, 2, 2, 5]], "strides": [None, [2, 1, 3, 1]], "begin_mask": [None, 1, 8], "end_mask": [None, 1, 8], "shrink_axis_mask": [None, 1, 8, 11, 15, -1], "constant_indices": [False, True], }, # TODO(b/73170889) Restore test paramaters removed in cl/191608113. # 2-D { "dtype": [tf.float32, tf.int32, tf.int64], "index_type": [tf.int32], "input_shape": [[2, 3]], "begin": [[0, 0], [1, 0]], "end": [[2, 3], [2, 2]], "strides": [None, [2, 2]], "begin_mask": [None, 1, 2], "end_mask": [None, 1, 2], "shrink_axis_mask": [None, 1, 2, 3, -1], "constant_indices": [False, True], }, # Negative strides { "dtype": [tf.float32], "index_type": [tf.int32], "input_shape": [[2, 3]], "begin": [[0, -1]], "end": [[2, -3]], "strides": [[1, -1]], "begin_mask": [None, 1, 2], "end_mask": [None, 1, 2], "shrink_axis_mask": [None, 1, 2, 3, -1], "constant_indices": [False], }, ] def build_graph(parameters): """Build graph for stride_slice test.""" input_tensor = tf.placeholder( dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) if parameters["constant_indices"]: begin = parameters["begin"] end = parameters["end"] strides = parameters["strides"] tensors = [input_tensor] else: begin = tf.placeholder( dtype=parameters["index_type"], name="begin", shape=[len(parameters["input_shape"])]) end = tf.placeholder( dtype=parameters["index_type"], name="end", shape=[len(parameters["input_shape"])]) strides = ( tf.placeholder( dtype=parameters["index_type"], name="strides", shape=[len(parameters["input_shape"])]) if parameters["strides"] is not None else None) tensors = [input_tensor, begin, end] if strides is not None: tensors.append(strides) out = tf.strided_slice( input_tensor, begin, end, strides, begin_mask=parameters["begin_mask"], end_mask=parameters["end_mask"]) return tensors, [out] def build_inputs(parameters, sess, inputs, outputs): """Build inputs for stride_slice test.""" input_values = create_tensor_data(parameters["dtype"], parameters["input_shape"]) index_type = _TF_TYPE_INFO[parameters["index_type"]][0] values = [input_values] if not parameters["constant_indices"]: begin_values = np.array(parameters["begin"]).astype(index_type) end_values = np.array(parameters["end"]).astype(index_type) stride_values = ( np.array(parameters["strides"]).astype(index_type) if parameters["strides"] is not None else None) values.append(begin_values) values.append(end_values) if stride_values is not None: values.append(stride_values) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_lstm_tests(zip_path): """Make a set of tests to do basic Lstm cell.""" test_parameters = [ { "dtype": [tf.float32], "num_batchs": [1], "time_step_size": [1], "input_vec_size": [3], "num_cells": [4], }, ] def build_graph(parameters): """Build a simple graph with BasicLSTMCell.""" num_batchs = parameters["num_batchs"] time_step_size = parameters["time_step_size"] input_vec_size = parameters["input_vec_size"] num_cells = parameters["num_cells"] inputs_after_split = [] for i in xrange(time_step_size): one_timestamp_input = tf.placeholder( dtype=parameters["dtype"], name="split_{}".format(i), shape=[num_batchs, input_vec_size]) inputs_after_split.append(one_timestamp_input) # Currently lstm identifier has a few limitations: only supports # forget_bias == 0, inner state activiation == tanh. # TODO(zhixianyan): Add another test with forget_bias == 1. # TODO(zhixianyan): Add another test with relu as activation. lstm_cell = tf.contrib.rnn.BasicLSTMCell( num_cells, forget_bias=0.0, state_is_tuple=True) cell_outputs, _ = rnn.static_rnn( lstm_cell, inputs_after_split, dtype=tf.float32) out = cell_outputs[-1] return inputs_after_split, [out] def build_inputs(parameters, sess, inputs, outputs): """Feed inputs, assign vairables, and freeze graph.""" with tf.variable_scope("", reuse=True): kernel = tf.get_variable("rnn/basic_lstm_cell/kernel") bias = tf.get_variable("rnn/basic_lstm_cell/bias") kernel_values = create_tensor_data( parameters["dtype"], [kernel.shape[0], kernel.shape[1]], -1, 1) bias_values = create_tensor_data(parameters["dtype"], [bias.shape[0]], 0, 1) sess.run(tf.group(kernel.assign(kernel_values), bias.assign(bias_values))) num_batchs = parameters["num_batchs"] time_step_size = parameters["time_step_size"] input_vec_size = parameters["input_vec_size"] input_values = [] for _ in xrange(time_step_size): tensor_data = create_tensor_data(parameters["dtype"], [num_batchs, input_vec_size], 0, 1) input_values.append(tensor_data) out = sess.run(outputs, feed_dict=dict(zip(inputs, input_values))) return input_values, out # TODO(zhixianyan): Automatically generate rnn_states for lstm cell. extra_toco_options = ExtraTocoOptions() extra_toco_options.rnn_states = ( "{state_array:rnn/BasicLSTMCellZeroState/zeros," "back_edge_source_array:rnn/basic_lstm_cell/Add_1,size:4}," "{state_array:rnn/BasicLSTMCellZeroState/zeros_1," "back_edge_source_array:rnn/basic_lstm_cell/Mul_2,size:4}") make_zip_of_tests( zip_path, test_parameters, build_graph, build_inputs, extra_toco_options, use_frozen_graph=True) def make_l2_pool(input_tensor, ksize, strides, padding, data_format): """Given an input perform a sequence of TensorFlow ops to produce l2pool.""" return tf.sqrt(tf.nn.avg_pool( tf.square(input_tensor), ksize=ksize, strides=strides, padding=padding, data_format=data_format)) def make_topk_tests(zip_path): """Make a set of tests to do topk.""" test_parameters = [{ "input_dtype": [tf.float32, tf.int32], "input_shape": [[10], [5, 20]], }] def build_graph(parameters): """Build the topk op testing graph.""" input_value = tf.placeholder( dtype=parameters["input_dtype"], name="input", shape=parameters["input_shape"]) k = tf.constant(3, name="k") out = tf.nn.top_k(input_value, k) return [input_value], [out[1]] def build_inputs(parameters, sess, inputs, outputs): input_value = create_tensor_data(parameters["input_dtype"], parameters["input_shape"]) return [input_value], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_arg_max_tests(zip_path): """Make a set of tests to do arg_max.""" test_parameters = [{ "input_dtype": [tf.float32, tf.int32], "input_shape": [[1, 1, 1, 3], [2, 3, 4, 5], [2, 3, 3], [5, 5], [10]], "axis": [0, 1, 2, 3], "output_type": [tf.int32, tf.int64], }] def build_graph(parameters): """Build the topk op testing graph.""" input_value = tf.placeholder( dtype=parameters["input_dtype"], name="input", shape=parameters["input_shape"]) axis = tf.constant(parameters["axis"], name="axis") out = tf.arg_max(input_value, axis, output_type=parameters["output_type"]) return [input_value], [out] def build_inputs(parameters, sess, inputs, outputs): input_value = create_tensor_data(parameters["input_dtype"], parameters["input_shape"]) return [input_value], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_less_tests(zip_path): """Make a set of tests to do less.""" test_parameters = [{ "input_dtype": [tf.float32, tf.int32, tf.int64], "input_shape_pair": [([1, 1, 1, 3], [1, 1, 1, 3]), ([2, 3, 4, 5], [2, 3, 4, 5]), ([2, 3, 3], [2, 3]), ([5, 5], [1]), ([10], [2, 4, 10])], }] def build_graph(parameters): """Build the less op testing graph.""" input_value1 = tf.placeholder( dtype=parameters["input_dtype"], name="input1", shape=parameters["input_shape_pair"][0]) input_value2 = tf.placeholder( dtype=parameters["input_dtype"], name="input2", shape=parameters["input_shape_pair"][1]) out = tf.less(input_value1, input_value2) return [input_value1, input_value2], [out] def build_inputs(parameters, sess, inputs, outputs): input_value1 = create_tensor_data(parameters["input_dtype"], parameters["input_shape_pair"][0]) input_value2 = create_tensor_data(parameters["input_dtype"], parameters["input_shape_pair"][1]) return [input_value1, input_value2], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value1, input_value2]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) # Toco binary path provided by the generate rule. bin_path = None def main(unused_args): global bin_path def mkdir_if_not_exist(x): if not os.path.isdir(x): os.mkdir(x) if not os.path.isdir(x): raise RuntimeError("Failed to create dir %r" % x) opstest_path = os.path.join(FLAGS.output_path) mkdir_if_not_exist(opstest_path) out = FLAGS.zip_to_output bin_path = FLAGS.toco test_function = ("make_%s_tests" % out.replace(".zip", "")) if test_function not in globals(): raise RuntimeError("Can't find a test function to create %r. Tried %r" % (out, test_function)) # TODO(ahentz): accessing globals() is not very elegant. We should either # break this file into multiple tests or use decorator-based registration to # avoid using globals(). globals()[test_function](os.path.join(opstest_path, out)) if __name__ == "__main__": FLAGS, unparsed = parser.parse_known_args() if unparsed: print("Usage: %s <path out> <zip file to generate>") else: tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
35.904322
82
0.625063
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import itertools import os import re import sys import tempfile import traceback import zipfile import numpy as np from six import StringIO from six.moves import xrange os.environ["CUDA_VISIBLE_DEVICES"] = "-1" import tensorflow as tf from google.protobuf import text_format from tensorflow.contrib.lite.testing import generate_examples_report as report_lib from tensorflow.python.framework import graph_util as tf_graph_util from tensorflow.python.ops import rnn parser = argparse.ArgumentParser(description="Script to generate TFLite tests.") parser.add_argument("output_path", help="Directory where the outputs will be go.") parser.add_argument("--zip_to_output", type=str, help="Particular zip to output.", required=False) parser.add_argument("--toco", type=str, help="Path to toco tool.", required=True) parser.add_argument( "--known_bugs_are_errors", action="store_true", help=("If a particular model is affected by a known bug," " count it as a toco error.")) parser.add_argument( "--ignore_toco_errors", action="store_true", help="Raise an exception if any toco error is encountered.") parser.add_argument( "--save_graphdefs", action="store_true", help="Include intermediate graphdefs in the output zip files.") RANDOM_SEED = 342 TEST_INPUT_DEPTH = 3 # A map from regular expression to bug number. Any test failure with label # matching the expression will be considered due to the corresponding bug. KNOWN_BUGS = { # TOCO doesn't support scalars as input. r"relu.*input_shape=\[\]": "67587484", r"sigmoid.*input_shape=\[\]": "67645668", r"concat.*num_tensors=1": "67378344", # Transposition in MatMul is not supported. r"fully_connected.*transpose_.=True": "67586970", # Softmax graphs are too complex. r"softmax.*dim=0": "67749831", r"softmax.*input_shape=\[1,3,4,3\]": "67749831", # SpaceToDepth only supports float32. r"space_to_depth.*(float16|int32|uint8|int64)": "68018134", # BatchToSpaceND only supports 4D tensors. r"batch_to_space_nd.*input_shape=\[8,2,2,2,1,1\]": "70594733", # Div will use floordiv. r"div.*int32": "72051395", # TOCO require matching dimensions in strided_slice. r"strided_slice.*begin=\[0\].*end=\[1\].*": "73170889", # No support for SplitV r"split.*num_or_size_splits=\[2,2\]": "73377559", # Needs support for dimensions other than the last one in argmax. r"arg_max.*axis=0.*": "77546240", r"arg_max.*axis=1.*": "77546240", r"arg_max.*axis=2.*": "77546240", } class ExtraTocoOptions(object): def __init__(self): # Whether to ignore control dependency nodes. self.drop_control_dependency = False # Allow custom ops in the toco conversion. self.allow_custom_ops = False # Rnn states that are used to support rnn / lstm cells. self.rnn_states = None def toco_options(data_types, input_arrays, output_arrays, shapes, extra_toco_options=ExtraTocoOptions()): shape_str = ":".join([",".join(str(y) for y in x) for x in shapes]) inference_type = "FLOAT" # TODO(ahentz): if we get multi-input quantization to work we need this # to change if data_types[0] == "QUANTIZED_UINT8": inference_type = "QUANTIZED_UINT8" s = (" --input_data_types=%s" % ",".join(data_types) + " --inference_type=%s" % inference_type + " --input_format=TENSORFLOW_GRAPHDEF" + " --output_format=TFLITE" + " --input_arrays=%s" % ",".join(input_arrays) + " --input_shapes=%s" % shape_str + " --output_arrays=%s" % ",".join(output_arrays)) if extra_toco_options.drop_control_dependency: s += " --drop_control_dependency" if extra_toco_options.allow_custom_ops: s += " --allow_custom_ops" if extra_toco_options.rnn_states: s += (" --rnn_states='" + extra_toco_options.rnn_states + "'") return s def write_examples(fp, examples): def write_tensor(fp, x): fp.write("dtype,%s\n" % x.dtype) fp.write("shape," + ",".join(map(str, x.shape)) + "\n") # Output 9 digits after the point to ensure the precision is good enough. values = ["{:.9f}".format(value) for value in list(x.flatten())] fp.write("values," + ",".join(values) + "\n") fp.write("test_cases,%d\n" % len(examples)) for example in examples: fp.write("inputs,%d\n" % len(example["inputs"])) for i in example["inputs"]: write_tensor(fp, i) fp.write("outputs,%d\n" % len(example["outputs"])) for i in example["outputs"]: write_tensor(fp, i) def write_test_cases(fp, model_name, examples): fp.write("load_model: %s\n" % os.path.basename(model_name)) for example in examples: fp.write("reshape {\n") for t in example["inputs"]: fp.write(" input: \"" + ",".join(map(str, t.shape)) + "\"\n") fp.write("}\n") fp.write("invoke {\n") for t in example["inputs"]: values = ["{:.9f}".format(value) for value in list(t.flatten())] fp.write(" input: \"" + ",".join(values) + "\"\n") for t in example["outputs"]: values = ["{:.9f}".format(value) for value in list(t.flatten())] fp.write(" output: \"" + ",".join(values) + "\"\n") fp.write("}\n") _TF_TYPE_INFO = { tf.float32: (np.float32, "FLOAT"), tf.float16: (np.float16, "FLOAT"), tf.int32: (np.int32, "INT32"), tf.uint8: (np.uint8, "QUANTIZED_UINT8"), tf.int64: (np.int64, "INT64"), } def create_tensor_data(dtype, shape, min_value=-100, max_value=100): if dtype in _TF_TYPE_INFO: dtype = _TF_TYPE_INFO[dtype][0] if dtype in (tf.float32, tf.float16): value = (max_value-min_value)*np.random.random_sample(shape)+min_value elif dtype in (tf.int32, tf.uint8, tf.int64): value = np.random.randint(min_value, max_value+1, shape) return value.astype(dtype) def freeze_graph(session, outputs): return tf_graph_util.convert_variables_to_constants( session, session.graph.as_graph_def(), [x.op.name for x in outputs]) def make_control_dep_tests(zip_path): test_parameters = [{ "input_shape": [[], [1, 1, 1, 1], [1, 15, 14, 1], [3, 15, 14, 3]], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) filter_value = tf.zeros((3, 3, TEST_INPUT_DEPTH, 8), tf.float32) assert_op = tf.assert_greater_equal(input_tensor, input_tensor - 1) with tf.control_dependencies([assert_op]): out = tf.nn.conv2d(input_tensor, filter_value, strides=(1, 1, 1, 1), padding="SAME") return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(tf.float32, parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) extra_toco_options = ExtraTocoOptions() extra_toco_options.drop_control_dependency = True make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs, extra_toco_options) def toco_convert(graph_def_str, input_tensors, output_tensors, extra_toco_options): data_types = [_TF_TYPE_INFO[x[2]][1] for x in input_tensors] opts = toco_options( data_types=data_types, input_arrays=[x[0] for x in input_tensors], shapes=[x[1] for x in input_tensors], output_arrays=output_tensors, extra_toco_options=extra_toco_options) with tempfile.NamedTemporaryFile() as graphdef_file, \ tempfile.NamedTemporaryFile() as output_file, \ tempfile.NamedTemporaryFile("w+") as stdout_file: graphdef_file.write(graph_def_str) graphdef_file.flush() # TODO(aselle): Switch this to subprocess at some point. cmd = ("%s --input_file=%s --output_file=%s %s > %s 2>&1" % (bin_path, graphdef_file.name, output_file.name, opts, stdout_file.name)) exit_code = os.system(cmd) log = ( cmd + "exited with code %d" % exit_code + "\n------------------\n" + stdout_file.read()) return (None if exit_code != 0 else output_file.read()), log def normalize_output_name(output_name): return output_name.split(":")[0] if output_name.endswith( ":0") else output_name def make_zip_of_tests(zip_path, test_parameters, make_graph, make_test_inputs, extra_toco_options=ExtraTocoOptions(), use_frozen_graph=False): # TODO(aselle): Make this allow multiple inputs outputs. archive = zipfile.PyZipFile(zip_path, "w") zip_manifest = [] convert_report = [] toco_errors = 0 for parameters in test_parameters: keys = parameters.keys() for curr in itertools.product(*parameters.values()): label = zip_path.replace(".zip", "") + (",".join( "%s=%r" % z for z in sorted(zip(keys, curr))).replace(" ", "")) if label[0] == "/": label = label[1:] param_dict = dict(zip(keys, curr)) def build_example(label, param_dict_real): np.random.seed(RANDOM_SEED) report = {"toco": report_lib.NOTRUN, "tf": report_lib.FAILED} # Build graph report["tf_log"] = "" report["toco_log"] = "" tf.reset_default_graph() with tf.device("/cpu:0"): try: inputs, outputs = make_graph(param_dict_real) except (tf.errors.UnimplementedError, tf.errors.InvalidArgumentError, ValueError): report["tf_log"] += traceback.format_exc() return None, report sess = tf.Session() try: baseline_inputs, baseline_outputs = (make_test_inputs( param_dict_real, sess, inputs, outputs)) except (tf.errors.UnimplementedError, tf.errors.InvalidArgumentError, ValueError): report["tf_log"] += traceback.format_exc() return None, report report["toco"] = report_lib.FAILED report["tf"] = report_lib.SUCCESS # Convert graph to toco input_tensors = [(input_tensor.name.split(":")[0], input_tensor.get_shape(), input_tensor.dtype) for input_tensor in inputs] output_tensors = [normalize_output_name(out.name) for out in outputs] graph_def = freeze_graph( sess, tf.global_variables() + inputs + outputs) if use_frozen_graph else sess.graph_def tflite_model_binary, toco_log = toco_convert( graph_def.SerializeToString(), input_tensors, output_tensors, extra_toco_options) report["toco"] = (report_lib.SUCCESS if tflite_model_binary is not None else report_lib.FAILED) report["toco_log"] = toco_log if FLAGS.save_graphdefs: archive.writestr(label + ".pb", text_format.MessageToString(graph_def), zipfile.ZIP_DEFLATED) if tflite_model_binary: archive.writestr(label + ".bin", tflite_model_binary, zipfile.ZIP_DEFLATED) example = {"inputs": baseline_inputs, "outputs": baseline_outputs} example_fp = StringIO() write_examples(example_fp, [example]) archive.writestr(label + ".inputs", example_fp.getvalue(), zipfile.ZIP_DEFLATED) example_fp2 = StringIO() write_test_cases(example_fp2, label + ".bin", [example]) archive.writestr(label + "_tests.txt", example_fp2.getvalue(), zipfile.ZIP_DEFLATED) zip_manifest.append(label + "\n") return tflite_model_binary, report _, report = build_example(label, param_dict) if report["toco"] == report_lib.FAILED: ignore_error = False if not FLAGS.known_bugs_are_errors: for pattern, bug_number in KNOWN_BUGS.items(): if re.search(pattern, label): print("Ignored TOCO error due to bug %s" % bug_number) ignore_error = True if not ignore_error: toco_errors += 1 print("-----------------\ntoco error!\n%s\n-----------------\n" % report["toco_log"]) convert_report.append((param_dict, report)) report_io = StringIO() report_lib.make_report_table(report_io, zip_path, convert_report) archive.writestr("report.html", report_io.getvalue()) archive.writestr("manifest.txt", "".join(zip_manifest), zipfile.ZIP_DEFLATED) # Log statistics of what succeeded total_conversions = len(convert_report) tf_success = sum(1 for x in convert_report if x[1]["tf"] == report_lib.SUCCESS) toco_success = sum(1 for x in convert_report if x[1]["toco"] == report_lib.SUCCESS) percent = 0 if tf_success > 0: percent = float(toco_success) / float(tf_success) * 100. tf.logging.info(("Archive %s Considered %d graphs, %d TF evaluated graphs " " and %d TOCO converted graphs (%.1f%%"), zip_path, total_conversions, tf_success, toco_success, percent) if not FLAGS.ignore_toco_errors and toco_errors > 0: raise RuntimeError( "Found %d errors while generating toco models" % toco_errors) def make_pool_tests(pool_op_in): pool_op = pool_op_in def f(zip_path): # Chose a set of parameters test_parameters = [{ "ksize": [[2, 1, 1, 2], [1, 1, 1, 1], [1, 1, 2, 1], [1, 10, 11, 1]], "strides": [[2, 1, 1, 2], [1, 1, 1, 1], [1, 1, 2, 1], [1, 10, 11, 1]], # TODO(aselle): should add in a degenerate shape (e.g. [1, 0, 1, 1]). "input_shape": [[], [1, 1, 1, 1], [1, 15, 14, 1], [3, 15, 14, 3]], "padding": ["SAME", "VALID"], "data_format": ["NHWC"], # TODO(aselle): NCHW would be good }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) out = pool_op( input_tensor, ksize=parameters["ksize"], strides=parameters["strides"], data_format=parameters["data_format"], padding=parameters["padding"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(tf.float32, parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) return f def make_l2_pool_tests(zip_path): make_pool_tests(make_l2_pool)(zip_path) def make_avg_pool_tests(zip_path): make_pool_tests(tf.nn.avg_pool)(zip_path) def make_max_pool_tests(zip_path): make_pool_tests(tf.nn.max_pool)(zip_path) def make_relu_tests(zip_path): # Chose a set of parameters test_parameters = [{ "input_shape": [[], [1], [2, 3], [1, 1, 1, 1], [1, 3, 4, 3], [3, 15, 14, 3], [3, 1, 2, 4, 6], [2, 2, 3, 4, 5, 6]], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) out = tf.nn.relu(input_tensor) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data( np.float32, parameters["input_shape"], min_value=-4, max_value=10) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_relu1_tests(zip_path): # Chose a set of parameters test_parameters = [{ "input_shape": [[], [1, 1, 1, 1], [1, 3, 4, 3], [3, 15, 14, 3], [3, 1, 2, 4, 6], [2, 2, 3, 4, 5, 6]], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) # Note that the following is not supported: # out = tf.maximum(-1.0, tf.minimum(input_tensor, 1.0)) out = tf.minimum(1.0, tf.maximum(input_tensor, -1.0)) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data( np.float32, parameters["input_shape"], min_value=-3, max_value=10) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_relu6_tests(zip_path): # Chose a set of parameters test_parameters = [{ "input_shape": [[], [1, 1, 1, 1], [1, 3, 4, 3], [3, 15, 14, 3], [3, 1, 2, 4, 6], [2, 2, 3, 4, 5, 6]], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) out = tf.nn.relu(input_tensor) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data( np.float32, parameters["input_shape"], min_value=-3, max_value=10) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) # This function tests various TensorFLow functions that generates Const op, # including `tf.ones`, `tf.zeros` and random functions. def make_constant_tests(zip_path): test_parameters = [{ "dtype": [tf.float32, tf.int32], "input_shape": [[1], [2], [1, 1, 1, 1], [2, 2, 2, 2]], }] def build_graph(parameters): # Since Toco & Tflite can't have a single constant op in the entire graph, input1 = tf.placeholder(dtype=parameters["dtype"], name="input1", shape=parameters["input_shape"]) out = tf.ones(parameters["input_shape"], dtype=parameters["dtype"]) + input1 return [input1], [out] def build_inputs(parameters, sess, inputs, outputs): input1 = np.zeros(parameters["input_shape"], dtype=_TF_TYPE_INFO[parameters["dtype"]][0]) return [input1], sess.run(outputs, feed_dict={inputs[0]: input1}) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_binary_op_tests(zip_path, binary_operator): test_parameters = [{ "dtype": [tf.float32, tf.int32], "input_shape_1": [[1, 3, 4, 3]], "input_shape_2": [[1, 3, 4, 3]], "activation": [True] }, { "dtype": [tf.float32], "input_shape_1": [[5]], "input_shape_2": [[5]], "activation": [False, True] }, { "dtype": [tf.float32], "input_shape_1": [[1, 3, 4, 3]], "input_shape_2": [[3]], "activation": [True] }] def build_graph(parameters): input1 = tf.placeholder( dtype=parameters["dtype"], name="input1", shape=parameters["input_shape_1"]) input2 = tf.placeholder( dtype=parameters["dtype"], name="input2", shape=parameters["input_shape_2"]) out = binary_operator(input1, input2) if parameters["activation"]: out = tf.nn.relu(out) return [input1, input2], [out] def build_inputs(parameters, sess, inputs, outputs): input1 = create_tensor_data(parameters["dtype"], parameters["input_shape_1"]) input2 = create_tensor_data(parameters["dtype"], parameters["input_shape_2"]) return [input1, input2], sess.run( outputs, feed_dict={ inputs[0]: input1, inputs[1]: input2 }) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_mean_tests(zip_path): test_parameters = [{ "input_dtype": [tf.float32, tf.int32, tf.int64], "input_shape": [[3, 2, 4]], "axis": [ None, 0, 1, 2, [0, 1], [0, 2], [1, 2], [0, 1, 2], [1, 0], [2, 0], [2, 1], [2, 1, 0], [2, 0, 1], -1, -2, -3, [1, -1], [0, -1], [-1, 0], [-1, -2, -3], [0, 0, 0], [2, 2, 0], [1, 0, -3, -3] ], "const_axis": [True, False], "keepdims": [True, False], }, { "input_dtype": [tf.float32, tf.int32, tf.int64], "input_shape": [[1, 224, 224, 3]], "axis": [ None, 0, 1, 2, 3, [1, 2], [0, 3], [1, 2, 3], [0, 1, 2, 3], [3, 2, 1, 0], [3, 1, 0, 2], [2, 0], [3, 0], [3, 1], [1, 0], -1, -2, -3, -4, [0, -2], [2, 3, -1, 0], [3, 1, 2, -3], [3, -4], [2, 2, 2], [2, 2, 3], [-3, -3, -4], [-3, 2, 1] ], "const_axis": [True, False], "keepdims": [True, False], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=parameters["input_dtype"], name="input", shape=parameters["input_shape"]) # Get axis as either a placeholder or constants. if parameters["const_axis"]: axis = parameters["axis"] input_tensors = [input_tensor] else: if isinstance(parameters["axis"], list): shape = [len(parameters["axis"])] else: shape = [0] # shape for None or integers. axis = tf.placeholder(dtype=tf.int32, name="axis", shape=shape) input_tensors = [input_tensor, axis] out = tf.reduce_mean( input_tensor, axis=axis, keepdims=parameters["keepdims"]) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["input_dtype"], parameters["input_shape"]) ] if not parameters["const_axis"]: if parameters["axis"]: values.append(np.array(parameters["axis"])) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_exp_tests(zip_path): test_parameters = [{ "input_dtype": [tf.float32], "input_shape": [[3], [1, 100], [4, 2, 3], [5, 224, 224, 3]], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=parameters["input_dtype"], name="input", shape=parameters["input_shape"]) out = tf.exp(input_tensor) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["input_dtype"], parameters["input_shape"], min_value=-100, max_value=9) ] return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_log_softmax_tests(zip_path): test_parameters = [{ "input_dtype": [tf.float32], "input_shape": [[1, 100], [4, 2], [5, 224]], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=parameters["input_dtype"], name="input", shape=parameters["input_shape"]) out = tf.nn.log_softmax(input_tensor) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data( parameters["input_dtype"], parameters["input_shape"], min_value=-100, max_value=9) ] return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_maximum_tests(zip_path): test_parameters = [{ "input_dtype": [tf.float32], "input_shape_1": [[3], [1, 100], [4, 2, 3], [5, 224, 224, 3]], "input_shape_2": [[3], [1, 100], [4, 2, 3], [5, 224, 224, 3]], }] def build_graph(parameters): input_tensor_1 = tf.placeholder( dtype=parameters["input_dtype"], name="input_1", shape=parameters["input_shape_1"]) input_tensor_2 = tf.placeholder( dtype=parameters["input_dtype"], name="input_2", shape=parameters["input_shape_2"]) out = tf.maximum(input_tensor_1, input_tensor_2) return [input_tensor_1, input_tensor_2], [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["input_dtype"], parameters["input_shape_1"]), create_tensor_data(parameters["input_dtype"], parameters["input_shape_2"]) ] return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_minimum_tests(zip_path): test_parameters = [{ "input_dtype": [tf.float32], "input_shape_1": [[3], [1, 100], [4, 2, 3], [5, 224, 224, 3]], "input_shape_2": [[3], [1, 100], [4, 2, 3], [5, 224, 224, 3]], }] def build_graph(parameters): input_tensor_1 = tf.placeholder( dtype=parameters["input_dtype"], name="input_1", shape=parameters["input_shape_1"]) input_tensor_2 = tf.placeholder( dtype=parameters["input_dtype"], name="input_2", shape=parameters["input_shape_2"]) out = tf.minimum(input_tensor_1, input_tensor_2) return [input_tensor_1, input_tensor_2], [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["input_dtype"], parameters["input_shape_1"]), create_tensor_data(parameters["input_dtype"], parameters["input_shape_2"]) ] return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_binary_op_tests_func(binary_operator): return lambda zip_path: make_binary_op_tests(zip_path, binary_operator) def make_add_tests(zip_path): make_binary_op_tests(zip_path, tf.add) def make_div_tests(zip_path): make_binary_op_tests(zip_path, tf.div) def make_sub_tests(zip_path): make_binary_op_tests(zip_path, tf.subtract) def make_mul_tests(zip_path): make_binary_op_tests(zip_path, tf.multiply) def make_gather_tests(zip_path): test_parameters = [{ # TODO(mgubin): add string tests when they are supported by Toco. # TODO(mgubin): add tests for Nd indices when they are supported by # TfLite. "params_dtype": [tf.float32, tf.int32], "params_shape": [[10], [1, 2, 20]], "indices_dtype": [tf.int32], "indices_shape": [[3], [5]], "axis": [0, 1], }] def build_graph(parameters): params = tf.placeholder( dtype=parameters["params_dtype"], name="params", shape=parameters["params_shape"]) indices = tf.placeholder( dtype=parameters["indices_dtype"], name="indices", shape=parameters["indices_shape"]) out = tf.gather(params, indices, axis=parameters["axis"]) return [params, indices], [out] def build_inputs(parameters, sess, inputs, outputs): params = create_tensor_data(parameters["params_dtype"], parameters["params_shape"]) indices = create_tensor_data(parameters["indices_dtype"], parameters["indices_shape"], 0, parameters["params_shape"][0] - 1) return [params, indices], sess.run( outputs, feed_dict=dict(zip(inputs, [params, indices]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_global_batch_norm_tests(zip_path): test_parameters = [{ "dtype": [tf.float32], "input_shape": [[1, 1, 6, 2], [3, 4, 5, 4]], "epsilon": [0.1, 0.0001], "scale_after": [True, False], }] def build_graph(parameters): input_shape = parameters["input_shape"] scale_shape = input_shape[3] scale = create_tensor_data(parameters["dtype"], scale_shape) offset = create_tensor_data(parameters["dtype"], scale_shape) mean = create_tensor_data(parameters["dtype"], scale_shape) variance = create_tensor_data(parameters["dtype"], scale_shape) x = create_tensor_data(parameters["dtype"], parameters["input_shape"]) x_norm = tf.nn.batch_norm_with_global_normalization( x, mean, variance, scale, offset, parameters["epsilon"], parameters["scale_after"]) input_tensor = tf.placeholder(dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.add(input_tensor, x_norm) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_value = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_value], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_fused_batch_norm_tests(zip_path): test_parameters = [{ "dtype": [tf.float32], "input_shape": [[1, 1, 6, 2]], "epsilon": [0.001, 0.1], }] def build_graph(parameters): input_shape = parameters["input_shape"] scale_shape = input_shape[3] scale = create_tensor_data(parameters["dtype"], scale_shape) offset = create_tensor_data(parameters["dtype"], scale_shape) mean = create_tensor_data(parameters["dtype"], scale_shape) variance = create_tensor_data(parameters["dtype"], scale_shape) x = create_tensor_data(parameters["dtype"], parameters["input_shape"]) [x_norm, _, _] = tf.nn.fused_batch_norm( x, scale, offset, mean, variance, parameters["epsilon"], data_format="NHWC", is_training=False) input_tensor = tf.placeholder(dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.add(input_tensor, x_norm) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_value = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_value], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_conv_tests(zip_path): test_parameters = [ { "input_shape": [[1, 3, 4, 3]], "filter_shape": [[1, 1, 3, 2]], "strides": [[1, 1, 1, 1], [1, 2, 3, 1]], "dilations": [[1, 1, 1, 1], [1, 3, 2, 1], [1, 2, 2, 1]], "padding": ["SAME", "VALID"], "data_format": ["NHWC"], # TODO(aselle): NCHW would be good "constant_filter": [True, False], }, { "input_shape": [[2, 14, 14, 2]], "filter_shape": [[6, 6, 2, 2]], "strides": [[1, 1, 1, 1], [1, 2, 3, 1]], "dilations": [[1, 1, 1, 1], [1, 2, 2, 1]], "padding": ["SAME", "VALID"], "data_format": ["NHWC"], # TODO(aselle): NCHW would be good "constant_filter": [True, False], } ] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) # Get filter input either as a placeholder or constants. Also get a list of # the input tensors that are represented as placeholders. if parameters["constant_filter"]: filter_input = create_tensor_data(np.float32, parameters["filter_shape"]) input_tensors = [input_tensor] else: filter_input = tf.placeholder( dtype=tf.float32, name="filter", shape=parameters["filter_shape"]) input_tensors = [input_tensor, filter_input] out = tf.nn.conv2d( input_tensor, filter_input, strides=parameters["strides"], dilations=parameters["dilations"], padding=parameters["padding"], data_format=parameters["data_format"]) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): # Build list of input values either containing 1 tensor (input) or 2 tensors # (input, filter) based on whether filter is constant or variable input. values = [create_tensor_data(np.float32, parameters["input_shape"])] if not parameters["constant_filter"]: values.append(create_tensor_data(np.float32, parameters["filter_shape"])) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_depthwiseconv_tests(zip_path): # Tensorflow only supports equal strides test_parameters = [ { "input_shape": [[1, 3, 4, 3], [1, 10, 10, 3]], "filter_size": [[1, 1], [1, 2], [3, 3]], "strides": [[1, 1, 1, 1], [1, 3, 3, 1]], "channel_multiplier": [1, 2], "rate": [[1, 1]], "padding": ["SAME", "VALID"], "data_format": ["NHWC"], "constant_filter": [True, False], }, { "input_shape": [[1, 3, 4, 3]], "filter_size": [[1, 1]], "strides": [[1, 1, 2, 1]], # TF needs [1, x, x, 1] "channel_multiplier": [2], "rate": [[2, 2]], # Only [1, 1] is supported "padding": ["SAME"], "data_format": ["NHWC"], "constant_filter": [True, False], } ] def get_tensor_shapes(parameters): input_shape = parameters["input_shape"] filter_size = parameters["filter_size"] filter_shape = filter_size + [ input_shape[3], parameters["channel_multiplier"] ] return [input_shape, filter_shape] def build_graph(parameters): input_shape, filter_shape = get_tensor_shapes(parameters) input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=input_shape) # Get filter input either as a placeholder or constants. Also get a list of # the input tensors that are represented as placeholders. if parameters["constant_filter"]: filter_input = create_tensor_data(np.float32, filter_shape) input_tensors = [input_tensor] else: filter_input = tf.placeholder( dtype=tf.float32, name="filter", shape=filter_shape) input_tensors = [input_tensor, filter_input] out = tf.nn.depthwise_conv2d( input_tensor, filter_input, strides=parameters["strides"], rate=parameters["rate"], padding=parameters["padding"], data_format=parameters["data_format"]) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): # Build list of input values either containing 1 tensor (input) or 2 tensors # (input, filter) based on whether filter is constant or variable input. input_shape, filter_shape = get_tensor_shapes(parameters) values = [create_tensor_data(np.float32, input_shape)] if not parameters["constant_filter"]: values.append(create_tensor_data(np.float32, filter_shape)) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_split_tests(zip_path): test_parameters = [{ "input_shape": [[1, 3, 4, 6], [2, 4, 1], [6, 4], [8]], "num_or_size_splits": [1, 2, 3, 4, 5, [2, 2]], "axis": [0, 1, 2, 3, -4, -3, -2, -1], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) out = tf.split( input_tensor, parameters["num_or_size_splits"], parameters["axis"]) return [input_tensor], out def build_inputs(parameters, sess, inputs, outputs): values = [create_tensor_data(np.float32, parameters["input_shape"])] return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_concat_tests(zip_path): test_parameters = [{ "base_shape": [[1, 3, 4, 3], [3, 4]], "num_tensors": [1, 2, 3, 4, 5, 6], "axis": [0, 1, 2, 3, -3, -2, -1], }] def get_shape(parameters, delta): axis = parameters["axis"] shape = parameters["base_shape"][:] if axis < 0: axis += len(shape) if axis < len(shape): shape[axis] += delta return shape def build_graph(parameters): all_tensors = [] for n in range(0, parameters["num_tensors"]): input_tensor = tf.placeholder(dtype=tf.float32, name=("input%d" % n), shape=get_shape(parameters, n)) all_tensors.append(input_tensor) out = tf.concat(all_tensors, parameters["axis"]) return all_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): all_values = [] for n in range(0, parameters["num_tensors"]): input_values = create_tensor_data(np.float32, get_shape(parameters, n)) all_values.append(input_values) return all_values, sess.run( outputs, feed_dict=dict(zip(inputs, all_values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_fully_connected_tests(zip_path): test_parameters = [{ "shape1": [[3, 3]], "shape2": [[3, 3]], "transpose_a": [True, False], "transpose_b": [True, False], "constant_filter": [True, False], }, { "shape1": [[4, 4], [1, 4], [4]], "shape2": [[4, 4], [4, 1], [4]], "transpose_a": [False], "transpose_b": [False], "constant_filter": [True, False], }, { "shape1": [[40, 37]], "shape2": [[37, 40]], "transpose_a": [False], "transpose_b": [False], "constant_filter": [True, False], }] def build_graph(parameters): input_tensor1 = tf.placeholder(dtype=tf.float32, name="input1", shape=parameters["shape1"]) # Get input_tensor2 either as a placeholder or constants. Also get a list of # the input tensors that are represented as placeholders. if parameters["constant_filter"]: input_tensor2 = create_tensor_data(np.float32, parameters["shape2"]) input_tensors = [input_tensor1] else: input_tensor2 = tf.placeholder( dtype=tf.float32, name="input2", shape=parameters["shape2"]) input_tensors = [input_tensor1, input_tensor2] out = tf.matmul(input_tensor1, input_tensor2, transpose_a=parameters["transpose_a"], transpose_b=parameters["transpose_b"]) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): # Build list of input values either containing 1 tensor (input_values1) or 2 # tensors (input_values1, input_values2) based on whether the second input # is a constant or variable input. values = [create_tensor_data(np.float32, shape=parameters["shape1"])] if not parameters["constant_filter"]: values.append(create_tensor_data(np.float32, parameters["shape2"])) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_l2norm_tests(zip_path): # Chose a set of parameters test_parameters = [{ "input_shape": [[5, 7], [1, 1, 1, 1], [1, 3, 4, 3], [3, 15, 14, 3], [3, 1, 2, 4, 6], [2, 2, 3, 4, 5, 6]], "dim": [0, 1, 2, 3, [2, 3], -2], "epsilon": [None, 1e-12, 1e-3], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) if parameters["epsilon"]: out = tf.nn.l2_normalize( input_tensor, parameters["dim"], epsilon=parameters["epsilon"]) else: out = tf.nn.l2_normalize(input_tensor, parameters["dim"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data( np.float32, parameters["input_shape"], min_value=-4, max_value=10) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_local_response_norm_tests(zip_path): # Chose a set of parameters test_parameters = [{ "input_shape": [[1, 1, 1, 1], [1, 3, 4, 3], [3, 15, 14, 3]], "depth_radius": [None, 0, 1, 3, 4, 5], "bias": [None, 0.1, 0.3, -0.1], "alpha": [None, 1, 2, -3], "beta": [None, 0.5, 0.25, 2], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=tf.float32, name="input", shape=parameters["input_shape"]) out = tf.nn.local_response_normalization( input_tensor, depth_radius=parameters["depth_radius"], bias=parameters["bias"], alpha=parameters["alpha"], beta=parameters["beta"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data( np.float32, parameters["input_shape"], min_value=-4, max_value=10) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_pad_tests(zip_path): # TODO(nupurgarg): Add test for tf.uint8. test_parameters = [ { "dtype": [tf.int32, tf.int64, tf.float32], "input_shape": [[1, 1, 2, 1], [2, 1, 1, 1]], "paddings": [[[0, 0], [0, 1], [2, 3], [0, 0]], [[0, 1], [0, 0], [0, 0], [2, 3]]], "constant_paddings": [True, False], }, # Non-4D use case. { "dtype": [tf.int32, tf.int64, tf.float32], "input_shape": [[1, 2], [0, 1, 2]], "paddings": [[[0, 1], [2, 3]]], "constant_paddings": [True, False], }, ] def build_graph(parameters): input_tensor = tf.placeholder( dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) # Get paddings as either a placeholder or constants. if parameters["constant_paddings"]: paddings = parameters["paddings"] input_tensors = [input_tensor] else: shape = [len(parameters["paddings"]), 2] paddings = tf.placeholder(dtype=tf.int32, name="padding", shape=shape) input_tensors = [input_tensor, paddings] out = tf.pad(input_tensor, paddings=paddings) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["dtype"], parameters["input_shape"]) ] if not parameters["constant_paddings"]: values.append(np.array(parameters["paddings"])) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_reshape_tests(zip_path): # All shapes below are suitable for tensors with 420 elements. test_parameters = [{ "dtype": [tf.float32, tf.int32], "input_shape": [[3, 4, 5, 7], [4, 105], [21, 5, 2, 2], [420]], "output_shape": [[15, 28], [420], [1, -1, 5, 7], [-1]], }] def build_graph(parameters): input_tensor = tf.placeholder(dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.reshape(input_tensor, shape=parameters["output_shape"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_resize_bilinear_tests(zip_path): test_parameters = [{ "dtype": [tf.float32, tf.int32], "input_shape": [[1, 3, 4, 3], [1, 10, 2, 1]], "size": [[1, 1], [4, 3], [2, 2], [5, 6]], "align_corners": [None, True, False], }] def build_graph(parameters): input_tensor = tf.placeholder(dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.image.resize_bilinear(input_tensor, size=parameters["size"], align_corners=parameters["align_corners"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_sigmoid_tests(zip_path): test_parameters = [{ "dtype": [tf.float32], "input_shape": [[1, 3, 4, 3], [4], [], [1, 2, 3, 4, 5, 6]], }] def build_graph(parameters): input_tensor = tf.placeholder(dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.sigmoid(input_tensor) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_softmax_tests(zip_path): test_parameters = [{ "dtype": [tf.float32], "input_shape": [[1, 3, 4, 3], [2, 3]], "dim": [-1, 0], }, { "dtype": [tf.float32], "input_shape": [[4, 7]], "dim": [-1, 1], }] def build_graph(parameters): input_tensor = tf.placeholder(dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.nn.softmax(input_tensor, dim=parameters["dim"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_space_to_depth_tests(zip_path): test_parameters = [{ "dtype": [tf.float32, tf.float16, tf.int32, tf.uint8, tf.int64], "input_shape": [[2, 12, 24, 1]], "block_size": [2, 3, 4], }] def build_graph(parameters): input_tensor = tf.placeholder(dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.space_to_depth(input_tensor, block_size=parameters["block_size"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_space_to_batch_nd_tests(zip_path): # TODO(nupurgarg): Add test for uint8. test_parameters = [ { "dtype": [tf.int32, tf.int64, tf.float32], "input_shape": [[1, 2, 2, 3], [2, 2, 4, 1]], "block_shape": [[1, 3], [2, 2]], "paddings": [[[0, 0], [0, 0]], [[0, 0], [2, 0]], [[1, 1], [1, 1]]], "constant_block_shape": [True, False], "constant_paddings": [True, False], }, { "dtype": [tf.float32], "input_shape": [[2, 3, 7, 3]], "block_shape": [[1, 3], [2, 2]], "paddings": [[[0, 0], [2, 0]], [[1, 0], [1, 0]]], "constant_block_shape": [True, False], "constant_paddings": [True, False], }, # Non-4D use case: 1 bath dimension, 3 spatial dimensions, 2 others. { "dtype": [tf.float32], "input_shape": [[1, 4, 4, 4, 1, 1]], "block_shape": [[2, 2, 2]], "paddings": [[[0, 0], [0, 0], [0, 0]]], "constant_block_shape": [True, False], "constant_paddings": [True, False], }, ] def build_graph(parameters): input_tensor = tf.placeholder( dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) input_tensors = [input_tensor] # Get block_shape either as a const or as a placeholder (tensor). if parameters["constant_block_shape"]: block_shape = parameters["block_shape"] else: shape = [len(parameters["block_shape"])] block_shape = tf.placeholder(dtype=tf.int32, name="shape", shape=shape) input_tensors.append(block_shape) # Get paddings either as a const or as a placeholder (tensor). if parameters["constant_paddings"]: paddings = parameters["paddings"] else: shape = [len(parameters["paddings"]), 2] paddings = tf.placeholder(dtype=tf.int32, name="paddings", shape=shape) input_tensors.append(paddings) out = tf.space_to_batch_nd(input_tensor, block_shape, paddings) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["dtype"], parameters["input_shape"]) ] if not parameters["constant_block_shape"]: values.append(np.array(parameters["block_shape"])) if not parameters["constant_paddings"]: values.append(np.array(parameters["paddings"])) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_batch_to_space_nd_tests(zip_path): test_parameters = [ { "dtype": [tf.float32, tf.int64, tf.int32], "input_shape": [[12, 3, 3, 1]], "block_shape": [[1, 4], [2, 2], [3, 4]], "crops": [[[0, 0], [0, 0]], [[1, 1], [1, 1]]], "constant_block_shape": [True, False], "constant_crops": [True, False], }, # Non-4D use case: 1 bath dimension, 3 spatial dimensions, 2 others. { "dtype": [tf.float32], "input_shape": [[8, 2, 2, 2, 1, 1]], "block_shape": [[2, 2, 2]], "crops": [[[0, 0], [0, 0], [0, 0]]], "constant_block_shape": [True, False], "constant_crops": [True, False], }, ] def build_graph(parameters): input_tensor = tf.placeholder( dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) input_tensors = [input_tensor] # Get block_shape either as a const or as a placeholder (tensor). if parameters["constant_block_shape"]: block_shape = parameters["block_shape"] else: shape = [len(parameters["block_shape"])] block_shape = tf.placeholder(dtype=tf.int32, name="shape", shape=shape) input_tensors.append(block_shape) # Get crops either as a const or as a placeholder (tensor). if parameters["constant_crops"]: crops = parameters["crops"] else: shape = [len(parameters["crops"]), 2] crops = tf.placeholder(dtype=tf.int32, name="crops", shape=shape) input_tensors.append(crops) out = tf.batch_to_space_nd(input_tensor, block_shape, crops) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["dtype"], parameters["input_shape"]) ] if not parameters["constant_block_shape"]: values.append(np.array(parameters["block_shape"])) if not parameters["constant_crops"]: values.append(np.array(parameters["crops"])) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_transpose_tests(zip_path): # TODO(nupurgarg): Add test for uint8. test_parameters = [{ "dtype": [tf.int32, tf.int64, tf.float32], "input_shape": [[2, 2, 3]], "perm": [[0, 1, 2], [0, 2, 1]], "constant_perm": [True, False], }, { "dtype": [tf.float32], "input_shape": [[1, 2, 3, 4]], "perm": [[0, 1, 2, 3], [3, 0, 1, 2]], "constant_perm": [True, False], }, { "dtype": [tf.float32], "input_shape": [[1, 2, 3, 4, 5]], "perm": [[4, 3, 2, 1, 0]], "constant_perm": [True, False], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) if parameters["constant_perm"]: perm = parameters["perm"] input_tensors = [input_tensor] else: shape = [len(parameters["perm"]), 2] perm = tf.placeholder(dtype=tf.int32, name="perm", shape=shape) input_tensors = [input_tensor, perm] out = tf.transpose(input_tensor, perm=perm) return input_tensors, [out] def build_inputs(parameters, sess, inputs, outputs): values = [ create_tensor_data(parameters["dtype"], parameters["input_shape"]) ] if not parameters["constant_perm"]: values.append(np.array(parameters["perm"])) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_squeeze_tests(zip_path): test_parameters = [{ "dtype": [tf.int32, tf.float32, tf.int64], "input_shape": [[1, 2, 1, 3, 1, 4, 1, 1]], "axis": [ None, [], [0, 2], [4, 7], [-1, 0, 2, 0, 7, -6], [1], [2, 3, 2], [-1, -2, -4, -6, -8], [0, 2, 4, 6, 7], [7, 6, 4, 2, 0], [6, 6], [0, 1, 2, 3, 4, 5, 6, 7], [-2, -3, 1, 0, 7, -5] ], }, { "dtype": [tf.int32, tf.float32, tf.int64], "input_shape": [[1]], "axis": [None, [], [0], [-1]], }, { "dtype": [tf.int32, tf.float32, tf.int64], "input_shape": [[1, 1, 1, 1, 1]], "axis": [None, [], [0], [3, 0], [-2, 0, 3, 2]], }] def build_graph(parameters): input_tensor = tf.placeholder( dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) out = tf.squeeze(input_tensor, axis=parameters["axis"]) return [input_tensor], [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(parameters["dtype"], parameters["input_shape"]) return [input_values], sess.run( outputs, feed_dict=dict(zip(inputs, [input_values]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_strided_slice_tests(zip_path): # TODO(soroosh): add test/support for uint8. test_parameters = [ # 4-D { "dtype": [tf.float32, tf.int32, tf.int64], "index_type": [tf.int32], "input_shape": [[12, 2, 2, 5]], "begin": [[0, 0, 0, 0], [1, 0, 1, 0]], "end": [[8, 2, 2, 3], [12, 2, 2, 5]], "strides": [None, [2, 1, 3, 1]], "begin_mask": [None, 1, 8], "end_mask": [None, 1, 8], "shrink_axis_mask": [None, 1, 8, 11, 15, -1], "constant_indices": [False, True], }, # TODO(b/73170889) Restore test paramaters removed in cl/191608113. # 2-D { "dtype": [tf.float32, tf.int32, tf.int64], "index_type": [tf.int32], "input_shape": [[2, 3]], "begin": [[0, 0], [1, 0]], "end": [[2, 3], [2, 2]], "strides": [None, [2, 2]], "begin_mask": [None, 1, 2], "end_mask": [None, 1, 2], "shrink_axis_mask": [None, 1, 2, 3, -1], "constant_indices": [False, True], }, # Negative strides { "dtype": [tf.float32], "index_type": [tf.int32], "input_shape": [[2, 3]], "begin": [[0, -1]], "end": [[2, -3]], "strides": [[1, -1]], "begin_mask": [None, 1, 2], "end_mask": [None, 1, 2], "shrink_axis_mask": [None, 1, 2, 3, -1], "constant_indices": [False], }, ] def build_graph(parameters): input_tensor = tf.placeholder( dtype=parameters["dtype"], name="input", shape=parameters["input_shape"]) if parameters["constant_indices"]: begin = parameters["begin"] end = parameters["end"] strides = parameters["strides"] tensors = [input_tensor] else: begin = tf.placeholder( dtype=parameters["index_type"], name="begin", shape=[len(parameters["input_shape"])]) end = tf.placeholder( dtype=parameters["index_type"], name="end", shape=[len(parameters["input_shape"])]) strides = ( tf.placeholder( dtype=parameters["index_type"], name="strides", shape=[len(parameters["input_shape"])]) if parameters["strides"] is not None else None) tensors = [input_tensor, begin, end] if strides is not None: tensors.append(strides) out = tf.strided_slice( input_tensor, begin, end, strides, begin_mask=parameters["begin_mask"], end_mask=parameters["end_mask"]) return tensors, [out] def build_inputs(parameters, sess, inputs, outputs): input_values = create_tensor_data(parameters["dtype"], parameters["input_shape"]) index_type = _TF_TYPE_INFO[parameters["index_type"]][0] values = [input_values] if not parameters["constant_indices"]: begin_values = np.array(parameters["begin"]).astype(index_type) end_values = np.array(parameters["end"]).astype(index_type) stride_values = ( np.array(parameters["strides"]).astype(index_type) if parameters["strides"] is not None else None) values.append(begin_values) values.append(end_values) if stride_values is not None: values.append(stride_values) return values, sess.run(outputs, feed_dict=dict(zip(inputs, values))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_lstm_tests(zip_path): test_parameters = [ { "dtype": [tf.float32], "num_batchs": [1], "time_step_size": [1], "input_vec_size": [3], "num_cells": [4], }, ] def build_graph(parameters): num_batchs = parameters["num_batchs"] time_step_size = parameters["time_step_size"] input_vec_size = parameters["input_vec_size"] num_cells = parameters["num_cells"] inputs_after_split = [] for i in xrange(time_step_size): one_timestamp_input = tf.placeholder( dtype=parameters["dtype"], name="split_{}".format(i), shape=[num_batchs, input_vec_size]) inputs_after_split.append(one_timestamp_input) # Currently lstm identifier has a few limitations: only supports # forget_bias == 0, inner state activiation == tanh. # TODO(zhixianyan): Add another test with forget_bias == 1. # TODO(zhixianyan): Add another test with relu as activation. lstm_cell = tf.contrib.rnn.BasicLSTMCell( num_cells, forget_bias=0.0, state_is_tuple=True) cell_outputs, _ = rnn.static_rnn( lstm_cell, inputs_after_split, dtype=tf.float32) out = cell_outputs[-1] return inputs_after_split, [out] def build_inputs(parameters, sess, inputs, outputs): with tf.variable_scope("", reuse=True): kernel = tf.get_variable("rnn/basic_lstm_cell/kernel") bias = tf.get_variable("rnn/basic_lstm_cell/bias") kernel_values = create_tensor_data( parameters["dtype"], [kernel.shape[0], kernel.shape[1]], -1, 1) bias_values = create_tensor_data(parameters["dtype"], [bias.shape[0]], 0, 1) sess.run(tf.group(kernel.assign(kernel_values), bias.assign(bias_values))) num_batchs = parameters["num_batchs"] time_step_size = parameters["time_step_size"] input_vec_size = parameters["input_vec_size"] input_values = [] for _ in xrange(time_step_size): tensor_data = create_tensor_data(parameters["dtype"], [num_batchs, input_vec_size], 0, 1) input_values.append(tensor_data) out = sess.run(outputs, feed_dict=dict(zip(inputs, input_values))) return input_values, out # TODO(zhixianyan): Automatically generate rnn_states for lstm cell. extra_toco_options = ExtraTocoOptions() extra_toco_options.rnn_states = ( "{state_array:rnn/BasicLSTMCellZeroState/zeros," "back_edge_source_array:rnn/basic_lstm_cell/Add_1,size:4}," "{state_array:rnn/BasicLSTMCellZeroState/zeros_1," "back_edge_source_array:rnn/basic_lstm_cell/Mul_2,size:4}") make_zip_of_tests( zip_path, test_parameters, build_graph, build_inputs, extra_toco_options, use_frozen_graph=True) def make_l2_pool(input_tensor, ksize, strides, padding, data_format): return tf.sqrt(tf.nn.avg_pool( tf.square(input_tensor), ksize=ksize, strides=strides, padding=padding, data_format=data_format)) def make_topk_tests(zip_path): test_parameters = [{ "input_dtype": [tf.float32, tf.int32], "input_shape": [[10], [5, 20]], }] def build_graph(parameters): input_value = tf.placeholder( dtype=parameters["input_dtype"], name="input", shape=parameters["input_shape"]) k = tf.constant(3, name="k") out = tf.nn.top_k(input_value, k) return [input_value], [out[1]] def build_inputs(parameters, sess, inputs, outputs): input_value = create_tensor_data(parameters["input_dtype"], parameters["input_shape"]) return [input_value], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_arg_max_tests(zip_path): test_parameters = [{ "input_dtype": [tf.float32, tf.int32], "input_shape": [[1, 1, 1, 3], [2, 3, 4, 5], [2, 3, 3], [5, 5], [10]], "axis": [0, 1, 2, 3], "output_type": [tf.int32, tf.int64], }] def build_graph(parameters): input_value = tf.placeholder( dtype=parameters["input_dtype"], name="input", shape=parameters["input_shape"]) axis = tf.constant(parameters["axis"], name="axis") out = tf.arg_max(input_value, axis, output_type=parameters["output_type"]) return [input_value], [out] def build_inputs(parameters, sess, inputs, outputs): input_value = create_tensor_data(parameters["input_dtype"], parameters["input_shape"]) return [input_value], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) def make_less_tests(zip_path): test_parameters = [{ "input_dtype": [tf.float32, tf.int32, tf.int64], "input_shape_pair": [([1, 1, 1, 3], [1, 1, 1, 3]), ([2, 3, 4, 5], [2, 3, 4, 5]), ([2, 3, 3], [2, 3]), ([5, 5], [1]), ([10], [2, 4, 10])], }] def build_graph(parameters): input_value1 = tf.placeholder( dtype=parameters["input_dtype"], name="input1", shape=parameters["input_shape_pair"][0]) input_value2 = tf.placeholder( dtype=parameters["input_dtype"], name="input2", shape=parameters["input_shape_pair"][1]) out = tf.less(input_value1, input_value2) return [input_value1, input_value2], [out] def build_inputs(parameters, sess, inputs, outputs): input_value1 = create_tensor_data(parameters["input_dtype"], parameters["input_shape_pair"][0]) input_value2 = create_tensor_data(parameters["input_dtype"], parameters["input_shape_pair"][1]) return [input_value1, input_value2], sess.run( outputs, feed_dict=dict(zip(inputs, [input_value1, input_value2]))) make_zip_of_tests(zip_path, test_parameters, build_graph, build_inputs) # Toco binary path provided by the generate rule. bin_path = None def main(unused_args): global bin_path def mkdir_if_not_exist(x): if not os.path.isdir(x): os.mkdir(x) if not os.path.isdir(x): raise RuntimeError("Failed to create dir %r" % x) opstest_path = os.path.join(FLAGS.output_path) mkdir_if_not_exist(opstest_path) out = FLAGS.zip_to_output bin_path = FLAGS.toco test_function = ("make_%s_tests" % out.replace(".zip", "")) if test_function not in globals(): raise RuntimeError("Can't find a test function to create %r. Tried %r" % (out, test_function)) globals()[test_function](os.path.join(opstest_path, out)) if __name__ == "__main__": FLAGS, unparsed = parser.parse_known_args() if unparsed: print("Usage: %s <path out> <zip file to generate>") else: tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
true
true
f72a4e3b9390c65a9d4226e4e2bfa029a474c9d9
10,627
py
Python
work_dirs/bsnet_fcos_test/bsnet_fcos_test.py
zzx0226/mmocr
50354895244339a392b4f1af5a35963883923cca
[ "Apache-2.0" ]
null
null
null
work_dirs/bsnet_fcos_test/bsnet_fcos_test.py
zzx0226/mmocr
50354895244339a392b4f1af5a35963883923cca
[ "Apache-2.0" ]
null
null
null
work_dirs/bsnet_fcos_test/bsnet_fcos_test.py
zzx0226/mmocr
50354895244339a392b4f1af5a35963883923cca
[ "Apache-2.0" ]
null
null
null
checkpoint_config = dict(interval=10) log_config = dict( interval=5, hooks=[dict(type='TextLoggerHook'), dict(type='TensorboardLoggerHook')]) dist_params = dict(backend='nccl') log_level = 'INFO' load_from = None resume_from = None workflow = [('train', 1)] optimizer = dict(type='SGD', lr=0.001, momentum=0.9, weight_decay=0.0005) optimizer_config = dict(grad_clip=None) lr_config = dict(policy='poly', power=0.9, min_lr=1e-07, by_epoch=True) total_epochs = 1500 cp_num = 8 bs_degree = 4 reconstr_points = 100 model = dict( type='BSNet_fcos', backbone=dict( type='mmdet.ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch', dcn=dict(type='DCNv2', deform_groups=2, fallback_on_stride=False), init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50'), stage_with_dcn=(False, True, True, True)), neck=dict( type='mmdet.FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, start_level=0, add_extra_convs='on_output', num_outs=5, relu_before_extra_convs=True), bbox_head=dict( type='BS_FCOSHead', bs_degree=4, cp_num=8, num_classes=1, in_channels=256, stacked_convs=4, feat_channels=256, strides=[8, 16, 32, 64, 128], loss_cls=dict( type='FocalLoss', use_sigmoid=True, gamma=2.0, alpha=0.25, loss_weight=1.0), loss_bbox=dict(type='IoULoss', loss_weight=1.0), loss_centerness=dict( type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0), postprocessor=dict( type='BSPostprocessor_fcos', bs_degree=4, cp_num=8, num_reconstr_points=100, alpha=1.0, beta=2.0, score_thr=0.1)), train_cfg=None, test_cfg=dict( nms_pre=1000, min_bbox_size=0, score_thr=0.05, nms=dict(type='nms', iou_threshold=0.5), max_per_img=100, classes=('text', ))) cp = 14 bs = 4 dataset_type = 'CurveDataset' data_root = '/home/atom/Research_STD/Datasets/mmocr/ctw1500' train = dict( type='CurveDataset', ann_file= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/train_labels_with_bs_4_cp_14.json', img_prefix='/home/atom/Research_STD/Datasets/mmocr/ctw1500/imgs/training/', pipeline=None) test = dict( type='CurveDataset', ann_file= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/CTW_test_with_bs_4_cp_14.json', img_prefix='/home/atom/Research_STD/Datasets/mmocr/ctw1500/imgs/test/', pipeline=None) train_list = [ dict( type='CurveDataset', ann_file= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/train_labels_with_bs_4_cp_14.json', img_prefix= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/imgs/training/', pipeline=None) ] test_list = [ dict( type='CurveDataset', ann_file= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/CTW_test_with_bs_4_cp_14.json', img_prefix='/home/atom/Research_STD/Datasets/mmocr/ctw1500/imgs/test/', pipeline=None) ] img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) leval_prop_range_icdar2015 = ((0, 0.4), (0.3, 0.7), (0.6, 1.0)) train_pipeline_icdar2015 = [ dict(type='LoadImageFromFile', color_type='color_ignore_orientation'), dict(type='LoadTextAnnotations', with_bbox=True), dict(type='Load_bs_cp'), dict( type='ColorJitter', brightness=0.12549019607843137, saturation=0.5, contrast=0.5), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='RandomScaling', size=800, scale=(0.75, 2.5)), dict(type='Resize', img_scale=(800, 800), keep_ratio=True), dict(type='Resize_cp'), dict(type='RandomFlip', flip_ratio=0.0, direction='horizontal'), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='FormatBundle_cp'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels', 'gt_cp']) ] img_scale_icdar2015 = (2260, 2260) test_pipeline_icdar2015 = [ dict(type='LoadImageFromFile', color_type='color_ignore_orientation'), dict( type='MultiScaleFlipAug', img_scale=(2260, 2260), flip=False, transforms=[ dict(type='Resize', img_scale=(1280, 800), keep_ratio=True), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ]) ] train_pipeline_ctw1500 = [ dict(type='LoadImageFromFile', color_type='color_ignore_orientation'), dict(type='LoadTextAnnotations', with_bbox=True), dict(type='Load_bs_cp'), dict( type='ColorJitter', brightness=0.12549019607843137, saturation=0.5, contrast=0.5), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='RandomScaling', size=800, scale=(0.75, 2.5)), dict(type='Resize', img_scale=(800, 800), keep_ratio=True), dict(type='Resize_cp'), dict(type='RandomFlip', flip_ratio=0.0, direction='horizontal'), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='FormatBundle_cp'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels', 'gt_cp']) ] test_pipeline_ctw1500 = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(800, 800), flip=False, transforms=[ dict(type='Resize', img_scale=(800, 800), keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.0), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ]) ] data = dict( samples_per_gpu=10, workers_per_gpu=6, val_dataloader=dict(samples_per_gpu=1), test_dataloader=dict(samples_per_gpu=1), train=dict( type='UniformConcatDataset', datasets=[ dict( type='CurveDataset', ann_file= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/train_labels_with_bs_4_cp_14.json', img_prefix= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/imgs/training/', pipeline=None) ], pipeline=[ dict( type='LoadImageFromFile', color_type='color_ignore_orientation'), dict(type='LoadTextAnnotations', with_bbox=True), dict(type='Load_bs_cp'), dict( type='ColorJitter', brightness=0.12549019607843137, saturation=0.5, contrast=0.5), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='RandomScaling', size=800, scale=(0.75, 2.5)), dict(type='Resize', img_scale=(800, 800), keep_ratio=True), dict(type='Resize_cp'), dict(type='RandomFlip', flip_ratio=0.0, direction='horizontal'), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='FormatBundle_cp'), dict( type='Collect', keys=['img', 'gt_bboxes', 'gt_labels', 'gt_cp']) ]), val=dict( type='UniformConcatDataset', datasets=[ dict( type='CurveDataset', ann_file= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/CTW_test_with_bs_4_cp_14.json', img_prefix= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/imgs/test/', pipeline=None) ], pipeline=[ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(800, 800), flip=False, transforms=[ dict(type='Resize', img_scale=(800, 800), keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.0), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ]) ]), test=dict( type='UniformConcatDataset', datasets=[ dict( type='CurveDataset', ann_file= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/CTW_test_with_bs_4_cp_14.json', img_prefix= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/imgs/test/', pipeline=None) ], pipeline=[ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(800, 800), flip=False, transforms=[ dict(type='Resize', img_scale=(800, 800), keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.0), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ]) ])) evaluation = dict(interval=20, metric='hmean-iou') work_dir = './work_dirs/bsnet_fcos_test' gpu_ids = [1]
35.423333
99
0.555472
checkpoint_config = dict(interval=10) log_config = dict( interval=5, hooks=[dict(type='TextLoggerHook'), dict(type='TensorboardLoggerHook')]) dist_params = dict(backend='nccl') log_level = 'INFO' load_from = None resume_from = None workflow = [('train', 1)] optimizer = dict(type='SGD', lr=0.001, momentum=0.9, weight_decay=0.0005) optimizer_config = dict(grad_clip=None) lr_config = dict(policy='poly', power=0.9, min_lr=1e-07, by_epoch=True) total_epochs = 1500 cp_num = 8 bs_degree = 4 reconstr_points = 100 model = dict( type='BSNet_fcos', backbone=dict( type='mmdet.ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch', dcn=dict(type='DCNv2', deform_groups=2, fallback_on_stride=False), init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50'), stage_with_dcn=(False, True, True, True)), neck=dict( type='mmdet.FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, start_level=0, add_extra_convs='on_output', num_outs=5, relu_before_extra_convs=True), bbox_head=dict( type='BS_FCOSHead', bs_degree=4, cp_num=8, num_classes=1, in_channels=256, stacked_convs=4, feat_channels=256, strides=[8, 16, 32, 64, 128], loss_cls=dict( type='FocalLoss', use_sigmoid=True, gamma=2.0, alpha=0.25, loss_weight=1.0), loss_bbox=dict(type='IoULoss', loss_weight=1.0), loss_centerness=dict( type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0), postprocessor=dict( type='BSPostprocessor_fcos', bs_degree=4, cp_num=8, num_reconstr_points=100, alpha=1.0, beta=2.0, score_thr=0.1)), train_cfg=None, test_cfg=dict( nms_pre=1000, min_bbox_size=0, score_thr=0.05, nms=dict(type='nms', iou_threshold=0.5), max_per_img=100, classes=('text', ))) cp = 14 bs = 4 dataset_type = 'CurveDataset' data_root = '/home/atom/Research_STD/Datasets/mmocr/ctw1500' train = dict( type='CurveDataset', ann_file= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/train_labels_with_bs_4_cp_14.json', img_prefix='/home/atom/Research_STD/Datasets/mmocr/ctw1500/imgs/training/', pipeline=None) test = dict( type='CurveDataset', ann_file= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/CTW_test_with_bs_4_cp_14.json', img_prefix='/home/atom/Research_STD/Datasets/mmocr/ctw1500/imgs/test/', pipeline=None) train_list = [ dict( type='CurveDataset', ann_file= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/train_labels_with_bs_4_cp_14.json', img_prefix= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/imgs/training/', pipeline=None) ] test_list = [ dict( type='CurveDataset', ann_file= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/CTW_test_with_bs_4_cp_14.json', img_prefix='/home/atom/Research_STD/Datasets/mmocr/ctw1500/imgs/test/', pipeline=None) ] img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) leval_prop_range_icdar2015 = ((0, 0.4), (0.3, 0.7), (0.6, 1.0)) train_pipeline_icdar2015 = [ dict(type='LoadImageFromFile', color_type='color_ignore_orientation'), dict(type='LoadTextAnnotations', with_bbox=True), dict(type='Load_bs_cp'), dict( type='ColorJitter', brightness=0.12549019607843137, saturation=0.5, contrast=0.5), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='RandomScaling', size=800, scale=(0.75, 2.5)), dict(type='Resize', img_scale=(800, 800), keep_ratio=True), dict(type='Resize_cp'), dict(type='RandomFlip', flip_ratio=0.0, direction='horizontal'), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='FormatBundle_cp'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels', 'gt_cp']) ] img_scale_icdar2015 = (2260, 2260) test_pipeline_icdar2015 = [ dict(type='LoadImageFromFile', color_type='color_ignore_orientation'), dict( type='MultiScaleFlipAug', img_scale=(2260, 2260), flip=False, transforms=[ dict(type='Resize', img_scale=(1280, 800), keep_ratio=True), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ]) ] train_pipeline_ctw1500 = [ dict(type='LoadImageFromFile', color_type='color_ignore_orientation'), dict(type='LoadTextAnnotations', with_bbox=True), dict(type='Load_bs_cp'), dict( type='ColorJitter', brightness=0.12549019607843137, saturation=0.5, contrast=0.5), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='RandomScaling', size=800, scale=(0.75, 2.5)), dict(type='Resize', img_scale=(800, 800), keep_ratio=True), dict(type='Resize_cp'), dict(type='RandomFlip', flip_ratio=0.0, direction='horizontal'), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='FormatBundle_cp'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels', 'gt_cp']) ] test_pipeline_ctw1500 = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(800, 800), flip=False, transforms=[ dict(type='Resize', img_scale=(800, 800), keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.0), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ]) ] data = dict( samples_per_gpu=10, workers_per_gpu=6, val_dataloader=dict(samples_per_gpu=1), test_dataloader=dict(samples_per_gpu=1), train=dict( type='UniformConcatDataset', datasets=[ dict( type='CurveDataset', ann_file= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/train_labels_with_bs_4_cp_14.json', img_prefix= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/imgs/training/', pipeline=None) ], pipeline=[ dict( type='LoadImageFromFile', color_type='color_ignore_orientation'), dict(type='LoadTextAnnotations', with_bbox=True), dict(type='Load_bs_cp'), dict( type='ColorJitter', brightness=0.12549019607843137, saturation=0.5, contrast=0.5), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='RandomScaling', size=800, scale=(0.75, 2.5)), dict(type='Resize', img_scale=(800, 800), keep_ratio=True), dict(type='Resize_cp'), dict(type='RandomFlip', flip_ratio=0.0, direction='horizontal'), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='FormatBundle_cp'), dict( type='Collect', keys=['img', 'gt_bboxes', 'gt_labels', 'gt_cp']) ]), val=dict( type='UniformConcatDataset', datasets=[ dict( type='CurveDataset', ann_file= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/CTW_test_with_bs_4_cp_14.json', img_prefix= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/imgs/test/', pipeline=None) ], pipeline=[ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(800, 800), flip=False, transforms=[ dict(type='Resize', img_scale=(800, 800), keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.0), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ]) ]), test=dict( type='UniformConcatDataset', datasets=[ dict( type='CurveDataset', ann_file= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/CTW_test_with_bs_4_cp_14.json', img_prefix= '/home/atom/Research_STD/Datasets/mmocr/ctw1500/imgs/test/', pipeline=None) ], pipeline=[ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(800, 800), flip=False, transforms=[ dict(type='Resize', img_scale=(800, 800), keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.0), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ]) ])) evaluation = dict(interval=20, metric='hmean-iou') work_dir = './work_dirs/bsnet_fcos_test' gpu_ids = [1]
true
true
f72a4e46e33271ff312daf81e2aa725c8a324bb1
584
py
Python
code/heap.py
philipmassouh/RoA
ed57d9da44cd04496dfc4c43f11b3ead99d58608
[ "Apache-2.0" ]
null
null
null
code/heap.py
philipmassouh/RoA
ed57d9da44cd04496dfc4c43f11b3ead99d58608
[ "Apache-2.0" ]
null
null
null
code/heap.py
philipmassouh/RoA
ed57d9da44cd04496dfc4c43f11b3ead99d58608
[ "Apache-2.0" ]
null
null
null
def heapify(heap, root): newRoot = root leftChild = 2*root+1 rightChild = 2*root+2 if leftChild < len(heap) and heap[leftChild] > heap[newRoot]: newRoot = leftChild if rightChild < len(heap) and heap[rightChild] > heap[newRoot]: newRoot = rightChild if root!=newRoot: heap[root],heap[newRoot]=heap[newRoot],heap[root] heapify(heap,newRoot) def heapSort(heap): for i in range(len(heap), -1, -1): heapify(heap, i) answer = [] while(len(heap)>1): answer.insert(len(answer),heap[0]) heap[0],heap[-1]=heap[-1],heap[0] heap.pop() heapify(heap, 0) return answer
25.391304
64
0.679795
def heapify(heap, root): newRoot = root leftChild = 2*root+1 rightChild = 2*root+2 if leftChild < len(heap) and heap[leftChild] > heap[newRoot]: newRoot = leftChild if rightChild < len(heap) and heap[rightChild] > heap[newRoot]: newRoot = rightChild if root!=newRoot: heap[root],heap[newRoot]=heap[newRoot],heap[root] heapify(heap,newRoot) def heapSort(heap): for i in range(len(heap), -1, -1): heapify(heap, i) answer = [] while(len(heap)>1): answer.insert(len(answer),heap[0]) heap[0],heap[-1]=heap[-1],heap[0] heap.pop() heapify(heap, 0) return answer
true
true
f72a4e980f110ebf4b26838dad3e5987b3b5af11
8,123
py
Python
shalstm/qa/model.py
alisafaya/shalstm
3d85f29c82451b393975ba587d53e0db0e43fff9
[ "MIT" ]
null
null
null
shalstm/qa/model.py
alisafaya/shalstm
3d85f29c82451b393975ba587d53e0db0e43fff9
[ "MIT" ]
null
null
null
shalstm/qa/model.py
alisafaya/shalstm
3d85f29c82451b393975ba587d53e0db0e43fff9
[ "MIT" ]
null
null
null
import torch.nn as nn import torch from shalstm import SHALSTM from shalstm.utils import top_k_top_p_filtering class SHALSTMforQuestionAnswering(SHALSTM): def forward(self, input, attention_mask=None, type_ids=None, hidden=None, mems=None, return_loss=False, lm_loss=False): """ all arguments have shape (seq length, batch) padding should be on left for input, on right for targets (as in seq2seq models) - type_ids is used both for loss masking and attention masking. it should be 1 for the answer tokens and 0 otherwise. - attention_mask (attention mask) is 0 for paddings and 1 for other tokens """ x = input[:-1].to(self.device) targets = input[1:].to(self.device) seq_len, batch_size = x.shape if attention_mask is None: attention_mask = torch.ones(*x.shape) if type_ids is None: type_ids = torch.zeros(*input.shape) loss_mask = type_ids[1:].view(-1).to(self.device) # encode and dropout input h = self.encoder(x) h = self.idrop(h) # if memory is provided, trim it to fit max memory size if attention_mask is None: attn_mask = torch.full((seq_len, seq_len), -1e6, device=h.device, dtype=h.dtype) # instead of -Inf we use -1,000,000 attn_mask = torch.triu(attn_mask, diagonal=1) # concatenate memories from the previous pass if provided if mems is not None: max_mems = max(len(m) for m in mems) mem_mask = torch.zeros((seq_len, max_mems), device=h.device, dtype=h.dtype) attn_mask = torch.cat([mem_mask, attn_mask], dim=-1) else: attention_mask = attention_mask.to(self.device) attn_mask = torch.full((batch_size, seq_len, seq_len), -1e6, device=self.device, dtype=h.dtype) attn_mask = torch.triu(attn_mask, diagonal=1) for b in range(batch_size): mask = torch.where(attention_mask[:-1, b] == 0) attn_mask[b, :, mask[0]] = -1e6 attn_mask[b, mask[0], :] = -1e6 # concatenate memories from the previous pass if provided if mems is not None: max_mems = max(len(m) for m in mems) mem_mask = torch.zeros((batch_size, seq_len, max_mems), device=h.device, dtype=h.dtype) attn_mask = torch.cat([mem_mask, attn_mask], dim=-1) # iterate over blocks new_hidden, new_mems = [], [] for idx, block in enumerate(self.blocks): mem = mems[idx] if mems is not None else None hid = hidden[idx] if hidden is not None else None h, new_mem, new_hid = block(h, attn_mask, self.memory_size, memory=mem, hidden=hid) new_hidden.append(new_hid) new_mems.append(new_mem) # final dropout h = self.odrop(h) if return_loss: if not lm_loss: # calculate loss targets are provided loss = -(self.splitloss(h.view(-1, self.embed_size), input[1:].to(self.device).view(-1)).output * loss_mask).mean() # .view(*x.shape).mean(0).mean() else: # calculate loss on all tokens loss = self.ate(h.view(-1, self.embed_size), input[1:].to(self.device).view(-1)).loss return loss, h, new_hidden, new_mems else: # calculate predictions output = self.splitloss.log_prob(h.view(-1, self.embed_size)) output = output.view(*x.shape, -1) return output, h, new_hidden, new_mems def conditional_generate(self, input, attention_mask, type_ids, eos_id=2, max_length=64, use_sampling=False, top_p=0.95, temperature=1.0): """ input sequence has shape [seq length, batch size] """ prompt = torch.cat([input, torch.zeros(1, input.shape[1], dtype=torch.long)]) attention_mask = torch.cat([attention_mask, torch.ones(1, attention_mask.shape[1])]) type_ids = torch.cat([type_ids, torch.zeros(1, type_ids.shape[1])]) self.eval() sequences = torch.zeros(max_length, input.shape[1], dtype=torch.long) hidden, mems = None, None with torch.no_grad(): output, h, hidden, mems = self(prompt[:-1], attention_mask=attention_mask[:-1], type_ids=type_ids[:-1], hidden=hidden, mems=mems) prompt = prompt[-2:] attention_mask=attention_mask[-2:] type_ids=type_ids[-2:] for i in range(max_length): output, h, hidden, mems = self(prompt, attention_mask=attention_mask, type_ids=type_ids, hidden=hidden, mems=mems) if use_sampling: raise NotImplementedError token_weights = top_k_top_p_filtering(torch.exp(output.view(-1)) / temperature, top_p=top_p, filter_value=0.0) output_idx = torch.multinomial(token_weights, num_samples=1)[0] else: output_idx = torch.argmax(output, dim=-1) prompt[0, :] = output_idx sequences[i, :] = output_idx if torch.all(output_idx == eos_id): break return sequences if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument("--model", type=str, default="bin/base/model") parser.add_argument("--tokenizer", type=str, default="tokenizer/tokenizer.json") parser.add_argument("--device", type=str, default="cuda") args = parser.parse_args() model = SHALSTMforQuestionAnswering.from_pretrained(args.model, device=torch.device(args.device)) from tokenizer import SHALSTMTokenizer tokenizer = SHALSTMTokenizer.from_file(args.tokenizer) questions = [ "another thing there", "some length here", ] answers = [ "brother Hi how", "this answer for question one", ] input, attn_mask, type_ids, input_length = tokenizer.encode_for_qa(questions, answers) loss, h, hidden, mems = model(input, attn_mask, type_ids, return_loss=True) warmup = 5 total_steps = 1500 optimizer = torch.optim.SGD(model.parameters(), lr=1e-2) scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=[lambda x: float(x / warmup) if x < warmup else float((total_steps - x) / total_steps)]) use_amp = False scaler = torch.cuda.amp.GradScaler(enabled=use_amp) import time starttime = time.time() model.train() for i in range(total_steps): with torch.cuda.amp.autocast(enabled=use_amp): loss, h, hidden, mems = model(input, attn_mask, type_ids, return_loss=True) scaler.scale(loss).backward() scaler.unscale_(optimizer) torch.nn.utils.clip_grad_norm_(model.parameters(), 0.1) scaler.step(optimizer) scaler.update() scheduler.step() if i % (total_steps // 10) == 0: print(loss.item()) print("Excecution time =", (time.time() - starttime) / total_steps, "sec per batch") questions = [ "question one ?", "some length here", ] answers = [ "this answer to this one", "This is another answer for another question ", ] input, attn_mask, type_ids, input_length = tokenizer.encode_for_qa(questions, answers) with torch.no_grad(): model.eval() output, h, hidden, mems = model(input, attn_mask, type_ids) output = torch.argmax(output, dim=-1) ids = output[input_length - 1:].t().cpu().tolist() ids = output.t().cpu().tolist() print(tokenizer.decode(ids[0])) print(tokenizer.decode(ids[1])) input, attn_mask, type_ids, input_length = tokenizer.encode_for_qa(questions, direction='left') sequence = model.conditional_generate(input, attn_mask, type_ids, max_length=10, use_sampling=False) print("Conditional generation") print(tokenizer.decode_batch(sequence.t().cpu().tolist()))
38.866029
164
0.612582
import torch.nn as nn import torch from shalstm import SHALSTM from shalstm.utils import top_k_top_p_filtering class SHALSTMforQuestionAnswering(SHALSTM): def forward(self, input, attention_mask=None, type_ids=None, hidden=None, mems=None, return_loss=False, lm_loss=False): x = input[:-1].to(self.device) targets = input[1:].to(self.device) seq_len, batch_size = x.shape if attention_mask is None: attention_mask = torch.ones(*x.shape) if type_ids is None: type_ids = torch.zeros(*input.shape) loss_mask = type_ids[1:].view(-1).to(self.device) h = self.encoder(x) h = self.idrop(h) if attention_mask is None: attn_mask = torch.full((seq_len, seq_len), -1e6, device=h.device, dtype=h.dtype) attn_mask = torch.triu(attn_mask, diagonal=1) if mems is not None: max_mems = max(len(m) for m in mems) mem_mask = torch.zeros((seq_len, max_mems), device=h.device, dtype=h.dtype) attn_mask = torch.cat([mem_mask, attn_mask], dim=-1) else: attention_mask = attention_mask.to(self.device) attn_mask = torch.full((batch_size, seq_len, seq_len), -1e6, device=self.device, dtype=h.dtype) attn_mask = torch.triu(attn_mask, diagonal=1) for b in range(batch_size): mask = torch.where(attention_mask[:-1, b] == 0) attn_mask[b, :, mask[0]] = -1e6 attn_mask[b, mask[0], :] = -1e6 if mems is not None: max_mems = max(len(m) for m in mems) mem_mask = torch.zeros((batch_size, seq_len, max_mems), device=h.device, dtype=h.dtype) attn_mask = torch.cat([mem_mask, attn_mask], dim=-1) new_hidden, new_mems = [], [] for idx, block in enumerate(self.blocks): mem = mems[idx] if mems is not None else None hid = hidden[idx] if hidden is not None else None h, new_mem, new_hid = block(h, attn_mask, self.memory_size, memory=mem, hidden=hid) new_hidden.append(new_hid) new_mems.append(new_mem) h = self.odrop(h) if return_loss: if not lm_loss: loss = -(self.splitloss(h.view(-1, self.embed_size), input[1:].to(self.device).view(-1)).output * loss_mask).mean() else: loss = self.ate(h.view(-1, self.embed_size), input[1:].to(self.device).view(-1)).loss return loss, h, new_hidden, new_mems else: output = self.splitloss.log_prob(h.view(-1, self.embed_size)) output = output.view(*x.shape, -1) return output, h, new_hidden, new_mems def conditional_generate(self, input, attention_mask, type_ids, eos_id=2, max_length=64, use_sampling=False, top_p=0.95, temperature=1.0): prompt = torch.cat([input, torch.zeros(1, input.shape[1], dtype=torch.long)]) attention_mask = torch.cat([attention_mask, torch.ones(1, attention_mask.shape[1])]) type_ids = torch.cat([type_ids, torch.zeros(1, type_ids.shape[1])]) self.eval() sequences = torch.zeros(max_length, input.shape[1], dtype=torch.long) hidden, mems = None, None with torch.no_grad(): output, h, hidden, mems = self(prompt[:-1], attention_mask=attention_mask[:-1], type_ids=type_ids[:-1], hidden=hidden, mems=mems) prompt = prompt[-2:] attention_mask=attention_mask[-2:] type_ids=type_ids[-2:] for i in range(max_length): output, h, hidden, mems = self(prompt, attention_mask=attention_mask, type_ids=type_ids, hidden=hidden, mems=mems) if use_sampling: raise NotImplementedError token_weights = top_k_top_p_filtering(torch.exp(output.view(-1)) / temperature, top_p=top_p, filter_value=0.0) output_idx = torch.multinomial(token_weights, num_samples=1)[0] else: output_idx = torch.argmax(output, dim=-1) prompt[0, :] = output_idx sequences[i, :] = output_idx if torch.all(output_idx == eos_id): break return sequences if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument("--model", type=str, default="bin/base/model") parser.add_argument("--tokenizer", type=str, default="tokenizer/tokenizer.json") parser.add_argument("--device", type=str, default="cuda") args = parser.parse_args() model = SHALSTMforQuestionAnswering.from_pretrained(args.model, device=torch.device(args.device)) from tokenizer import SHALSTMTokenizer tokenizer = SHALSTMTokenizer.from_file(args.tokenizer) questions = [ "another thing there", "some length here", ] answers = [ "brother Hi how", "this answer for question one", ] input, attn_mask, type_ids, input_length = tokenizer.encode_for_qa(questions, answers) loss, h, hidden, mems = model(input, attn_mask, type_ids, return_loss=True) warmup = 5 total_steps = 1500 optimizer = torch.optim.SGD(model.parameters(), lr=1e-2) scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=[lambda x: float(x / warmup) if x < warmup else float((total_steps - x) / total_steps)]) use_amp = False scaler = torch.cuda.amp.GradScaler(enabled=use_amp) import time starttime = time.time() model.train() for i in range(total_steps): with torch.cuda.amp.autocast(enabled=use_amp): loss, h, hidden, mems = model(input, attn_mask, type_ids, return_loss=True) scaler.scale(loss).backward() scaler.unscale_(optimizer) torch.nn.utils.clip_grad_norm_(model.parameters(), 0.1) scaler.step(optimizer) scaler.update() scheduler.step() if i % (total_steps // 10) == 0: print(loss.item()) print("Excecution time =", (time.time() - starttime) / total_steps, "sec per batch") questions = [ "question one ?", "some length here", ] answers = [ "this answer to this one", "This is another answer for another question ", ] input, attn_mask, type_ids, input_length = tokenizer.encode_for_qa(questions, answers) with torch.no_grad(): model.eval() output, h, hidden, mems = model(input, attn_mask, type_ids) output = torch.argmax(output, dim=-1) ids = output[input_length - 1:].t().cpu().tolist() ids = output.t().cpu().tolist() print(tokenizer.decode(ids[0])) print(tokenizer.decode(ids[1])) input, attn_mask, type_ids, input_length = tokenizer.encode_for_qa(questions, direction='left') sequence = model.conditional_generate(input, attn_mask, type_ids, max_length=10, use_sampling=False) print("Conditional generation") print(tokenizer.decode_batch(sequence.t().cpu().tolist()))
true
true
f72a4f4af0ffe7527231500fcb530dd4fab8692b
14,981
py
Python
patrole_tempest_plugin/tests/unit/test_rbac_utils.py
openstack/patrole
fa0ee135121a5e86301ad5ee1854b3a0bd70b69b
[ "Apache-2.0" ]
14
2017-01-03T15:07:18.000Z
2020-09-17T18:07:39.000Z
patrole_tempest_plugin/tests/unit/test_rbac_utils.py
openstack/patrole
fa0ee135121a5e86301ad5ee1854b3a0bd70b69b
[ "Apache-2.0" ]
null
null
null
patrole_tempest_plugin/tests/unit/test_rbac_utils.py
openstack/patrole
fa0ee135121a5e86301ad5ee1854b3a0bd70b69b
[ "Apache-2.0" ]
12
2017-02-28T20:08:48.000Z
2020-12-30T09:31:51.000Z
# Copyright 2017 AT&T Corporation. # 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. import testtools from unittest import mock from tempest.lib import exceptions as lib_exc from patrole_tempest_plugin import rbac_exceptions from patrole_tempest_plugin import rbac_utils from patrole_tempest_plugin.tests.unit import base from patrole_tempest_plugin.tests.unit import fixtures as patrole_fixtures class RBACUtilsMixinTest(base.TestCase): def setUp(self): super(RBACUtilsMixinTest, self).setUp() self.rbac_utils_fixture = self.useFixture( patrole_fixtures.RbacUtilsMixinFixture()) self.test_obj = self.rbac_utils_fixture.test_obj def test_init_roles_with_missing_admin_role(self): self.rbac_utils_fixture.set_roles('member') error_re = (".*Following roles were not found: admin. Available " "roles: member.") self.assertRaisesRegex(rbac_exceptions.RbacResourceSetupFailed, error_re, self.test_obj._init_roles) def test_init_roles_with_missing_rbac_role(self): self.rbac_utils_fixture.set_roles('admin') error_re = (".*Following roles were not found: member. Available " "roles: admin.") self.assertRaisesRegex(rbac_exceptions.RbacResourceSetupFailed, error_re, self.test_obj._init_roles) def test_override_role_to_admin_role_at_creating(self): rbac_utils_fixture = self.useFixture( patrole_fixtures.RbacUtilsMixinFixture(do_reset_mocks=False)) test_obj = rbac_utils_fixture.test_obj roles_client = rbac_utils_fixture.admin_roles_client mock_time = rbac_utils_fixture.mock_time roles_client.create_user_role_on_project.assert_called_once_with( rbac_utils_fixture.PROJECT_ID, rbac_utils_fixture.USER_ID, 'admin_id') test_obj.get_auth_providers()[0].clear_auth.assert_called_once_with() test_obj.get_auth_providers()[0].set_auth.assert_called_once_with() mock_time.sleep.assert_called_once_with(1) def test_override_role_to_admin_role(self): self.test_obj._override_role() roles_client = self.rbac_utils_fixture.admin_roles_client mock_time = self.rbac_utils_fixture.mock_time roles_client.create_user_role_on_project.assert_called_once_with( self.rbac_utils_fixture.PROJECT_ID, self.rbac_utils_fixture.USER_ID, 'admin_id') self.test_obj.get_auth_providers()[0].clear_auth\ .assert_called_once_with() self.test_obj.get_auth_providers()[0].set_auth\ .assert_called_once_with() mock_time.sleep.assert_called_once_with(1) def test_override_role_to_admin_role_avoids_role_switch(self): self.rbac_utils_fixture.set_roles(['admin', 'member'], 'admin') self.test_obj._override_role() roles_client = self.rbac_utils_fixture.admin_roles_client mock_time = self.rbac_utils_fixture.mock_time roles_client.create_user_role_on_project.assert_not_called() mock_time.sleep.assert_not_called() def test_override_role_to_member_role(self): self.test_obj._override_role(True) roles_client = self.rbac_utils_fixture.admin_roles_client mock_time = self.rbac_utils_fixture.mock_time roles_client.create_user_role_on_project.assert_has_calls([ mock.call(self.rbac_utils_fixture.PROJECT_ID, self.rbac_utils_fixture.USER_ID, 'member_id') ]) self.test_obj.get_auth_providers()[0].clear_auth.assert_has_calls( [mock.call()]) self.test_obj.get_auth_providers()[0].set_auth.assert_has_calls( [mock.call()]) mock_time.sleep.assert_has_calls([mock.call(1)]) def test_override_role_to_member_role_avoids_role_switch(self): self.rbac_utils_fixture.set_roles(['admin', 'member'], 'member') self.test_obj._override_role(True) roles_client = self.rbac_utils_fixture.admin_roles_client mock_time = self.rbac_utils_fixture.mock_time self.assertEqual(0, roles_client.create_user_role_on_project.call_count) self.assertEqual(0, mock_time.sleep.call_count) def test_override_role_to_member_role_then_admin_role(self): self.test_obj._override_role(True) self.test_obj._override_role(False) roles_client = self.rbac_utils_fixture.admin_roles_client mock_time = self.rbac_utils_fixture.mock_time roles_client.create_user_role_on_project.assert_has_calls([ mock.call(self.rbac_utils_fixture.PROJECT_ID, self.rbac_utils_fixture.USER_ID, 'member_id'), mock.call(self.rbac_utils_fixture.PROJECT_ID, self.rbac_utils_fixture.USER_ID, 'admin_id') ]) self.test_obj.get_auth_providers()[0].clear_auth.assert_has_calls( [mock.call()] * 2) self.test_obj.get_auth_providers()[0].set_auth.assert_has_calls( [mock.call()] * 2) mock_time.sleep.assert_has_calls([mock.call(1)] * 2) def test_clear_user_roles(self): # NOTE(felipemonteiro): Set the user's roles on the project to # include 'random' to coerce a role switch, or else it will be # skipped. self.rbac_utils_fixture.set_roles(['admin', 'member'], ['member', 'random']) self.test_obj._override_role() roles_client = self.rbac_utils_fixture.admin_roles_client roles_client.list_user_roles_on_project.assert_called_once_with( self.rbac_utils_fixture.PROJECT_ID, self.rbac_utils_fixture.USER_ID) roles_client.delete_role_from_user_on_project.\ assert_has_calls([ mock.call(mock.sentinel.project_id, mock.sentinel.user_id, 'member_id'), mock.call(mock.sentinel.project_id, mock.sentinel.user_id, 'random_id')]) def test_override_role_context_manager_simulate_pass(self): """Validate that expected override_role calls are made when switching to admin role for success path. """ mock_override_role = self.patchobject(self.test_obj, '_override_role') with self.test_obj.override_role(): # Validate `override_role` public method called private method # `_override_role` with True. mock_override_role.assert_called_once_with(True) mock_override_role.reset_mock() # Validate that `override_role` switched back to admin role after # contextmanager. mock_override_role.assert_called_once_with(False) def test_override_role_context_manager_simulate_fail(self): """Validate that expected override_role calls are made when switching to admin role for failure path (i.e. when test raises exception). """ mock_override_role = self.patchobject(self.test_obj, '_override_role') def _do_test(): with self.test_obj.override_role(): # Validate `override_role` public method called private method # `_override_role` with True. mock_override_role.assert_called_once_with(True) mock_override_role.reset_mock() # Raise exc to verify role switch works for negative case. raise lib_exc.Forbidden() # Validate that role is switched back to admin, despite test failure. with testtools.ExpectedException(lib_exc.Forbidden): _do_test() mock_override_role.assert_called_once_with(False) def test_override_role_and_validate_list(self): m_override_role = self.patchobject(self.test_obj, 'override_role') with (self.test_obj.override_role_and_validate_list( admin_resource_id='foo')) as ctx: self.assertIsInstance(ctx, rbac_utils._ValidateListContext) m_validate = self.patchobject(ctx, '_validate') m_override_role.assert_called_once_with() m_validate.assert_called_once() def test_prepare_role_inferences_mapping(self): self.test_obj.admin_roles_client.list_all_role_inference_rules.\ return_value = { "role_inferences": [ { "implies": [{"id": "reader_id", "name": "reader"}], "prior_role": {"id": "member_id", "name": "member"} }, { "implies": [{"id": "member_id", "name": "member"}], "prior_role": {"id": "admin_id", "name": "admin"} } ] } expected_role_inferences_mapping = { "member_id": {"reader_id"}, "admin_id": {"member_id", "reader_id"} } actual_role_inferences_mapping = self.test_obj.\ _prepare_role_inferences_mapping() self.assertEqual(expected_role_inferences_mapping, actual_role_inferences_mapping) def test_get_all_needed_roles(self): self.test_obj.__class__._role_inferences_mapping = { "member_id": {"reader_id"}, "admin_id": {"member_id", "reader_id"} } self.test_obj.__class__._role_map = { "admin_id": "admin", "admin": "admin_id", "member_id": "member", "member": "member_id", "reader_id": "reader", "reader": "reader_id" } for roles, expected_roles in ( (['admin'], ['admin', 'member', 'reader']), (['member'], ['member', 'reader']), (['reader'], ['reader']), (['custom_role'], ['custom_role']), (['custom_role', 'member'], ['custom_role', 'member', 'reader']), (['admin', 'member'], ['admin', 'member', 'reader']), ): expected_roles = sorted(expected_roles) actual_roles = sorted(self.test_obj.get_all_needed_roles(roles)) self.assertEqual(expected_roles, actual_roles) def test_restore_roles(self): self.rbac_utils_fixture.set_roles(['admin', 'member'], 'member') roles_client = self.rbac_utils_fixture.admin_roles_client # Explicitly call setup_clients() to make sure cls._orig_roles is set # properly. Explicitly call resource_cleanup to invoke restore_roles(). self.test_obj.setup_clients() self.test_obj.resource_cleanup() # list_user_roles_on_project is called twice in setup_clients(), # restore_roles() is called twice during resource cleanup. self.assertEqual(4, roles_client.list_user_roles_on_project.call_count) self.assertEqual(['member_id'], self.test_obj._orig_roles) class ValidateListContextTest(base.TestCase): @staticmethod def _get_context(admin_resources=None, admin_resource_id=None): return rbac_utils._ValidateListContext( admin_resources=admin_resources, admin_resource_id=admin_resource_id) def test_incorrect_usage(self): # admin_resources and admin_resource_is are not assigned self.assertRaises(rbac_exceptions.RbacValidateListException, self._get_context) # both admin_resources and admin_resource_is are assigned self.assertRaises(rbac_exceptions.RbacValidateListException, self._get_context, admin_resources='foo', admin_resource_id='bar') # empty list assigned to admin_resources self.assertRaises(rbac_exceptions.RbacValidateListException, self._get_context, admin_resources=[]) # ctx.resources is not assigned ctx = self._get_context(admin_resources='foo') self.assertRaises(rbac_exceptions.RbacValidateListException, ctx._validate) def test_validate_len_negative(self): ctx = self._get_context(admin_resources=[1, 2, 3, 4]) self.assertEqual(ctx._validate_len, ctx._validate_func) self.assertEqual(4, ctx._admin_len) self.assertFalse(hasattr(ctx, '_admin_resource_id')) # the number of resources is less than admin resources ctx.resources = [1, 2, 3] self.assertRaises(rbac_exceptions.RbacPartialResponseBody, ctx._validate_len) # the resources is empty ctx.resources = [] self.assertRaises(rbac_exceptions.RbacEmptyResponseBody, ctx._validate_len) def test_validate_len(self): ctx = self._get_context(admin_resources=[1, 2, 3, 4]) # the number of resources and admin resources are same ctx.resources = [1, 2, 3, 4] self.assertIsNone(ctx._validate_len()) def test_validate_resource_negative(self): ctx = self._get_context(admin_resource_id=1) self.assertEqual(ctx._validate_resource, ctx._validate_func) self.assertEqual(1, ctx._admin_resource_id) self.assertFalse(hasattr(ctx, '_admin_len')) # there is no admin resource in the resources ctx.resources = [{'id': 2}, {'id': 3}] self.assertRaises(rbac_exceptions.RbacPartialResponseBody, ctx._validate_resource) def test_validate_resource(self): ctx = self._get_context(admin_resource_id=1) # there is admin resource in the resources ctx.resources = [{'id': 1}, {'id': 2}] self.assertIsNone(ctx._validate_resource()) def test_validate(self): ctx = self._get_context(admin_resources='foo') ctx.resources = 'bar' with mock.patch.object(ctx, '_validate_func', autospec=False) as m_validate_func: m_validate_func.side_effect = ( rbac_exceptions.RbacPartialResponseBody, None ) self.assertRaises(rbac_exceptions.RbacPartialResponseBody, ctx._validate) m_validate_func.assert_called_once() m_validate_func.reset_mock() ctx._validate() m_validate_func.assert_called_once()
43.048851
79
0.653227
import testtools from unittest import mock from tempest.lib import exceptions as lib_exc from patrole_tempest_plugin import rbac_exceptions from patrole_tempest_plugin import rbac_utils from patrole_tempest_plugin.tests.unit import base from patrole_tempest_plugin.tests.unit import fixtures as patrole_fixtures class RBACUtilsMixinTest(base.TestCase): def setUp(self): super(RBACUtilsMixinTest, self).setUp() self.rbac_utils_fixture = self.useFixture( patrole_fixtures.RbacUtilsMixinFixture()) self.test_obj = self.rbac_utils_fixture.test_obj def test_init_roles_with_missing_admin_role(self): self.rbac_utils_fixture.set_roles('member') error_re = (".*Following roles were not found: admin. Available " "roles: member.") self.assertRaisesRegex(rbac_exceptions.RbacResourceSetupFailed, error_re, self.test_obj._init_roles) def test_init_roles_with_missing_rbac_role(self): self.rbac_utils_fixture.set_roles('admin') error_re = (".*Following roles were not found: member. Available " "roles: admin.") self.assertRaisesRegex(rbac_exceptions.RbacResourceSetupFailed, error_re, self.test_obj._init_roles) def test_override_role_to_admin_role_at_creating(self): rbac_utils_fixture = self.useFixture( patrole_fixtures.RbacUtilsMixinFixture(do_reset_mocks=False)) test_obj = rbac_utils_fixture.test_obj roles_client = rbac_utils_fixture.admin_roles_client mock_time = rbac_utils_fixture.mock_time roles_client.create_user_role_on_project.assert_called_once_with( rbac_utils_fixture.PROJECT_ID, rbac_utils_fixture.USER_ID, 'admin_id') test_obj.get_auth_providers()[0].clear_auth.assert_called_once_with() test_obj.get_auth_providers()[0].set_auth.assert_called_once_with() mock_time.sleep.assert_called_once_with(1) def test_override_role_to_admin_role(self): self.test_obj._override_role() roles_client = self.rbac_utils_fixture.admin_roles_client mock_time = self.rbac_utils_fixture.mock_time roles_client.create_user_role_on_project.assert_called_once_with( self.rbac_utils_fixture.PROJECT_ID, self.rbac_utils_fixture.USER_ID, 'admin_id') self.test_obj.get_auth_providers()[0].clear_auth\ .assert_called_once_with() self.test_obj.get_auth_providers()[0].set_auth\ .assert_called_once_with() mock_time.sleep.assert_called_once_with(1) def test_override_role_to_admin_role_avoids_role_switch(self): self.rbac_utils_fixture.set_roles(['admin', 'member'], 'admin') self.test_obj._override_role() roles_client = self.rbac_utils_fixture.admin_roles_client mock_time = self.rbac_utils_fixture.mock_time roles_client.create_user_role_on_project.assert_not_called() mock_time.sleep.assert_not_called() def test_override_role_to_member_role(self): self.test_obj._override_role(True) roles_client = self.rbac_utils_fixture.admin_roles_client mock_time = self.rbac_utils_fixture.mock_time roles_client.create_user_role_on_project.assert_has_calls([ mock.call(self.rbac_utils_fixture.PROJECT_ID, self.rbac_utils_fixture.USER_ID, 'member_id') ]) self.test_obj.get_auth_providers()[0].clear_auth.assert_has_calls( [mock.call()]) self.test_obj.get_auth_providers()[0].set_auth.assert_has_calls( [mock.call()]) mock_time.sleep.assert_has_calls([mock.call(1)]) def test_override_role_to_member_role_avoids_role_switch(self): self.rbac_utils_fixture.set_roles(['admin', 'member'], 'member') self.test_obj._override_role(True) roles_client = self.rbac_utils_fixture.admin_roles_client mock_time = self.rbac_utils_fixture.mock_time self.assertEqual(0, roles_client.create_user_role_on_project.call_count) self.assertEqual(0, mock_time.sleep.call_count) def test_override_role_to_member_role_then_admin_role(self): self.test_obj._override_role(True) self.test_obj._override_role(False) roles_client = self.rbac_utils_fixture.admin_roles_client mock_time = self.rbac_utils_fixture.mock_time roles_client.create_user_role_on_project.assert_has_calls([ mock.call(self.rbac_utils_fixture.PROJECT_ID, self.rbac_utils_fixture.USER_ID, 'member_id'), mock.call(self.rbac_utils_fixture.PROJECT_ID, self.rbac_utils_fixture.USER_ID, 'admin_id') ]) self.test_obj.get_auth_providers()[0].clear_auth.assert_has_calls( [mock.call()] * 2) self.test_obj.get_auth_providers()[0].set_auth.assert_has_calls( [mock.call()] * 2) mock_time.sleep.assert_has_calls([mock.call(1)] * 2) def test_clear_user_roles(self): # include 'random' to coerce a role switch, or else it will be # skipped. self.rbac_utils_fixture.set_roles(['admin', 'member'], ['member', 'random']) self.test_obj._override_role() roles_client = self.rbac_utils_fixture.admin_roles_client roles_client.list_user_roles_on_project.assert_called_once_with( self.rbac_utils_fixture.PROJECT_ID, self.rbac_utils_fixture.USER_ID) roles_client.delete_role_from_user_on_project.\ assert_has_calls([ mock.call(mock.sentinel.project_id, mock.sentinel.user_id, 'member_id'), mock.call(mock.sentinel.project_id, mock.sentinel.user_id, 'random_id')]) def test_override_role_context_manager_simulate_pass(self): mock_override_role = self.patchobject(self.test_obj, '_override_role') with self.test_obj.override_role(): # Validate `override_role` public method called private method # `_override_role` with True. mock_override_role.assert_called_once_with(True) mock_override_role.reset_mock() # Validate that `override_role` switched back to admin role after # contextmanager. mock_override_role.assert_called_once_with(False) def test_override_role_context_manager_simulate_fail(self): mock_override_role = self.patchobject(self.test_obj, '_override_role') def _do_test(): with self.test_obj.override_role(): # Validate `override_role` public method called private method # `_override_role` with True. mock_override_role.assert_called_once_with(True) mock_override_role.reset_mock() # Raise exc to verify role switch works for negative case. raise lib_exc.Forbidden() # Validate that role is switched back to admin, despite test failure. with testtools.ExpectedException(lib_exc.Forbidden): _do_test() mock_override_role.assert_called_once_with(False) def test_override_role_and_validate_list(self): m_override_role = self.patchobject(self.test_obj, 'override_role') with (self.test_obj.override_role_and_validate_list( admin_resource_id='foo')) as ctx: self.assertIsInstance(ctx, rbac_utils._ValidateListContext) m_validate = self.patchobject(ctx, '_validate') m_override_role.assert_called_once_with() m_validate.assert_called_once() def test_prepare_role_inferences_mapping(self): self.test_obj.admin_roles_client.list_all_role_inference_rules.\ return_value = { "role_inferences": [ { "implies": [{"id": "reader_id", "name": "reader"}], "prior_role": {"id": "member_id", "name": "member"} }, { "implies": [{"id": "member_id", "name": "member"}], "prior_role": {"id": "admin_id", "name": "admin"} } ] } expected_role_inferences_mapping = { "member_id": {"reader_id"}, "admin_id": {"member_id", "reader_id"} } actual_role_inferences_mapping = self.test_obj.\ _prepare_role_inferences_mapping() self.assertEqual(expected_role_inferences_mapping, actual_role_inferences_mapping) def test_get_all_needed_roles(self): self.test_obj.__class__._role_inferences_mapping = { "member_id": {"reader_id"}, "admin_id": {"member_id", "reader_id"} } self.test_obj.__class__._role_map = { "admin_id": "admin", "admin": "admin_id", "member_id": "member", "member": "member_id", "reader_id": "reader", "reader": "reader_id" } for roles, expected_roles in ( (['admin'], ['admin', 'member', 'reader']), (['member'], ['member', 'reader']), (['reader'], ['reader']), (['custom_role'], ['custom_role']), (['custom_role', 'member'], ['custom_role', 'member', 'reader']), (['admin', 'member'], ['admin', 'member', 'reader']), ): expected_roles = sorted(expected_roles) actual_roles = sorted(self.test_obj.get_all_needed_roles(roles)) self.assertEqual(expected_roles, actual_roles) def test_restore_roles(self): self.rbac_utils_fixture.set_roles(['admin', 'member'], 'member') roles_client = self.rbac_utils_fixture.admin_roles_client # Explicitly call setup_clients() to make sure cls._orig_roles is set # properly. Explicitly call resource_cleanup to invoke restore_roles(). self.test_obj.setup_clients() self.test_obj.resource_cleanup() # list_user_roles_on_project is called twice in setup_clients(), # restore_roles() is called twice during resource cleanup. self.assertEqual(4, roles_client.list_user_roles_on_project.call_count) self.assertEqual(['member_id'], self.test_obj._orig_roles) class ValidateListContextTest(base.TestCase): @staticmethod def _get_context(admin_resources=None, admin_resource_id=None): return rbac_utils._ValidateListContext( admin_resources=admin_resources, admin_resource_id=admin_resource_id) def test_incorrect_usage(self): # admin_resources and admin_resource_is are not assigned self.assertRaises(rbac_exceptions.RbacValidateListException, self._get_context) # both admin_resources and admin_resource_is are assigned self.assertRaises(rbac_exceptions.RbacValidateListException, self._get_context, admin_resources='foo', admin_resource_id='bar') # empty list assigned to admin_resources self.assertRaises(rbac_exceptions.RbacValidateListException, self._get_context, admin_resources=[]) # ctx.resources is not assigned ctx = self._get_context(admin_resources='foo') self.assertRaises(rbac_exceptions.RbacValidateListException, ctx._validate) def test_validate_len_negative(self): ctx = self._get_context(admin_resources=[1, 2, 3, 4]) self.assertEqual(ctx._validate_len, ctx._validate_func) self.assertEqual(4, ctx._admin_len) self.assertFalse(hasattr(ctx, '_admin_resource_id')) # the number of resources is less than admin resources ctx.resources = [1, 2, 3] self.assertRaises(rbac_exceptions.RbacPartialResponseBody, ctx._validate_len) # the resources is empty ctx.resources = [] self.assertRaises(rbac_exceptions.RbacEmptyResponseBody, ctx._validate_len) def test_validate_len(self): ctx = self._get_context(admin_resources=[1, 2, 3, 4]) # the number of resources and admin resources are same ctx.resources = [1, 2, 3, 4] self.assertIsNone(ctx._validate_len()) def test_validate_resource_negative(self): ctx = self._get_context(admin_resource_id=1) self.assertEqual(ctx._validate_resource, ctx._validate_func) self.assertEqual(1, ctx._admin_resource_id) self.assertFalse(hasattr(ctx, '_admin_len')) # there is no admin resource in the resources ctx.resources = [{'id': 2}, {'id': 3}] self.assertRaises(rbac_exceptions.RbacPartialResponseBody, ctx._validate_resource) def test_validate_resource(self): ctx = self._get_context(admin_resource_id=1) # there is admin resource in the resources ctx.resources = [{'id': 1}, {'id': 2}] self.assertIsNone(ctx._validate_resource()) def test_validate(self): ctx = self._get_context(admin_resources='foo') ctx.resources = 'bar' with mock.patch.object(ctx, '_validate_func', autospec=False) as m_validate_func: m_validate_func.side_effect = ( rbac_exceptions.RbacPartialResponseBody, None ) self.assertRaises(rbac_exceptions.RbacPartialResponseBody, ctx._validate) m_validate_func.assert_called_once() m_validate_func.reset_mock() ctx._validate() m_validate_func.assert_called_once()
true
true
f72a4f6721d4ff9bda92ac47662c4d9dcaa83260
2,333
py
Python
var/spack/repos/builtin/packages/r-gsodr/package.py
kkauder/spack
6ae8d5c380c1f42094b05d38be26b03650aafb39
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
2,360
2017-11-06T08:47:01.000Z
2022-03-31T14:45:33.000Z
var/spack/repos/builtin/packages/r-gsodr/package.py
kkauder/spack
6ae8d5c380c1f42094b05d38be26b03650aafb39
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
13,838
2017-11-04T07:49:45.000Z
2022-03-31T23:38:39.000Z
var/spack/repos/builtin/packages/r-gsodr/package.py
kkauder/spack
6ae8d5c380c1f42094b05d38be26b03650aafb39
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
1,793
2017-11-04T07:45:50.000Z
2022-03-30T14:31:53.000Z
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RGsodr(RPackage): """A Global Surface Summary of the Day (GSOD) Weather Data Client for R Provides automated downloading, parsing, cleaning, unit conversion and formatting of Global Surface Summary of the Day ('GSOD') weather data from the from the USA National Centers for Environmental Information ('NCEI'). Units are converted from from United States Customary System ('USCS') units to International System of Units ('SI'). Stations may be individually checked for number of missing days defined by the user, where stations with too many missing observations are omitted. Only stations with valid reported latitude and longitude values are permitted in the final data. Additional useful elements, saturation vapour pressure ('es'), actual vapour pressure ('ea') and relative humidity ('RH') are calculated from the original data using the improved August-Roche-Magnus approximation (Alduchov & Eskridge 1996) and included in the final data set. The resulting metadata include station identification information, country, state, latitude, longitude, elevation, weather observations and associated flags. For information on the 'GSOD' data from 'NCEI', please see the 'GSOD' 'readme.txt' file available from, <https://www1.ncdc.noaa.gov/pub/data/gsod/readme.txt>.""" homepage = "https://docs.ropensci.org/GSODR/" url = "https://cloud.r-project.org/src/contrib/GSODR_2.1.1.tar.gz" list_url = "https://cloud.r-project.org/src/contrib/Archive/GSODR" version('2.1.2', sha256='4fc1d084b6c21055d8cc17a6a6dc412261aa0d4ef4079bcd73b580a8c16bf74e') version('2.1.1', sha256='dba732e5bd1e367b9d710e6b8924f0c02fa4546202f049124dba02bc2e3329f5') depends_on('r@3.5.0:', type=('build', 'run')) depends_on('r-countrycode', type=('build', 'run')) depends_on('r-curl', type=('build', 'run')) depends_on('r-data-table@1.11.6:', type=('build', 'run')) depends_on('r-future-apply', type=('build', 'run')) depends_on('r-httr', type=('build', 'run')) depends_on('r-r-utils', type=('build', 'run'))
53.022727
95
0.724389
from spack import * class RGsodr(RPackage): homepage = "https://docs.ropensci.org/GSODR/" url = "https://cloud.r-project.org/src/contrib/GSODR_2.1.1.tar.gz" list_url = "https://cloud.r-project.org/src/contrib/Archive/GSODR" version('2.1.2', sha256='4fc1d084b6c21055d8cc17a6a6dc412261aa0d4ef4079bcd73b580a8c16bf74e') version('2.1.1', sha256='dba732e5bd1e367b9d710e6b8924f0c02fa4546202f049124dba02bc2e3329f5') depends_on('r@3.5.0:', type=('build', 'run')) depends_on('r-countrycode', type=('build', 'run')) depends_on('r-curl', type=('build', 'run')) depends_on('r-data-table@1.11.6:', type=('build', 'run')) depends_on('r-future-apply', type=('build', 'run')) depends_on('r-httr', type=('build', 'run')) depends_on('r-r-utils', type=('build', 'run'))
true
true
f72a51b526015df516689e7669b54b9e20831540
639
py
Python
tests/clims/api/serializers/models/test_work_batch.py
withrocks/commonlims
d8a925c917aa26e8205fefb3966a9f49f8f2e2f8
[ "BSD-3-Clause" ]
null
null
null
tests/clims/api/serializers/models/test_work_batch.py
withrocks/commonlims
d8a925c917aa26e8205fefb3966a9f49f8f2e2f8
[ "BSD-3-Clause" ]
null
null
null
tests/clims/api/serializers/models/test_work_batch.py
withrocks/commonlims
d8a925c917aa26e8205fefb3966a9f49f8f2e2f8
[ "BSD-3-Clause" ]
null
null
null
from __future__ import absolute_import from sentry.testutils import TestCase from clims.api.serializers.models.workbatch import WorkBatchSerializer from clims.models.work_batch import WorkBatch class WorkBatchSerializerTest(TestCase): def test_can_serialize_task(self): model = WorkBatch(id=1, name="Test1", organization_id=1, handler="somehandler") result = WorkBatchSerializer(model).data assert result.get('handler') == 'somehandler' assert result.get('id') == 1 assert result.get('name') == 'Test1' assert result.get('organization') == 1 assert result.get('status') == 0
35.5
87
0.713615
from __future__ import absolute_import from sentry.testutils import TestCase from clims.api.serializers.models.workbatch import WorkBatchSerializer from clims.models.work_batch import WorkBatch class WorkBatchSerializerTest(TestCase): def test_can_serialize_task(self): model = WorkBatch(id=1, name="Test1", organization_id=1, handler="somehandler") result = WorkBatchSerializer(model).data assert result.get('handler') == 'somehandler' assert result.get('id') == 1 assert result.get('name') == 'Test1' assert result.get('organization') == 1 assert result.get('status') == 0
true
true
f72a51ff116cdacd733759b6eb96d4b97659306d
609
py
Python
djasana/migrations/0008_auto_20180906_1407.py
zaptim/django-asana
ab6d7166f28945292d5632ef766fc13cc2ea4cf3
[ "MIT" ]
null
null
null
djasana/migrations/0008_auto_20180906_1407.py
zaptim/django-asana
ab6d7166f28945292d5632ef766fc13cc2ea4cf3
[ "MIT" ]
null
null
null
djasana/migrations/0008_auto_20180906_1407.py
zaptim/django-asana
ab6d7166f28945292d5632ef766fc13cc2ea4cf3
[ "MIT" ]
null
null
null
# Generated by Django 2.1 on 2018-09-06 14:07 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('djasana', '0007_auto_20180819_1518'), ] operations = [ migrations.AlterField( model_name='customfield', name='description', field=models.CharField(blank=True, max_length=2048, null=True), ), migrations.AlterField( model_name='customfield', name='enum_options', field=models.CharField(blank=True, max_length=2048, null=True), ), ]
24.36
75
0.602627
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('djasana', '0007_auto_20180819_1518'), ] operations = [ migrations.AlterField( model_name='customfield', name='description', field=models.CharField(blank=True, max_length=2048, null=True), ), migrations.AlterField( model_name='customfield', name='enum_options', field=models.CharField(blank=True, max_length=2048, null=True), ), ]
true
true
f72a5265e0f02fda5da08d5bce4bd2145df5c0eb
582
py
Python
examples/2021_12_31/py_files/plotters/Paraview/timeAverage.py
jagarciap/SCSI
0972548adf17a27b78ef2865a837bf20aadca3e9
[ "MIT" ]
null
null
null
examples/2021_12_31/py_files/plotters/Paraview/timeAverage.py
jagarciap/SCSI
0972548adf17a27b78ef2865a837bf20aadca3e9
[ "MIT" ]
null
null
null
examples/2021_12_31/py_files/plotters/Paraview/timeAverage.py
jagarciap/SCSI
0972548adf17a27b78ef2865a837bf20aadca3e9
[ "MIT" ]
1
2022-01-18T10:24:39.000Z
2022-01-18T10:24:39.000Z
from paraview.simple import * firststep = 50 #names = ['0_ts*', '0-0_ts*', '0-0-0_ts*'] names = ['0_ts*', '0-0_ts*'] for name in names: acs = FindSource(name) SetActiveSource(acs) laststep = int(acs.TimestepValues[-1]) extractTimeSteps = ExtractTimeSteps(Input=acs) extractTimeSteps.TimeStepIndices = [i for i in range(firststep, laststep+1)] temporalStatistics = TemporalStatistics(Input=extractTimeSteps) renderView1 = GetActiveViewOrCreate('RenderView') temporalStatisticsDisplay = Show(temporalStatistics, renderView1) renderView1.Update()
34.235294
80
0.725086
from paraview.simple import * firststep = 50 names = ['0_ts*', '0-0_ts*'] for name in names: acs = FindSource(name) SetActiveSource(acs) laststep = int(acs.TimestepValues[-1]) extractTimeSteps = ExtractTimeSteps(Input=acs) extractTimeSteps.TimeStepIndices = [i for i in range(firststep, laststep+1)] temporalStatistics = TemporalStatistics(Input=extractTimeSteps) renderView1 = GetActiveViewOrCreate('RenderView') temporalStatisticsDisplay = Show(temporalStatistics, renderView1) renderView1.Update()
true
true
f72a52a097ae8acfd4297be79489feb161d30056
6,350
py
Python
tools/cFS-GroundSystem/GroundSystem.py
ammarrm/cFS_MSTAR
f7d59eec4a445bb8572d01a580c043ec7a33df44
[ "Apache-2.0" ]
null
null
null
tools/cFS-GroundSystem/GroundSystem.py
ammarrm/cFS_MSTAR
f7d59eec4a445bb8572d01a580c043ec7a33df44
[ "Apache-2.0" ]
null
null
null
tools/cFS-GroundSystem/GroundSystem.py
ammarrm/cFS_MSTAR
f7d59eec4a445bb8572d01a580c043ec7a33df44
[ "Apache-2.0" ]
1
2021-04-23T04:26:08.000Z
2021-04-23T04:26:08.000Z
# # GSC-18128-1, "Core Flight Executive Version 6.7" # # Copyright (c) 2006-2019 United States Government as represented by # the Administrator of the National Aeronautics and Space Administration. # 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. # # cFS Ground System Version 2.0.0 # #!/usr/bin/env python3 # import shlex import subprocess import sys from pathlib import Path from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox from RoutingService import RoutingService from Ui_MainWindow import Ui_MainWindow from _version import __version__ as _version from _version import _version_string __version__ = _version ROOTDIR = Path(sys.argv[0]).resolve().parent # # CFS Ground System: Setup and manage the main window # class GroundSystem(QMainWindow, Ui_MainWindow): HDR_VER_1_OFFSET = 0 HDR_VER_2_OFFSET = 4 # # Init the class # def __init__(self): super().__init__() self.setupUi(self) self.RoutingService = None self.alert = QMessageBox() self.pushButtonStartTlm.clicked.connect(self.startTlmSystem) self.pushButtonStartCmd.clicked.connect(self.startCmdSystem) self.cbTlmHeaderVer.currentIndexChanged.connect(self.setTlmOffset) self.cbCmdHeaderVer.currentIndexChanged.connect(self.setCmdOffsets) for sb in (self.sbTlmOffset, self.sbCmdOffsetPri, self.sbCmdOffsetSec): sb.valueChanged.connect(self.saveOffsets) # Init lists self.ipAddressesList = ['All'] self.spacecraftNames = ['All'] def closeEvent(self, evnt): if self.RoutingService: self.RoutingService.stop() print("Stopped routing service") super().closeEvent(evnt) # Read the selected spacecraft from combo box on GUI def getSelectedSpacecraftAddress(self): return self.comboBoxIpAddresses.currentText().strip() # Returns the name of the selected spacecraft def getSelectedSpacecraftName(self): return self.spacecraftNames[self.ipAddressesList.index( self.getSelectedSpacecraftAddress())].strip() # # Display popup with error # def DisplayErrorMessage(self, message): print(message) self.alert.setText(message) self.alert.setIcon(QMessageBox.Warning) self.alert.exec_() # Start the telemetry system for the selected spacecraft def startTlmSystem(self): # Setup the subscription (to let the telemetry # system know the messages it will be receiving) subscription = '--sub=GroundSystem' selectedSpacecraft = self.getSelectedSpacecraftName() if selectedSpacecraft != 'All': subscription += f'.{selectedSpacecraft}.TelemetryPackets' # Open Telemetry System system_call = f'python3 {ROOTDIR}/Subsystems/tlmGUI/TelemetrySystem.py {subscription}' args = shlex.split(system_call) subprocess.Popen(args) # Start command system @staticmethod def startCmdSystem(): subprocess.Popen( ['python3', f'{ROOTDIR}/Subsystems/cmdGui/CommandSystem.py']) # Start FDL-FUL gui system def startFDLSystem(self): selectedSpacecraft = self.getSelectedSpacecraftName() if selectedSpacecraft == 'All': self.DisplayErrorMessage( 'Cannot open FDL manager.\nNo spacecraft selected.') else: subscription = f'--sub=GroundSystem.{selectedSpacecraft}' subprocess.Popen([ 'python3', f'{ROOTDIR}/Subsystems/fdlGui/FdlSystem.py', subscription ]) def setTlmOffset(self): selectedVer = self.cbTlmHeaderVer.currentText().strip() if selectedVer == "Custom": self.sbTlmOffset.setEnabled(True) else: self.sbTlmOffset.setEnabled(False) if selectedVer == "1": self.sbTlmOffset.setValue(self.HDR_VER_1_OFFSET) elif selectedVer == "2": self.sbTlmOffset.setValue(self.HDR_VER_2_OFFSET) def setCmdOffsets(self): selectedVer = self.cbCmdHeaderVer.currentText().strip() if selectedVer == "Custom": self.sbCmdOffsetPri.setEnabled(True) self.sbCmdOffsetSec.setEnabled(True) else: self.sbCmdOffsetPri.setEnabled(False) self.sbCmdOffsetSec.setEnabled(False) if selectedVer == "1": self.sbCmdOffsetPri.setValue(self.HDR_VER_1_OFFSET) elif selectedVer == "2": self.sbCmdOffsetPri.setValue(self.HDR_VER_2_OFFSET) self.sbCmdOffsetSec.setValue(self.HDR_VER_1_OFFSET) def saveOffsets(self): offsets = bytes((self.sbTlmOffset.value(), self.sbCmdOffsetPri.value(), self.sbCmdOffsetSec.value())) with open("/tmp/OffsetData", "wb") as f: f.write(offsets) # Update the combo box list in gui def updateIpList(self, ip, name): self.ipAddressesList.append(ip) self.spacecraftNames.append(name) self.comboBoxIpAddresses.addItem(ip) # Start the routing service (see RoutingService.py) def initRoutingService(self): self.RoutingService = RoutingService() self.RoutingService.signalUpdateIpList.connect(self.updateIpList) self.RoutingService.start() # # Main # if __name__ == "__main__": # Report Version Number upon startup print(_version_string) # Init app app = QApplication(sys.argv) # Init main window MainWindow = GroundSystem() # Show and put window on front MainWindow.show() MainWindow.raise_() # Start the Routing Service MainWindow.initRoutingService() MainWindow.saveOffsets() # Execute the app sys.exit(app.exec_())
32.397959
94
0.671811
import shlex import subprocess import sys from pathlib import Path from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox from RoutingService import RoutingService from Ui_MainWindow import Ui_MainWindow from _version import __version__ as _version from _version import _version_string __version__ = _version ROOTDIR = Path(sys.argv[0]).resolve().parent class GroundSystem(QMainWindow, Ui_MainWindow): HDR_VER_1_OFFSET = 0 HDR_VER_2_OFFSET = 4 def __init__(self): super().__init__() self.setupUi(self) self.RoutingService = None self.alert = QMessageBox() self.pushButtonStartTlm.clicked.connect(self.startTlmSystem) self.pushButtonStartCmd.clicked.connect(self.startCmdSystem) self.cbTlmHeaderVer.currentIndexChanged.connect(self.setTlmOffset) self.cbCmdHeaderVer.currentIndexChanged.connect(self.setCmdOffsets) for sb in (self.sbTlmOffset, self.sbCmdOffsetPri, self.sbCmdOffsetSec): sb.valueChanged.connect(self.saveOffsets) self.ipAddressesList = ['All'] self.spacecraftNames = ['All'] def closeEvent(self, evnt): if self.RoutingService: self.RoutingService.stop() print("Stopped routing service") super().closeEvent(evnt) def getSelectedSpacecraftAddress(self): return self.comboBoxIpAddresses.currentText().strip() def getSelectedSpacecraftName(self): return self.spacecraftNames[self.ipAddressesList.index( self.getSelectedSpacecraftAddress())].strip() def DisplayErrorMessage(self, message): print(message) self.alert.setText(message) self.alert.setIcon(QMessageBox.Warning) self.alert.exec_() def startTlmSystem(self): subscription = '--sub=GroundSystem' selectedSpacecraft = self.getSelectedSpacecraftName() if selectedSpacecraft != 'All': subscription += f'.{selectedSpacecraft}.TelemetryPackets' system_call = f'python3 {ROOTDIR}/Subsystems/tlmGUI/TelemetrySystem.py {subscription}' args = shlex.split(system_call) subprocess.Popen(args) @staticmethod def startCmdSystem(): subprocess.Popen( ['python3', f'{ROOTDIR}/Subsystems/cmdGui/CommandSystem.py']) def startFDLSystem(self): selectedSpacecraft = self.getSelectedSpacecraftName() if selectedSpacecraft == 'All': self.DisplayErrorMessage( 'Cannot open FDL manager.\nNo spacecraft selected.') else: subscription = f'--sub=GroundSystem.{selectedSpacecraft}' subprocess.Popen([ 'python3', f'{ROOTDIR}/Subsystems/fdlGui/FdlSystem.py', subscription ]) def setTlmOffset(self): selectedVer = self.cbTlmHeaderVer.currentText().strip() if selectedVer == "Custom": self.sbTlmOffset.setEnabled(True) else: self.sbTlmOffset.setEnabled(False) if selectedVer == "1": self.sbTlmOffset.setValue(self.HDR_VER_1_OFFSET) elif selectedVer == "2": self.sbTlmOffset.setValue(self.HDR_VER_2_OFFSET) def setCmdOffsets(self): selectedVer = self.cbCmdHeaderVer.currentText().strip() if selectedVer == "Custom": self.sbCmdOffsetPri.setEnabled(True) self.sbCmdOffsetSec.setEnabled(True) else: self.sbCmdOffsetPri.setEnabled(False) self.sbCmdOffsetSec.setEnabled(False) if selectedVer == "1": self.sbCmdOffsetPri.setValue(self.HDR_VER_1_OFFSET) elif selectedVer == "2": self.sbCmdOffsetPri.setValue(self.HDR_VER_2_OFFSET) self.sbCmdOffsetSec.setValue(self.HDR_VER_1_OFFSET) def saveOffsets(self): offsets = bytes((self.sbTlmOffset.value(), self.sbCmdOffsetPri.value(), self.sbCmdOffsetSec.value())) with open("/tmp/OffsetData", "wb") as f: f.write(offsets) def updateIpList(self, ip, name): self.ipAddressesList.append(ip) self.spacecraftNames.append(name) self.comboBoxIpAddresses.addItem(ip) def initRoutingService(self): self.RoutingService = RoutingService() self.RoutingService.signalUpdateIpList.connect(self.updateIpList) self.RoutingService.start() if __name__ == "__main__": print(_version_string) app = QApplication(sys.argv) MainWindow = GroundSystem() MainWindow.show() MainWindow.raise_() MainWindow.initRoutingService() MainWindow.saveOffsets() sys.exit(app.exec_())
true
true
f72a530516b9a3b382487caa11390d79ac8dedb8
1,185
py
Python
pyprof/alembic/versions/2021_03_12_15_41_50.py
kooichirooooo/pyprof
a2cce7ef335d02b0566a169b46f3cf976e7d9662
[ "MIT" ]
null
null
null
pyprof/alembic/versions/2021_03_12_15_41_50.py
kooichirooooo/pyprof
a2cce7ef335d02b0566a169b46f3cf976e7d9662
[ "MIT" ]
null
null
null
pyprof/alembic/versions/2021_03_12_15_41_50.py
kooichirooooo/pyprof
a2cce7ef335d02b0566a169b46f3cf976e7d9662
[ "MIT" ]
null
null
null
"""create frame and block table Revision ID: 1fc165a90d68 Revises: Create Date: 2021-03-12 15:41:50.150507 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = "1fc165a90d68" down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "frames", sa.Column("id", sa.Integer(), autoincrement=True, nullable=False), sa.Column("name", sa.String(length=32), nullable=True), sa.PrimaryKeyConstraint("id"), ) op.create_table( "blocks", sa.Column("id", sa.Integer(), autoincrement=True, nullable=False), sa.Column("frame_id", sa.Integer(), nullable=True), sa.Column("name", sa.String(length=32), nullable=True), sa.ForeignKeyConstraint( ["frame_id"], ["frames.id"], ), sa.PrimaryKeyConstraint("id"), ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table("blocks") op.drop_table("frames") # ### end Alembic commands ###
26.333333
74
0.625316
import sqlalchemy as sa from alembic import op revision = "1fc165a90d68" down_revision = None branch_labels = None depends_on = None def upgrade(): sa.PrimaryKeyConstraint("id"), ) op.create_table( "blocks", sa.Column("id", sa.Integer(), autoincrement=True, nullable=False), sa.Column("frame_id", sa.Integer(), nullable=True), sa.Column("name", sa.String(length=32), nullable=True), sa.ForeignKeyConstraint( ["frame_id"], ["frames.id"], ), sa.PrimaryKeyConstraint("id"), )
true
true
f72a5319acea927f969baaeedae8a60444d73815
168
py
Python
ftruck/urls.py
sunlightlabs/foodtrucks
f6531a3e47c3d5975d5230e946e636d082dbc24a
[ "BSD-3-Clause" ]
null
null
null
ftruck/urls.py
sunlightlabs/foodtrucks
f6531a3e47c3d5975d5230e946e636d082dbc24a
[ "BSD-3-Clause" ]
null
null
null
ftruck/urls.py
sunlightlabs/foodtrucks
f6531a3e47c3d5975d5230e946e636d082dbc24a
[ "BSD-3-Clause" ]
null
null
null
from django.conf.urls.defaults import * urlpatterns = patterns('ftruck.views', url(r'^$', 'mainmap', name='map'), url(r'^tweets/$', 'tweets', name='tweets') )
24
46
0.630952
from django.conf.urls.defaults import * urlpatterns = patterns('ftruck.views', url(r'^$', 'mainmap', name='map'), url(r'^tweets/$', 'tweets', name='tweets') )
true
true
f72a5350a454b362d7b0b72c74c7c361977c73b5
2,289
py
Python
data/cirq_new/cirq_program/startCirq_noisy553.py
UCLA-SEAL/QDiff
d968cbc47fe926b7f88b4adf10490f1edd6f8819
[ "BSD-3-Clause" ]
null
null
null
data/cirq_new/cirq_program/startCirq_noisy553.py
UCLA-SEAL/QDiff
d968cbc47fe926b7f88b4adf10490f1edd6f8819
[ "BSD-3-Clause" ]
null
null
null
data/cirq_new/cirq_program/startCirq_noisy553.py
UCLA-SEAL/QDiff
d968cbc47fe926b7f88b4adf10490f1edd6f8819
[ "BSD-3-Clause" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 5/15/20 4:49 PM # @File : grover.py # qubit number=4 # total number=19 import cirq import cirq.google as cg from typing import Optional import sys from math import log2 import numpy as np #thatsNoCode def make_circuit(n: int, input_qubit): c = cirq.Circuit() # circuit begin c.append(cirq.H.on(input_qubit[0])) # number=1 c.append(cirq.H.on(input_qubit[1])) # number=2 c.append(cirq.H.on(input_qubit[1])) # number=7 c.append(cirq.H.on(input_qubit[2])) # number=3 c.append(cirq.H.on(input_qubit[3])) # number=4 c.append(cirq.H.on(input_qubit[0])) # number=14 c.append(cirq.CZ.on(input_qubit[3],input_qubit[0])) # number=15 c.append(cirq.H.on(input_qubit[0])) # number=16 c.append(cirq.CNOT.on(input_qubit[3],input_qubit[0])) # number=6 c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=8 c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=9 c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=10 c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=11 c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=12 c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=13 c.append(cirq.X.on(input_qubit[1])) # number=17 c.append(cirq.X.on(input_qubit[1])) # number=18 # circuit end c.append(cirq.measure(*input_qubit, key='result')) return c def bitstring(bits): return ''.join(str(int(b)) for b in bits) if __name__ == '__main__': qubit_count = 4 input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)] circuit = make_circuit(qubit_count,input_qubits) circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap') circuit_sample_count =2820 circuit = circuit.with_noise(cirq.depolarize(p=0.01)) simulator = cirq.Simulator() result = simulator.run(circuit, repetitions=circuit_sample_count) frequencies = result.histogram(key='result', fold_func=bitstring) writefile = open("../data/startCirq_noisy553.csv","w+") print(format(frequencies),file=writefile) print("results end", file=writefile) print(circuit.__len__(), file=writefile) print(circuit,file=writefile) writefile.close()
33.173913
77
0.68851
import cirq import cirq.google as cg from typing import Optional import sys from math import log2 import numpy as np def make_circuit(n: int, input_qubit): c = cirq.Circuit() c.append(cirq.H.on(input_qubit[0])) c.append(cirq.H.on(input_qubit[1])) c.append(cirq.H.on(input_qubit[1])) c.append(cirq.H.on(input_qubit[2])) c.append(cirq.H.on(input_qubit[3])) c.append(cirq.H.on(input_qubit[0])) c.append(cirq.CZ.on(input_qubit[3],input_qubit[0])) c.append(cirq.H.on(input_qubit[0])) c.append(cirq.CNOT.on(input_qubit[3],input_qubit[0])) c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) c.append(cirq.X.on(input_qubit[1])) c.append(cirq.X.on(input_qubit[1])) c.append(cirq.measure(*input_qubit, key='result')) return c def bitstring(bits): return ''.join(str(int(b)) for b in bits) if __name__ == '__main__': qubit_count = 4 input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)] circuit = make_circuit(qubit_count,input_qubits) circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap') circuit_sample_count =2820 circuit = circuit.with_noise(cirq.depolarize(p=0.01)) simulator = cirq.Simulator() result = simulator.run(circuit, repetitions=circuit_sample_count) frequencies = result.histogram(key='result', fold_func=bitstring) writefile = open("../data/startCirq_noisy553.csv","w+") print(format(frequencies),file=writefile) print("results end", file=writefile) print(circuit.__len__(), file=writefile) print(circuit,file=writefile) writefile.close()
true
true
f72a536ed7d7645ecead0368a4011e2dfa79644e
20
py
Python
ckan/lib/navl/__init__.py
florianm/ckan
1cfd98d591ac70b4eb81048bcd227b6c1354b1bf
[ "Apache-2.0" ]
12
2015-08-28T16:59:07.000Z
2020-03-08T01:39:30.000Z
ckan/lib/navl/__init__.py
florianm/ckan
1cfd98d591ac70b4eb81048bcd227b6c1354b1bf
[ "Apache-2.0" ]
13
2019-05-02T21:01:28.000Z
2020-10-20T23:34:48.000Z
ckan/lib/navl/__init__.py
florianm/ckan
1cfd98d591ac70b4eb81048bcd227b6c1354b1bf
[ "Apache-2.0" ]
10
2015-05-08T04:33:20.000Z
2020-03-03T15:17:58.000Z
__license__ = 'MIT'
10
19
0.7
__license__ = 'MIT'
true
true
f72a5415b9a53ec576425cc8bb6d98e89c6da886
700
py
Python
pytreex/block/util/setglobal.py
ufal/pytreex
9633c1420e6b4adecd73baaf761d26fa49708a61
[ "Apache-2.0" ]
11
2015-06-24T08:41:44.000Z
2021-09-02T21:12:10.000Z
pytreex/block/util/setglobal.py
ufal/pytreex
9633c1420e6b4adecd73baaf761d26fa49708a61
[ "Apache-2.0" ]
4
2016-01-12T19:21:22.000Z
2019-05-10T14:46:44.000Z
pytreex/block/util/setglobal.py
ufal/pytreex
9633c1420e6b4adecd73baaf761d26fa49708a61
[ "Apache-2.0" ]
3
2016-01-22T11:54:11.000Z
2019-04-30T17:09:55.000Z
#!/usr/bin/env python # coding=utf-8 # # Block for making tree copies # from __future__ import unicode_literals from pytreex.core.block import Block __author__ = "Ondřej Dušek" __date__ = "2012" class SetGlobal(Block): def __init__(self, scenario, args): """\ Constructor, sets the arguments given to this block as global. """ Block.__init__(self, scenario, args) for arg, value in args.items(): scenario.global_args[arg] = value def process_bundle(self, doc): """\ This block does nothing with the documents, its only work is setting the global arguments in the initialization phase. """ pass
23.333333
70
0.642857
from __future__ import unicode_literals from pytreex.core.block import Block __author__ = "Ondřej Dušek" __date__ = "2012" class SetGlobal(Block): def __init__(self, scenario, args): Block.__init__(self, scenario, args) for arg, value in args.items(): scenario.global_args[arg] = value def process_bundle(self, doc): pass
true
true
f72a54c5a6aefc1b68cf97340534140cea211c6d
39,428
py
Python
modin/pandas/test/utils.py
itsliya/modin
d4ce5390816ae7eb8717bf271e1feabd3d5fabee
[ "ECL-2.0", "Apache-2.0" ]
1
2021-05-19T04:01:17.000Z
2021-05-19T04:01:17.000Z
modin/pandas/test/utils.py
itsliya/modin
d4ce5390816ae7eb8717bf271e1feabd3d5fabee
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
modin/pandas/test/utils.py
itsliya/modin
d4ce5390816ae7eb8717bf271e1feabd3d5fabee
[ "ECL-2.0", "Apache-2.0" ]
1
2022-01-29T12:12:42.000Z
2022-01-29T12:12:42.000Z
# Licensed to Modin Development Team under one or more contributor license agreements. # See the NOTICE file distributed with this work for additional information regarding # copyright ownership. The Modin Development Team 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. import pytest import numpy as np import math import pandas from pandas.testing import ( assert_series_equal, assert_frame_equal, assert_index_equal, assert_extension_array_equal, ) import modin.pandas as pd from modin.utils import to_pandas from modin.config import TestDatasetSize, TrackFileLeaks from io import BytesIO import os from string import ascii_letters import csv import psutil import functools random_state = np.random.RandomState(seed=42) DATASET_SIZE_DICT = { "Small": (2 ** 2, 2 ** 3), "Normal": (2 ** 6, 2 ** 8), "Big": (2 ** 7, 2 ** 12), } # Size of test dataframes NCOLS, NROWS = DATASET_SIZE_DICT.get(TestDatasetSize.get(), DATASET_SIZE_DICT["Normal"]) # Range for values for test data RAND_LOW = 0 RAND_HIGH = 100 # Directory for storing I/O operations test data IO_OPS_DATA_DIR = os.path.join(os.path.dirname(__file__), "io_tests_data") # Input data and functions for the tests # The test data that we will test our code against test_data = { # "empty_data": {}, # "columns_only": {"col1": [], "col2": [], "col3": [], "col4": [], "col5": []}, "int_data": { "col{}".format(int((i - NCOLS / 2) % NCOLS + 1)): random_state.randint( RAND_LOW, RAND_HIGH, size=(NROWS) ) for i in range(NCOLS) }, "float_nan_data": { "col{}".format(int((i - NCOLS / 2) % NCOLS + 1)): [ x if (j % 4 == 0 and i > NCOLS // 2) or (j != i and i <= NCOLS // 2) else np.NaN for j, x in enumerate( random_state.uniform(RAND_LOW, RAND_HIGH, size=(NROWS)) ) ] for i in range(NCOLS) }, # "int_float_object_data": { # "col3": [1, 2, 3, 4], # "col4": [4, 5, 6, 7], # "col1": [8.0, 9.4, 10.1, 11.3], # "col2": ["a", "b", "c", "d"], # }, # "datetime_timedelta_data": { # "col3": [ # np.datetime64("2010"), # np.datetime64("2011"), # np.datetime64("2011-06-15T00:00"), # np.datetime64("2009-01-01"), # ], # "col4": [ # np.datetime64("2010"), # np.datetime64("2011"), # np.datetime64("2011-06-15T00:00"), # np.datetime64("2009-01-01"), # ], # "col1": [ # np.timedelta64(1, "M"), # np.timedelta64(2, "D"), # np.timedelta64(3, "Y"), # np.timedelta64(20, "D"), # ], # "col2": [ # np.timedelta64(1, "M"), # np.timedelta64(2, "D"), # np.timedelta64(3, "Y"), # np.timedelta64(20, "D"), # ], # }, # "all_data": { # "col3": 1.0, # "col4": np.datetime64("2011-06-15T00:00"), # "col5": np.array([3] * 4, dtype="int32"), # "col1": "foo", # "col2": True, # }, } # See details in #1403 test_data["int_data"]["index"] = test_data["int_data"].pop( "col{}".format(int(NCOLS / 2)) ) for col in test_data["float_nan_data"]: for row in range(NROWS // 2): if row % 16 == 0: test_data["float_nan_data"][col][row] = np.NaN test_data_values = list(test_data.values()) test_data_keys = list(test_data.keys()) test_bool_data = { "col{}".format(int((i - NCOLS / 2) % NCOLS + 1)): random_state.choice( [True, False], size=(NROWS) ) for i in range(NCOLS) } test_data_resample = { "data": {"A": range(12), "B": range(12)}, "index": pandas.date_range("31/12/2000", periods=12, freq="H"), } test_data_with_duplicates = { "no_duplicates": { "col{}".format(int((i - NCOLS / 2) % NCOLS + 1)): range(NROWS) for i in range(NCOLS) }, "all_duplicates": { "col{}".format(int((i - NCOLS / 2) % NCOLS + 1)): [ float(i) for _ in range(NROWS) ] for i in range(NCOLS) }, "some_duplicates": { "col{}".format(int((i - NCOLS / 2) % NCOLS + 1)): [ i if j % 7 == 0 else x for j, x in enumerate(range(NROWS)) ] for i in range(NCOLS) }, "has_name_column": { "name": ["one", "two", "two", "three"], "col1": [1, 2, 2, 3], "col3": [10, 20, 20, 3], "col7": [100, 201, 200, 300], }, "str_columns": { "col_str{}".format(int((i - NCOLS / 2) % NCOLS + 1)): [ "s" + str(x % 5) for x in range(NROWS) ] for i in range(NCOLS) }, } test_data_with_duplicates["float_nan"] = test_data["float_nan_data"] test_data_small = { "small": { "col0": [1, 2, 3, 4], "col1": [8.0, 9.4, 10.1, 11.3], "col2": [4, 5, 6, 7], } } test_data_diff_dtype = { "int_col": [-5, 2, 7, 16], "float_col": [np.NaN, -9.4, 10.1, np.NaN], "str_col": ["a", np.NaN, "c", "d"], "bool_col": [False, True, True, False], } test_data_small_values = list(test_data_small.values()) test_data_small_keys = list(test_data_small.keys()) test_data_with_duplicates_values = list(test_data_with_duplicates.values()) test_data_with_duplicates_keys = list(test_data_with_duplicates.keys()) test_data_categorical = { "ordered": pandas.Categorical(list("testdata"), ordered=True), "unordered": pandas.Categorical(list("testdata"), ordered=False), } test_data_categorical_values = list(test_data_categorical.values()) test_data_categorical_keys = list(test_data_categorical.keys()) numeric_dfs = [ "empty_data", "columns_only", "int_data", "float_nan_data", "with_index_column", ] no_numeric_dfs = ["datetime_timedelta_data"] # String test data test_string_data = { "separator data": [ "abC|DeF,Hik", "234,3245.67", "gSaf,qWer|Gre", "asd3,4sad|", np.NaN, ] } test_string_data_values = list(test_string_data.values()) test_string_data_keys = list(test_string_data.keys()) # List of strings test data test_string_list_data = {"simple string": [["a"], ["CdE"], ["jDf"], ["werB"]]} test_string_list_data_values = list(test_string_list_data.values()) test_string_list_data_keys = list(test_string_list_data.keys()) string_seperators = {"empty sep": "", "comma sep": ",", "None sep": None} string_sep_values = list(string_seperators.values()) string_sep_keys = list(string_seperators.keys()) string_na_rep = {"None na_rep": None, "- na_rep": "-", "nan na_rep": np.NaN} string_na_rep_values = list(string_na_rep.values()) string_na_rep_keys = list(string_na_rep.keys()) join_type = {"left": "left", "right": "right", "inner": "inner", "outer": "outer"} join_type_keys = list(join_type.keys()) join_type_values = list(join_type.values()) # Test functions for applymap test_func = { "plus one": lambda x: x + 1, "convert to string": lambda x: str(x), "square": lambda x: x * x, "identity": lambda x: x, "return false": lambda x: False, } test_func_keys = list(test_func.keys()) test_func_values = list(test_func.values()) numeric_test_funcs = ["plus one", "square"] # Test functions for query query_func = { "col1 < col2": "col1 < col2", "col3 > col4": "col3 > col4", "col1 == col2": "col1 == col2", "(col2 > col1) and (col1 < col3)": "(col2 > col1) and (col1 < col3)", } query_func_keys = list(query_func.keys()) query_func_values = list(query_func.values()) # Test agg functions for apply, agg, and aggregate agg_func = { "sum": "sum", "df sum": lambda df: df.sum(), "str": str, "sum mean": ["sum", "mean"], "sum df sum": ["sum", lambda df: df.sum()], "should raise TypeError": 1, } agg_func_keys = list(agg_func.keys()) agg_func_values = list(agg_func.values()) # For this sort of parameters pandas throws an exception. # See details in pandas issue 36036. agg_func_except = { "sum sum": ["sum", "sum"], } agg_func_except_keys = list(agg_func_except.keys()) agg_func_except_values = list(agg_func_except.values()) numeric_agg_funcs = ["sum mean", "sum sum", "sum df sum"] udf_func = { "return self": lambda df: lambda x, *args, **kwargs: type(x)(x.values), "change index": lambda df: lambda x, *args, **kwargs: pandas.Series( x.values, index=np.arange(-1, len(x.index) - 1) ), "return none": lambda df: lambda x, *args, **kwargs: None, "return empty": lambda df: lambda x, *args, **kwargs: pandas.Series(), "access self": lambda df: lambda x, other, *args, **kwargs: pandas.Series( x.values, index=other.index ), } udf_func_keys = list(udf_func.keys()) udf_func_values = list(udf_func.values()) # Test q values for quantiles quantiles = { "0.25": 0.25, "0.5": 0.5, "0.75": 0.75, "0.66": 0.66, "0.01": 0.01, "list": [0.25, 0.5, 0.75, 0.66, 0.01], } quantiles_keys = list(quantiles.keys()) quantiles_values = list(quantiles.values()) # Test indices for get, set_index, __contains__, insert indices = { "col1": "col1", "col2": "col2", "A": "A", "B": "B", "does not exist": "does not exist", } indices_keys = list(indices.keys()) indices_values = list(indices.values()) # Test functions for groupby apply groupby_apply_func = {"sum": lambda df: df.sum(), "negate": lambda df: -df} groupby_apply_func_keys = list(groupby_apply_func.keys()) groupby_apply_func_values = list(groupby_apply_func.values()) # Test functions for groupby agg groupby_agg_func = {"min": "min", "max": "max"} groupby_agg_func_keys = list(groupby_agg_func.keys()) groupby_agg_func_values = list(groupby_agg_func.values()) # Test functions for groupby transform groupby_transform_func = { "add 4": lambda df: df + 4, "negatie and minus 10": lambda df: -df - 10, } groupby_transform_func_keys = list(groupby_transform_func.keys()) groupby_transform_func_values = list(groupby_transform_func.values()) # Test functions for groupby pipe groupby_pipe_func = {"sum": lambda df: df.sum()} groupby_pipe_func_keys = list(groupby_pipe_func.keys()) groupby_pipe_func_values = list(groupby_pipe_func.values()) # END Test input data and functions # Parametrizations of common kwargs axis = { "over_rows_int": 0, "over_rows_str": "rows", "over_columns_int": 1, "over_columns_str": "columns", } axis_keys = list(axis.keys()) axis_values = list(axis.values()) bool_arg = {"True": True, "False": False, "None": None} bool_arg_keys = list(bool_arg.keys()) bool_arg_values = list(bool_arg.values()) int_arg = {"-5": -5, "-1": -1, "0": 0, "1": 1, "5": 5} int_arg_keys = list(int_arg.keys()) int_arg_values = list(int_arg.values()) # END parametrizations of common kwargs json_short_string = """[{"project": "modin"}]""" json_long_string = """{ "quiz": { "sport": { "q1": { "question": "Which one is correct team name in NBA?", "options": [ "New York Bulls", "Los Angeles Kings", "Golden State Warriros", "Huston Rocket" ], "answer": "Huston Rocket" } }, "maths": { "q1": { "question": "5 + 7 = ?", "options": [ "10", "11", "12", "13" ], "answer": "12" }, "q2": { "question": "12 - 8 = ?", "options": [ "1", "2", "3", "4" ], "answer": "4" } } } }""" json_long_bytes = BytesIO(json_long_string.encode(encoding="UTF-8")) json_short_bytes = BytesIO(json_short_string.encode(encoding="UTF-8")) # Text encoding types encoding_types = [ "ascii", "utf_32", "utf_32_be", "utf_32_le", "utf_16", "utf_16_be", "utf_16_le", "utf_7", "utf_8", "utf_8_sig", ] # raising of this exceptions can be caused by unexpected behavior # of I/O operation test, but can passed by eval_io function since # the type of this exceptions are the same io_ops_bad_exc = [TypeError, FileNotFoundError] # Files compression to extension mapping COMP_TO_EXT = {"gzip": "gz", "bz2": "bz2", "xz": "xz", "zip": "zip"} def categories_equals(left, right): assert (left.ordered and right.ordered) or (not left.ordered and not right.ordered) assert_extension_array_equal(left, right) def df_categories_equals(df1, df2): if not hasattr(df1, "select_dtypes"): if isinstance(df1, pandas.CategoricalDtype): return categories_equals(df1, df2) elif isinstance(getattr(df1, "dtype"), pandas.CategoricalDtype) and isinstance( getattr(df1, "dtype"), pandas.CategoricalDtype ): return categories_equals(df1.dtype, df2.dtype) else: return True categories_columns = df1.select_dtypes(include="category").columns for column in categories_columns: assert_extension_array_equal( df1[column].values, df2[column].values, check_dtype=False, ) def df_equals(df1, df2): """Tests if df1 and df2 are equal. Args: df1: (pandas or modin DataFrame or series) dataframe to test if equal. df2: (pandas or modin DataFrame or series) dataframe to test if equal. Returns: True if df1 is equal to df2. """ # Gets AttributError if modin's groupby object is not import like this from modin.pandas.groupby import DataFrameGroupBy groupby_types = (pandas.core.groupby.DataFrameGroupBy, DataFrameGroupBy) # The typing behavior of how pandas treats its index is not consistent when the # length of the DataFrame or Series is 0, so we just verify that the contents are # the same. if ( hasattr(df1, "index") and hasattr(df2, "index") and len(df1) == 0 and len(df2) == 0 ): if type(df1).__name__ == type(df2).__name__: if hasattr(df1, "name") and hasattr(df2, "name") and df1.name == df2.name: return if ( hasattr(df1, "columns") and hasattr(df2, "columns") and df1.columns.equals(df2.columns) ): return assert False if isinstance(df1, (list, tuple)) and all( isinstance(d, (pd.DataFrame, pd.Series, pandas.DataFrame, pandas.Series)) for d in df1 ): assert isinstance(df2, type(df1)), "Different type of collection" assert len(df1) == len(df2), "Different length result" return (df_equals(d1, d2) for d1, d2 in zip(df1, df2)) # Convert to pandas if isinstance(df1, (pd.DataFrame, pd.Series)): df1 = to_pandas(df1) if isinstance(df2, (pd.DataFrame, pd.Series)): df2 = to_pandas(df2) if isinstance(df1, pandas.DataFrame) and isinstance(df2, pandas.DataFrame): if (df1.empty and not df2.empty) or (df2.empty and not df1.empty): assert False, "One of the passed frames is empty, when other isn't" elif df1.empty and df2.empty and type(df1) != type(df2): assert ( False ), f"Empty frames have different types: {type(df1)} != {type(df2)}" if isinstance(df1, pandas.DataFrame) and isinstance(df2, pandas.DataFrame): assert_frame_equal( df1, df2, check_dtype=False, check_datetimelike_compat=True, check_index_type=False, check_column_type=False, check_categorical=False, ) df_categories_equals(df1, df2) elif isinstance(df1, pandas.Index) and isinstance(df2, pandas.Index): assert_index_equal(df1, df2) elif isinstance(df1, pandas.Series) and isinstance(df2, pandas.Series): assert_series_equal(df1, df2, check_dtype=False, check_series_type=False) elif isinstance(df1, groupby_types) and isinstance(df2, groupby_types): for g1, g2 in zip(df1, df2): assert g1[0] == g2[0] df_equals(g1[1], g2[1]) elif ( isinstance(df1, pandas.Series) and isinstance(df2, pandas.Series) and df1.empty and df2.empty ): assert all(df1.index == df2.index) assert df1.dtypes == df2.dtypes elif isinstance(df1, pandas.core.arrays.numpy_.PandasArray): assert isinstance(df2, pandas.core.arrays.numpy_.PandasArray) assert df1 == df2 elif isinstance(df1, np.recarray) and isinstance(df2, np.recarray): np.testing.assert_array_equal(df1, df2) else: if df1 != df2: np.testing.assert_almost_equal(df1, df2) def modin_df_almost_equals_pandas(modin_df, pandas_df): df_categories_equals(modin_df._to_pandas(), pandas_df) modin_df = to_pandas(modin_df) if hasattr(modin_df, "select_dtypes"): modin_df = modin_df.select_dtypes(exclude=["category"]) if hasattr(pandas_df, "select_dtypes"): pandas_df = pandas_df.select_dtypes(exclude=["category"]) difference = modin_df - pandas_df diff_max = difference.max() if isinstance(diff_max, pandas.Series): diff_max = diff_max.max() assert ( modin_df.equals(pandas_df) or diff_max < 0.0001 or (all(modin_df.isna().all()) and all(pandas_df.isna().all())) ) def df_is_empty(df): """Tests if df is empty. Args: df: (pandas or modin DataFrame) dataframe to test if empty. Returns: True if df is empty. """ assert df.size == 0 and df.empty assert df.shape[0] == 0 or df.shape[1] == 0 def arg_keys(arg_name, keys): """Appends arg_name to the front of all values in keys. Args: arg_name: (string) String containing argument name. keys: (list of strings) Possible inputs of argument. Returns: List of strings with arg_name append to front of keys. """ return ["{0}_{1}".format(arg_name, key) for key in keys] def name_contains(test_name, vals): """Determines if any string in vals is a substring of test_name. Args: test_name: (string) String to determine if contains substrings. vals: (list of strings) List of substrings to test for. Returns: True if a substring in vals is in test_name, else False. """ return any(val in test_name for val in vals) def check_df_columns_have_nans(df, cols): """Checks if there are NaN values in specified columns of a dataframe. :param df: Dataframe to check. :param cols: One column name or list of column names. :return: True if specified columns of dataframe contains NaNs. """ return ( pandas.api.types.is_list_like(cols) and ( any(isinstance(x, str) and x in df.columns and df[x].hasnans for x in cols) or any( isinstance(x, pd.Series) and x._parent is df and x.hasnans for x in cols ) ) ) or ( not pandas.api.types.is_list_like(cols) and cols in df.columns and df[cols].hasnans ) def eval_general( modin_df, pandas_df, operation, comparator=df_equals, __inplace__=False, check_exception_type=True, raising_exceptions=None, check_kwargs_callable=True, md_extra_kwargs=None, **kwargs, ): if raising_exceptions: assert ( check_exception_type ), "if raising_exceptions is not None or False, check_exception_type should be True" md_kwargs, pd_kwargs = {}, {} def execute_callable(fn, inplace=False, md_kwargs={}, pd_kwargs={}): try: pd_result = fn(pandas_df, **pd_kwargs) except Exception as pd_e: if check_exception_type is None: return None with pytest.raises(Exception) as md_e: # repr to force materialization repr(fn(modin_df, **md_kwargs)) if check_exception_type: assert isinstance(md_e.value, type(pd_e)) if raising_exceptions: assert not isinstance( md_e.value, tuple(raising_exceptions) ), f"not acceptable exception type: {md_e.value}" else: md_result = fn(modin_df, **md_kwargs) return (md_result, pd_result) if not __inplace__ else (modin_df, pandas_df) for key, value in kwargs.items(): if check_kwargs_callable and callable(value): values = execute_callable(value) # that means, that callable raised an exception if values is None: return else: md_value, pd_value = values else: md_value, pd_value = value, value md_kwargs[key] = md_value pd_kwargs[key] = pd_value if md_extra_kwargs: assert isinstance(md_extra_kwargs, dict) md_kwargs.update(md_extra_kwargs) values = execute_callable( operation, md_kwargs=md_kwargs, pd_kwargs=pd_kwargs, inplace=__inplace__ ) if values is not None: comparator(*values) def eval_io( fn_name, comparator=df_equals, cast_to_str=False, check_exception_type=True, raising_exceptions=io_ops_bad_exc, check_kwargs_callable=True, modin_warning=None, md_extra_kwargs=None, *args, **kwargs, ): """Evaluate I/O operation outputs equality check. Parameters ---------- fn_name: str I/O operation name ("read_csv" for example). comparator: obj Function to perform comparison. cast_to_str: bool There could be some missmatches in dtypes, so we're casting the whole frame to `str` before comparison. See issue #1931 for details. check_exception_type: bool Check or not exception types in the case of operation fail (compare exceptions types raised by Pandas and Modin). raising_exceptions: Exception or list of Exceptions Exceptions that should be raised even if they are raised both by Pandas and Modin (check evaluated only if `check_exception_type` passed as `True`). modin_warning: obj Warning that should be raised by Modin. md_extra_kwargs: dict Modin operation specific kwargs. """ def applyier(module, *args, **kwargs): result = getattr(module, fn_name)(*args, **kwargs) if cast_to_str: result = result.astype(str) return result def call_eval_general(): eval_general( pd, pandas, applyier, check_exception_type=check_exception_type, raising_exceptions=raising_exceptions, check_kwargs_callable=check_kwargs_callable, md_extra_kwargs=md_extra_kwargs, *args, **kwargs, ) if modin_warning: with pytest.warns(modin_warning): call_eval_general() else: call_eval_general() def eval_io_from_str(csv_str: str, unique_filename: str, **kwargs): """Evaluate I/O operation outputs equality check by using `csv_str` data passed as python str (csv test file will be created from `csv_str`). Parameters ---------- csv_str: str Test data for storing to csv file. unique_filename: str csv file name. """ try: with open(unique_filename, "w") as f: f.write(csv_str) eval_io( filepath_or_buffer=unique_filename, fn_name="read_csv", **kwargs, ) finally: if os.path.exists(unique_filename): try: os.remove(unique_filename) except PermissionError: pass def create_test_dfs(*args, **kwargs): post_fn = kwargs.pop("post_fn", lambda df: df) return map( post_fn, [pd.DataFrame(*args, **kwargs), pandas.DataFrame(*args, **kwargs)] ) def generate_dfs(): df = pandas.DataFrame( { "col1": [0, 1, 2, 3], "col2": [4, 5, 6, 7], "col3": [8, 9, 10, 11], "col4": [12, 13, 14, 15], "col5": [0, 0, 0, 0], } ) df2 = pandas.DataFrame( { "col1": [0, 1, 2, 3], "col2": [4, 5, 6, 7], "col3": [8, 9, 10, 11], "col6": [12, 13, 14, 15], "col7": [0, 0, 0, 0], } ) return df, df2 def generate_multiindex_dfs(axis=1): def generate_multiindex(index): return pandas.MultiIndex.from_tuples( [("a", x) for x in index.values], names=["name1", "name2"] ) df1, df2 = generate_dfs() df1.axes[axis], df2.axes[axis] = map( generate_multiindex, [df1.axes[axis], df2.axes[axis]] ) return df1, df2 def generate_multiindex(elements_number, nlevels=2, is_tree_like=False): def generate_level(length, nlevel): src = ["bar", "baz", "foo", "qux"] return [src[i % len(src)] + f"-{nlevel}-{i}" for i in range(length)] if is_tree_like: for penalty_level in [0, 1]: lvl_len_f, lvl_len_d = math.modf( round(elements_number ** (1 / (nlevels - penalty_level)), 12) ) if lvl_len_d >= 2 and lvl_len_f == 0: break if lvl_len_d < 2 or lvl_len_f != 0: raise RuntimeError( f"Can't generate Tree-like MultiIndex with lenght: {elements_number} and number of levels: {nlevels}" ) lvl_len = int(lvl_len_d) result = pd.MultiIndex.from_product( [generate_level(lvl_len, i) for i in range(nlevels - penalty_level)], names=[f"level-{i}" for i in range(nlevels - penalty_level)], ) if penalty_level: result = pd.MultiIndex.from_tuples( [("base_level", *ml_tuple) for ml_tuple in result], names=[f"level-{i}" for i in range(nlevels)], ) return result.sort_values() else: base_level = ["first"] * (elements_number // 2 + elements_number % 2) + [ "second" ] * (elements_number // 2) primary_levels = [generate_level(elements_number, i) for i in range(1, nlevels)] arrays = [base_level] + primary_levels return pd.MultiIndex.from_tuples( list(zip(*arrays)), names=[f"level-{i}" for i in range(nlevels)] ).sort_values() def generate_none_dfs(): df = pandas.DataFrame( { "col1": [0, 1, 2, 3], "col2": [4, 5, None, 7], "col3": [8, 9, 10, 11], "col4": [12, 13, 14, 15], "col5": [None, None, None, None], } ) df2 = pandas.DataFrame( { "col1": [0, 1, 2, 3], "col2": [4, 5, 6, 7], "col3": [8, 9, 10, 11], "col6": [12, 13, 14, 15], "col7": [0, 0, 0, 0], } ) return df, df2 def get_unique_filename( test_name: str = "test", kwargs: dict = {}, extension: str = "csv", data_dir: str = IO_OPS_DATA_DIR, suffix: str = "", debug_mode=False, ): """Returns unique file name with specified parameters. Parameters ---------- test_name: str name of the test for which the unique file name is needed. kwargs: list of ints Unique combiantion of test parameters for creation of unique name. extension: str Extension of unique file. data_dir: str Data directory where test files will be created. suffix: str String to append to the resulted name. debug_mode: bool Get unique filename containing kwargs values. Otherwise kwargs values will be replaced with hash equivalent. Returns ------- Unique file name. """ suffix_part = f"_{suffix}" if suffix else "" extension_part = f".{extension}" if extension else "" if debug_mode: # shortcut if kwargs parameter are not provided if len(kwargs) == 0 and extension == "csv" and suffix == "": return os.path.join(data_dir, (test_name + suffix_part + f".{extension}")) assert "." not in extension, "please provide pure extension name without '.'" prohibited_chars = ['"', "\n"] non_prohibited_char = "np_char" char_counter = 0 kwargs_name = dict(kwargs) for key, value in kwargs_name.items(): for char in prohibited_chars: if isinstance(value, str) and char in value or callable(value): kwargs_name[key] = non_prohibited_char + str(char_counter) char_counter += 1 parameters_values = "_".join( [ str(value) if not isinstance(value, (list, tuple)) else "_".join([str(x) for x in value]) for value in kwargs_name.values() ] ) return os.path.join( data_dir, test_name + parameters_values + suffix_part + extension_part ) else: import uuid return os.path.join(data_dir, uuid.uuid1().hex + suffix_part + extension_part) def get_random_string(): random_string = "".join( random_state.choice([x for x in ascii_letters], size=10).tolist() ) return random_string def insert_lines_to_csv( csv_name: str, lines_positions: list, lines_type: str = "blank", encoding: str = None, **csv_reader_writer_params, ): """Insert lines to ".csv" file. Parameters ---------- csv_name: str ".csv" file that should be modified. lines_positions: list of ints Lines postions that sghould be modified (serial number of line - begins from 0, ends in <rows_number> - 1). lines_type: str Lines types that should be inserted to ".csv" file. Possible types: "blank" - empty line without any delimiters/separators, "bad" - lines with len(lines_data) > cols_number encoding: str Encoding type that should be used during file reading and writing. """ cols_number = len(pandas.read_csv(csv_name, nrows=1).columns) if lines_type == "blank": lines_data = [] elif lines_type == "bad": cols_number = len(pandas.read_csv(csv_name, nrows=1).columns) lines_data = [x for x in range(cols_number + 1)] else: raise ValueError( f"acceptable values for parameter are ['blank', 'bad'], actually passed {lines_type}" ) lines = [] dialect = "excel" with open(csv_name, "r", encoding=encoding, newline="") as read_file: try: dialect = csv.Sniffer().sniff(read_file.read()) read_file.seek(0) except Exception: dialect = None reader = csv.reader( read_file, dialect=dialect if dialect is not None else "excel", **csv_reader_writer_params, ) counter = 0 for row in reader: if counter in lines_positions: lines.append(lines_data) else: lines.append(row) counter += 1 with open(csv_name, "w", encoding=encoding, newline="") as write_file: writer = csv.writer( write_file, dialect=dialect if dialect is not None else "excel", **csv_reader_writer_params, ) writer.writerows(lines) def _get_open_files(): """ psutil open_files() can return a lot of extra information that we can allow to be different, like file position; for simplicity we care about path and fd only. """ return sorted((info.path, info.fd) for info in psutil.Process().open_files()) def check_file_leaks(func): """ A decorator that ensures that no *newly* opened file handles are left after decorated function is finished. """ if not TrackFileLeaks.get(): return func @functools.wraps(func) def check(*a, **kw): fstart = _get_open_files() try: return func(*a, **kw) finally: leaks = [] for item in _get_open_files(): try: fstart.remove(item) except ValueError: # ignore files in /proc/, as they have nothing to do with # modin reading any data (and this is what we care about) if not item[0].startswith("/proc/"): leaks.append(item) assert ( not leaks ), f"Unexpected open handles left for: {', '.join(item[0] for item in leaks)}" return check def dummy_decorator(): """A problematic decorator that does not use `functools.wraps`. This introduces unwanted local variables for inspect.currentframe. This decorator is used in test_io to test `read_csv` and `read_table` """ def wrapper(method): def wrapped_function(self, *args, **kwargs): result = method(self, *args, **kwargs) return result return wrapped_function return wrapper def generate_dataframe(row_size=NROWS, additional_col_values=None): dates = pandas.date_range("2000", freq="h", periods=row_size) data = { "col1": np.arange(row_size) * 10, "col2": [str(x.date()) for x in dates], "col3": np.arange(row_size) * 10, "col4": [str(x.time()) for x in dates], "col5": [get_random_string() for _ in range(row_size)], "col6": random_state.uniform(low=0.0, high=10000.0, size=row_size), } if additional_col_values is not None: assert isinstance(additional_col_values, (list, tuple)) data.update( { "col7": random_state.choice(additional_col_values, size=row_size), } ) return pandas.DataFrame(data) def _make_csv_file(filenames): def _csv_file_maker( filename, row_size=NROWS, force=True, delimiter=",", encoding=None, compression="infer", additional_col_values=None, remove_randomness=False, add_blank_lines=False, add_bad_lines=False, add_nan_lines=False, thousands_separator=None, decimal_separator=None, comment_col_char=None, quoting=csv.QUOTE_MINIMAL, quotechar='"', doublequote=True, escapechar=None, line_terminator=None, ): if os.path.exists(filename) and not force: pass else: df = generate_dataframe(row_size, additional_col_values) if remove_randomness: df = df[["col1", "col2", "col3", "col4"]] if add_nan_lines: for i in range(0, row_size, row_size // (row_size // 10)): df.loc[i] = pandas.Series() if comment_col_char: char = comment_col_char if isinstance(comment_col_char, str) else "#" df.insert( loc=0, column="col_with_comments", value=[char if (x + 2) == 0 else x for x in range(row_size)], ) if thousands_separator: for col_id in ["col1", "col3"]: df[col_id] = df[col_id].apply( lambda x: f"{x:,d}".replace(",", thousands_separator) ) df["col6"] = df["col6"].apply( lambda x: f"{x:,f}".replace(",", thousands_separator) ) filename = ( f"{filename}.{COMP_TO_EXT[compression]}" if compression != "infer" else filename ) df.to_csv( filename, sep=delimiter, encoding=encoding, compression=compression, index=False, decimal=decimal_separator if decimal_separator else ".", line_terminator=line_terminator, quoting=quoting, quotechar=quotechar, doublequote=doublequote, escapechar=escapechar, ) csv_reader_writer_params = { "delimiter": delimiter, "doublequote": doublequote, "escapechar": escapechar, "lineterminator": line_terminator if line_terminator else os.linesep, "quotechar": quotechar, "quoting": quoting, } if add_blank_lines: insert_lines_to_csv( csv_name=filename, lines_positions=[ x for x in range(5, row_size, row_size // (row_size // 10)) ], lines_type="blank", encoding=encoding, **csv_reader_writer_params, ) if add_bad_lines: insert_lines_to_csv( csv_name=filename, lines_positions=[ x for x in range(6, row_size, row_size // (row_size // 10)) ], lines_type="bad", encoding=encoding, **csv_reader_writer_params, ) filenames.append(filename) return df return _csv_file_maker def teardown_test_file(test_path): if os.path.exists(test_path): # PermissionError can occure because of issue #2533 try: os.remove(test_path) except PermissionError: pass def teardown_test_files(test_paths: list): for path in test_paths: teardown_test_file(path) def sort_index_for_equal_values(series, ascending=False): if series.index.dtype == np.float64: # HACK: workaround for pandas bug: # https://github.com/pandas-dev/pandas/issues/34455 series.index = series.index.astype("str") res = series.groupby(series, sort=False).apply( lambda df: df.sort_index(ascending=ascending) ) if res.index.nlevels > series.index.nlevels: # Sometimes GroupBy adds an extra level with 'by' to the result index. # GroupBy is very inconsistent about when it's doing this, so that's # why this clumsy if-statement is used. res.index = res.index.droplevel(0) res.name = series.name return res
31.848142
117
0.582124
import pytest import numpy as np import math import pandas from pandas.testing import ( assert_series_equal, assert_frame_equal, assert_index_equal, assert_extension_array_equal, ) import modin.pandas as pd from modin.utils import to_pandas from modin.config import TestDatasetSize, TrackFileLeaks from io import BytesIO import os from string import ascii_letters import csv import psutil import functools random_state = np.random.RandomState(seed=42) DATASET_SIZE_DICT = { "Small": (2 ** 2, 2 ** 3), "Normal": (2 ** 6, 2 ** 8), "Big": (2 ** 7, 2 ** 12), } NCOLS, NROWS = DATASET_SIZE_DICT.get(TestDatasetSize.get(), DATASET_SIZE_DICT["Normal"]) RAND_LOW = 0 RAND_HIGH = 100 IO_OPS_DATA_DIR = os.path.join(os.path.dirname(__file__), "io_tests_data") test_data = { "int_data": { "col{}".format(int((i - NCOLS / 2) % NCOLS + 1)): random_state.randint( RAND_LOW, RAND_HIGH, size=(NROWS) ) for i in range(NCOLS) }, "float_nan_data": { "col{}".format(int((i - NCOLS / 2) % NCOLS + 1)): [ x if (j % 4 == 0 and i > NCOLS // 2) or (j != i and i <= NCOLS // 2) else np.NaN for j, x in enumerate( random_state.uniform(RAND_LOW, RAND_HIGH, size=(NROWS)) ) ] for i in range(NCOLS) }, } _data["int_data"]["index"] = test_data["int_data"].pop( "col{}".format(int(NCOLS / 2)) ) for col in test_data["float_nan_data"]: for row in range(NROWS // 2): if row % 16 == 0: test_data["float_nan_data"][col][row] = np.NaN test_data_values = list(test_data.values()) test_data_keys = list(test_data.keys()) test_bool_data = { "col{}".format(int((i - NCOLS / 2) % NCOLS + 1)): random_state.choice( [True, False], size=(NROWS) ) for i in range(NCOLS) } test_data_resample = { "data": {"A": range(12), "B": range(12)}, "index": pandas.date_range("31/12/2000", periods=12, freq="H"), } test_data_with_duplicates = { "no_duplicates": { "col{}".format(int((i - NCOLS / 2) % NCOLS + 1)): range(NROWS) for i in range(NCOLS) }, "all_duplicates": { "col{}".format(int((i - NCOLS / 2) % NCOLS + 1)): [ float(i) for _ in range(NROWS) ] for i in range(NCOLS) }, "some_duplicates": { "col{}".format(int((i - NCOLS / 2) % NCOLS + 1)): [ i if j % 7 == 0 else x for j, x in enumerate(range(NROWS)) ] for i in range(NCOLS) }, "has_name_column": { "name": ["one", "two", "two", "three"], "col1": [1, 2, 2, 3], "col3": [10, 20, 20, 3], "col7": [100, 201, 200, 300], }, "str_columns": { "col_str{}".format(int((i - NCOLS / 2) % NCOLS + 1)): [ "s" + str(x % 5) for x in range(NROWS) ] for i in range(NCOLS) }, } test_data_with_duplicates["float_nan"] = test_data["float_nan_data"] test_data_small = { "small": { "col0": [1, 2, 3, 4], "col1": [8.0, 9.4, 10.1, 11.3], "col2": [4, 5, 6, 7], } } test_data_diff_dtype = { "int_col": [-5, 2, 7, 16], "float_col": [np.NaN, -9.4, 10.1, np.NaN], "str_col": ["a", np.NaN, "c", "d"], "bool_col": [False, True, True, False], } test_data_small_values = list(test_data_small.values()) test_data_small_keys = list(test_data_small.keys()) test_data_with_duplicates_values = list(test_data_with_duplicates.values()) test_data_with_duplicates_keys = list(test_data_with_duplicates.keys()) test_data_categorical = { "ordered": pandas.Categorical(list("testdata"), ordered=True), "unordered": pandas.Categorical(list("testdata"), ordered=False), } test_data_categorical_values = list(test_data_categorical.values()) test_data_categorical_keys = list(test_data_categorical.keys()) numeric_dfs = [ "empty_data", "columns_only", "int_data", "float_nan_data", "with_index_column", ] no_numeric_dfs = ["datetime_timedelta_data"] test_string_data = { "separator data": [ "abC|DeF,Hik", "234,3245.67", "gSaf,qWer|Gre", "asd3,4sad|", np.NaN, ] } test_string_data_values = list(test_string_data.values()) test_string_data_keys = list(test_string_data.keys()) test_string_list_data = {"simple string": [["a"], ["CdE"], ["jDf"], ["werB"]]} test_string_list_data_values = list(test_string_list_data.values()) test_string_list_data_keys = list(test_string_list_data.keys()) string_seperators = {"empty sep": "", "comma sep": ",", "None sep": None} string_sep_values = list(string_seperators.values()) string_sep_keys = list(string_seperators.keys()) string_na_rep = {"None na_rep": None, "- na_rep": "-", "nan na_rep": np.NaN} string_na_rep_values = list(string_na_rep.values()) string_na_rep_keys = list(string_na_rep.keys()) join_type = {"left": "left", "right": "right", "inner": "inner", "outer": "outer"} join_type_keys = list(join_type.keys()) join_type_values = list(join_type.values()) test_func = { "plus one": lambda x: x + 1, "convert to string": lambda x: str(x), "square": lambda x: x * x, "identity": lambda x: x, "return false": lambda x: False, } test_func_keys = list(test_func.keys()) test_func_values = list(test_func.values()) numeric_test_funcs = ["plus one", "square"] query_func = { "col1 < col2": "col1 < col2", "col3 > col4": "col3 > col4", "col1 == col2": "col1 == col2", "(col2 > col1) and (col1 < col3)": "(col2 > col1) and (col1 < col3)", } query_func_keys = list(query_func.keys()) query_func_values = list(query_func.values()) agg_func = { "sum": "sum", "df sum": lambda df: df.sum(), "str": str, "sum mean": ["sum", "mean"], "sum df sum": ["sum", lambda df: df.sum()], "should raise TypeError": 1, } agg_func_keys = list(agg_func.keys()) agg_func_values = list(agg_func.values()) agg_func_except = { "sum sum": ["sum", "sum"], } agg_func_except_keys = list(agg_func_except.keys()) agg_func_except_values = list(agg_func_except.values()) numeric_agg_funcs = ["sum mean", "sum sum", "sum df sum"] udf_func = { "return self": lambda df: lambda x, *args, **kwargs: type(x)(x.values), "change index": lambda df: lambda x, *args, **kwargs: pandas.Series( x.values, index=np.arange(-1, len(x.index) - 1) ), "return none": lambda df: lambda x, *args, **kwargs: None, "return empty": lambda df: lambda x, *args, **kwargs: pandas.Series(), "access self": lambda df: lambda x, other, *args, **kwargs: pandas.Series( x.values, index=other.index ), } udf_func_keys = list(udf_func.keys()) udf_func_values = list(udf_func.values()) quantiles = { "0.25": 0.25, "0.5": 0.5, "0.75": 0.75, "0.66": 0.66, "0.01": 0.01, "list": [0.25, 0.5, 0.75, 0.66, 0.01], } quantiles_keys = list(quantiles.keys()) quantiles_values = list(quantiles.values()) indices = { "col1": "col1", "col2": "col2", "A": "A", "B": "B", "does not exist": "does not exist", } indices_keys = list(indices.keys()) indices_values = list(indices.values()) groupby_apply_func = {"sum": lambda df: df.sum(), "negate": lambda df: -df} groupby_apply_func_keys = list(groupby_apply_func.keys()) groupby_apply_func_values = list(groupby_apply_func.values()) groupby_agg_func = {"min": "min", "max": "max"} groupby_agg_func_keys = list(groupby_agg_func.keys()) groupby_agg_func_values = list(groupby_agg_func.values()) groupby_transform_func = { "add 4": lambda df: df + 4, "negatie and minus 10": lambda df: -df - 10, } groupby_transform_func_keys = list(groupby_transform_func.keys()) groupby_transform_func_values = list(groupby_transform_func.values()) groupby_pipe_func = {"sum": lambda df: df.sum()} groupby_pipe_func_keys = list(groupby_pipe_func.keys()) groupby_pipe_func_values = list(groupby_pipe_func.values()) axis = { "over_rows_int": 0, "over_rows_str": "rows", "over_columns_int": 1, "over_columns_str": "columns", } axis_keys = list(axis.keys()) axis_values = list(axis.values()) bool_arg = {"True": True, "False": False, "None": None} bool_arg_keys = list(bool_arg.keys()) bool_arg_values = list(bool_arg.values()) int_arg = {"-5": -5, "-1": -1, "0": 0, "1": 1, "5": 5} int_arg_keys = list(int_arg.keys()) int_arg_values = list(int_arg.values()) json_short_string = """[{"project": "modin"}]""" json_long_string = """{ "quiz": { "sport": { "q1": { "question": "Which one is correct team name in NBA?", "options": [ "New York Bulls", "Los Angeles Kings", "Golden State Warriros", "Huston Rocket" ], "answer": "Huston Rocket" } }, "maths": { "q1": { "question": "5 + 7 = ?", "options": [ "10", "11", "12", "13" ], "answer": "12" }, "q2": { "question": "12 - 8 = ?", "options": [ "1", "2", "3", "4" ], "answer": "4" } } } }""" json_long_bytes = BytesIO(json_long_string.encode(encoding="UTF-8")) json_short_bytes = BytesIO(json_short_string.encode(encoding="UTF-8")) encoding_types = [ "ascii", "utf_32", "utf_32_be", "utf_32_le", "utf_16", "utf_16_be", "utf_16_le", "utf_7", "utf_8", "utf_8_sig", ] io_ops_bad_exc = [TypeError, FileNotFoundError] COMP_TO_EXT = {"gzip": "gz", "bz2": "bz2", "xz": "xz", "zip": "zip"} def categories_equals(left, right): assert (left.ordered and right.ordered) or (not left.ordered and not right.ordered) assert_extension_array_equal(left, right) def df_categories_equals(df1, df2): if not hasattr(df1, "select_dtypes"): if isinstance(df1, pandas.CategoricalDtype): return categories_equals(df1, df2) elif isinstance(getattr(df1, "dtype"), pandas.CategoricalDtype) and isinstance( getattr(df1, "dtype"), pandas.CategoricalDtype ): return categories_equals(df1.dtype, df2.dtype) else: return True categories_columns = df1.select_dtypes(include="category").columns for column in categories_columns: assert_extension_array_equal( df1[column].values, df2[column].values, check_dtype=False, ) def df_equals(df1, df2): from modin.pandas.groupby import DataFrameGroupBy groupby_types = (pandas.core.groupby.DataFrameGroupBy, DataFrameGroupBy) # The typing behavior of how pandas treats its index is not consistent when the # length of the DataFrame or Series is 0, so we just verify that the contents are # the same. if ( hasattr(df1, "index") and hasattr(df2, "index") and len(df1) == 0 and len(df2) == 0 ): if type(df1).__name__ == type(df2).__name__: if hasattr(df1, "name") and hasattr(df2, "name") and df1.name == df2.name: return if ( hasattr(df1, "columns") and hasattr(df2, "columns") and df1.columns.equals(df2.columns) ): return assert False if isinstance(df1, (list, tuple)) and all( isinstance(d, (pd.DataFrame, pd.Series, pandas.DataFrame, pandas.Series)) for d in df1 ): assert isinstance(df2, type(df1)), "Different type of collection" assert len(df1) == len(df2), "Different length result" return (df_equals(d1, d2) for d1, d2 in zip(df1, df2)) # Convert to pandas if isinstance(df1, (pd.DataFrame, pd.Series)): df1 = to_pandas(df1) if isinstance(df2, (pd.DataFrame, pd.Series)): df2 = to_pandas(df2) if isinstance(df1, pandas.DataFrame) and isinstance(df2, pandas.DataFrame): if (df1.empty and not df2.empty) or (df2.empty and not df1.empty): assert False, "One of the passed frames is empty, when other isn't" elif df1.empty and df2.empty and type(df1) != type(df2): assert ( False ), f"Empty frames have different types: {type(df1)} != {type(df2)}" if isinstance(df1, pandas.DataFrame) and isinstance(df2, pandas.DataFrame): assert_frame_equal( df1, df2, check_dtype=False, check_datetimelike_compat=True, check_index_type=False, check_column_type=False, check_categorical=False, ) df_categories_equals(df1, df2) elif isinstance(df1, pandas.Index) and isinstance(df2, pandas.Index): assert_index_equal(df1, df2) elif isinstance(df1, pandas.Series) and isinstance(df2, pandas.Series): assert_series_equal(df1, df2, check_dtype=False, check_series_type=False) elif isinstance(df1, groupby_types) and isinstance(df2, groupby_types): for g1, g2 in zip(df1, df2): assert g1[0] == g2[0] df_equals(g1[1], g2[1]) elif ( isinstance(df1, pandas.Series) and isinstance(df2, pandas.Series) and df1.empty and df2.empty ): assert all(df1.index == df2.index) assert df1.dtypes == df2.dtypes elif isinstance(df1, pandas.core.arrays.numpy_.PandasArray): assert isinstance(df2, pandas.core.arrays.numpy_.PandasArray) assert df1 == df2 elif isinstance(df1, np.recarray) and isinstance(df2, np.recarray): np.testing.assert_array_equal(df1, df2) else: if df1 != df2: np.testing.assert_almost_equal(df1, df2) def modin_df_almost_equals_pandas(modin_df, pandas_df): df_categories_equals(modin_df._to_pandas(), pandas_df) modin_df = to_pandas(modin_df) if hasattr(modin_df, "select_dtypes"): modin_df = modin_df.select_dtypes(exclude=["category"]) if hasattr(pandas_df, "select_dtypes"): pandas_df = pandas_df.select_dtypes(exclude=["category"]) difference = modin_df - pandas_df diff_max = difference.max() if isinstance(diff_max, pandas.Series): diff_max = diff_max.max() assert ( modin_df.equals(pandas_df) or diff_max < 0.0001 or (all(modin_df.isna().all()) and all(pandas_df.isna().all())) ) def df_is_empty(df): assert df.size == 0 and df.empty assert df.shape[0] == 0 or df.shape[1] == 0 def arg_keys(arg_name, keys): return ["{0}_{1}".format(arg_name, key) for key in keys] def name_contains(test_name, vals): return any(val in test_name for val in vals) def check_df_columns_have_nans(df, cols): return ( pandas.api.types.is_list_like(cols) and ( any(isinstance(x, str) and x in df.columns and df[x].hasnans for x in cols) or any( isinstance(x, pd.Series) and x._parent is df and x.hasnans for x in cols ) ) ) or ( not pandas.api.types.is_list_like(cols) and cols in df.columns and df[cols].hasnans ) def eval_general( modin_df, pandas_df, operation, comparator=df_equals, __inplace__=False, check_exception_type=True, raising_exceptions=None, check_kwargs_callable=True, md_extra_kwargs=None, **kwargs, ): if raising_exceptions: assert ( check_exception_type ), "if raising_exceptions is not None or False, check_exception_type should be True" md_kwargs, pd_kwargs = {}, {} def execute_callable(fn, inplace=False, md_kwargs={}, pd_kwargs={}): try: pd_result = fn(pandas_df, **pd_kwargs) except Exception as pd_e: if check_exception_type is None: return None with pytest.raises(Exception) as md_e: repr(fn(modin_df, **md_kwargs)) if check_exception_type: assert isinstance(md_e.value, type(pd_e)) if raising_exceptions: assert not isinstance( md_e.value, tuple(raising_exceptions) ), f"not acceptable exception type: {md_e.value}" else: md_result = fn(modin_df, **md_kwargs) return (md_result, pd_result) if not __inplace__ else (modin_df, pandas_df) for key, value in kwargs.items(): if check_kwargs_callable and callable(value): values = execute_callable(value) if values is None: return else: md_value, pd_value = values else: md_value, pd_value = value, value md_kwargs[key] = md_value pd_kwargs[key] = pd_value if md_extra_kwargs: assert isinstance(md_extra_kwargs, dict) md_kwargs.update(md_extra_kwargs) values = execute_callable( operation, md_kwargs=md_kwargs, pd_kwargs=pd_kwargs, inplace=__inplace__ ) if values is not None: comparator(*values) def eval_io( fn_name, comparator=df_equals, cast_to_str=False, check_exception_type=True, raising_exceptions=io_ops_bad_exc, check_kwargs_callable=True, modin_warning=None, md_extra_kwargs=None, *args, **kwargs, ): def applyier(module, *args, **kwargs): result = getattr(module, fn_name)(*args, **kwargs) if cast_to_str: result = result.astype(str) return result def call_eval_general(): eval_general( pd, pandas, applyier, check_exception_type=check_exception_type, raising_exceptions=raising_exceptions, check_kwargs_callable=check_kwargs_callable, md_extra_kwargs=md_extra_kwargs, *args, **kwargs, ) if modin_warning: with pytest.warns(modin_warning): call_eval_general() else: call_eval_general() def eval_io_from_str(csv_str: str, unique_filename: str, **kwargs): try: with open(unique_filename, "w") as f: f.write(csv_str) eval_io( filepath_or_buffer=unique_filename, fn_name="read_csv", **kwargs, ) finally: if os.path.exists(unique_filename): try: os.remove(unique_filename) except PermissionError: pass def create_test_dfs(*args, **kwargs): post_fn = kwargs.pop("post_fn", lambda df: df) return map( post_fn, [pd.DataFrame(*args, **kwargs), pandas.DataFrame(*args, **kwargs)] ) def generate_dfs(): df = pandas.DataFrame( { "col1": [0, 1, 2, 3], "col2": [4, 5, 6, 7], "col3": [8, 9, 10, 11], "col4": [12, 13, 14, 15], "col5": [0, 0, 0, 0], } ) df2 = pandas.DataFrame( { "col1": [0, 1, 2, 3], "col2": [4, 5, 6, 7], "col3": [8, 9, 10, 11], "col6": [12, 13, 14, 15], "col7": [0, 0, 0, 0], } ) return df, df2 def generate_multiindex_dfs(axis=1): def generate_multiindex(index): return pandas.MultiIndex.from_tuples( [("a", x) for x in index.values], names=["name1", "name2"] ) df1, df2 = generate_dfs() df1.axes[axis], df2.axes[axis] = map( generate_multiindex, [df1.axes[axis], df2.axes[axis]] ) return df1, df2 def generate_multiindex(elements_number, nlevels=2, is_tree_like=False): def generate_level(length, nlevel): src = ["bar", "baz", "foo", "qux"] return [src[i % len(src)] + f"-{nlevel}-{i}" for i in range(length)] if is_tree_like: for penalty_level in [0, 1]: lvl_len_f, lvl_len_d = math.modf( round(elements_number ** (1 / (nlevels - penalty_level)), 12) ) if lvl_len_d >= 2 and lvl_len_f == 0: break if lvl_len_d < 2 or lvl_len_f != 0: raise RuntimeError( f"Can't generate Tree-like MultiIndex with lenght: {elements_number} and number of levels: {nlevels}" ) lvl_len = int(lvl_len_d) result = pd.MultiIndex.from_product( [generate_level(lvl_len, i) for i in range(nlevels - penalty_level)], names=[f"level-{i}" for i in range(nlevels - penalty_level)], ) if penalty_level: result = pd.MultiIndex.from_tuples( [("base_level", *ml_tuple) for ml_tuple in result], names=[f"level-{i}" for i in range(nlevels)], ) return result.sort_values() else: base_level = ["first"] * (elements_number // 2 + elements_number % 2) + [ "second" ] * (elements_number // 2) primary_levels = [generate_level(elements_number, i) for i in range(1, nlevels)] arrays = [base_level] + primary_levels return pd.MultiIndex.from_tuples( list(zip(*arrays)), names=[f"level-{i}" for i in range(nlevels)] ).sort_values() def generate_none_dfs(): df = pandas.DataFrame( { "col1": [0, 1, 2, 3], "col2": [4, 5, None, 7], "col3": [8, 9, 10, 11], "col4": [12, 13, 14, 15], "col5": [None, None, None, None], } ) df2 = pandas.DataFrame( { "col1": [0, 1, 2, 3], "col2": [4, 5, 6, 7], "col3": [8, 9, 10, 11], "col6": [12, 13, 14, 15], "col7": [0, 0, 0, 0], } ) return df, df2 def get_unique_filename( test_name: str = "test", kwargs: dict = {}, extension: str = "csv", data_dir: str = IO_OPS_DATA_DIR, suffix: str = "", debug_mode=False, ): suffix_part = f"_{suffix}" if suffix else "" extension_part = f".{extension}" if extension else "" if debug_mode: # shortcut if kwargs parameter are not provided if len(kwargs) == 0 and extension == "csv" and suffix == "": return os.path.join(data_dir, (test_name + suffix_part + f".{extension}")) assert "." not in extension, "please provide pure extension name without '.'" prohibited_chars = ['"', "\n"] non_prohibited_char = "np_char" char_counter = 0 kwargs_name = dict(kwargs) for key, value in kwargs_name.items(): for char in prohibited_chars: if isinstance(value, str) and char in value or callable(value): kwargs_name[key] = non_prohibited_char + str(char_counter) char_counter += 1 parameters_values = "_".join( [ str(value) if not isinstance(value, (list, tuple)) else "_".join([str(x) for x in value]) for value in kwargs_name.values() ] ) return os.path.join( data_dir, test_name + parameters_values + suffix_part + extension_part ) else: import uuid return os.path.join(data_dir, uuid.uuid1().hex + suffix_part + extension_part) def get_random_string(): random_string = "".join( random_state.choice([x for x in ascii_letters], size=10).tolist() ) return random_string def insert_lines_to_csv( csv_name: str, lines_positions: list, lines_type: str = "blank", encoding: str = None, **csv_reader_writer_params, ): cols_number = len(pandas.read_csv(csv_name, nrows=1).columns) if lines_type == "blank": lines_data = [] elif lines_type == "bad": cols_number = len(pandas.read_csv(csv_name, nrows=1).columns) lines_data = [x for x in range(cols_number + 1)] else: raise ValueError( f"acceptable values for parameter are ['blank', 'bad'], actually passed {lines_type}" ) lines = [] dialect = "excel" with open(csv_name, "r", encoding=encoding, newline="") as read_file: try: dialect = csv.Sniffer().sniff(read_file.read()) read_file.seek(0) except Exception: dialect = None reader = csv.reader( read_file, dialect=dialect if dialect is not None else "excel", **csv_reader_writer_params, ) counter = 0 for row in reader: if counter in lines_positions: lines.append(lines_data) else: lines.append(row) counter += 1 with open(csv_name, "w", encoding=encoding, newline="") as write_file: writer = csv.writer( write_file, dialect=dialect if dialect is not None else "excel", **csv_reader_writer_params, ) writer.writerows(lines) def _get_open_files(): return sorted((info.path, info.fd) for info in psutil.Process().open_files()) def check_file_leaks(func): if not TrackFileLeaks.get(): return func @functools.wraps(func) def check(*a, **kw): fstart = _get_open_files() try: return func(*a, **kw) finally: leaks = [] for item in _get_open_files(): try: fstart.remove(item) except ValueError: # ignore files in /proc/, as they have nothing to do with # modin reading any data (and this is what we care about) if not item[0].startswith("/proc/"): leaks.append(item) assert ( not leaks ), f"Unexpected open handles left for: {', '.join(item[0] for item in leaks)}" return check def dummy_decorator(): def wrapper(method): def wrapped_function(self, *args, **kwargs): result = method(self, *args, **kwargs) return result return wrapped_function return wrapper def generate_dataframe(row_size=NROWS, additional_col_values=None): dates = pandas.date_range("2000", freq="h", periods=row_size) data = { "col1": np.arange(row_size) * 10, "col2": [str(x.date()) for x in dates], "col3": np.arange(row_size) * 10, "col4": [str(x.time()) for x in dates], "col5": [get_random_string() for _ in range(row_size)], "col6": random_state.uniform(low=0.0, high=10000.0, size=row_size), } if additional_col_values is not None: assert isinstance(additional_col_values, (list, tuple)) data.update( { "col7": random_state.choice(additional_col_values, size=row_size), } ) return pandas.DataFrame(data) def _make_csv_file(filenames): def _csv_file_maker( filename, row_size=NROWS, force=True, delimiter=",", encoding=None, compression="infer", additional_col_values=None, remove_randomness=False, add_blank_lines=False, add_bad_lines=False, add_nan_lines=False, thousands_separator=None, decimal_separator=None, comment_col_char=None, quoting=csv.QUOTE_MINIMAL, quotechar='"', doublequote=True, escapechar=None, line_terminator=None, ): if os.path.exists(filename) and not force: pass else: df = generate_dataframe(row_size, additional_col_values) if remove_randomness: df = df[["col1", "col2", "col3", "col4"]] if add_nan_lines: for i in range(0, row_size, row_size // (row_size // 10)): df.loc[i] = pandas.Series() if comment_col_char: char = comment_col_char if isinstance(comment_col_char, str) else "#" df.insert( loc=0, column="col_with_comments", value=[char if (x + 2) == 0 else x for x in range(row_size)], ) if thousands_separator: for col_id in ["col1", "col3"]: df[col_id] = df[col_id].apply( lambda x: f"{x:,d}".replace(",", thousands_separator) ) df["col6"] = df["col6"].apply( lambda x: f"{x:,f}".replace(",", thousands_separator) ) filename = ( f"{filename}.{COMP_TO_EXT[compression]}" if compression != "infer" else filename ) df.to_csv( filename, sep=delimiter, encoding=encoding, compression=compression, index=False, decimal=decimal_separator if decimal_separator else ".", line_terminator=line_terminator, quoting=quoting, quotechar=quotechar, doublequote=doublequote, escapechar=escapechar, ) csv_reader_writer_params = { "delimiter": delimiter, "doublequote": doublequote, "escapechar": escapechar, "lineterminator": line_terminator if line_terminator else os.linesep, "quotechar": quotechar, "quoting": quoting, } if add_blank_lines: insert_lines_to_csv( csv_name=filename, lines_positions=[ x for x in range(5, row_size, row_size // (row_size // 10)) ], lines_type="blank", encoding=encoding, **csv_reader_writer_params, ) if add_bad_lines: insert_lines_to_csv( csv_name=filename, lines_positions=[ x for x in range(6, row_size, row_size // (row_size // 10)) ], lines_type="bad", encoding=encoding, **csv_reader_writer_params, ) filenames.append(filename) return df return _csv_file_maker def teardown_test_file(test_path): if os.path.exists(test_path): # PermissionError can occure because of issue #2533 try: os.remove(test_path) except PermissionError: pass def teardown_test_files(test_paths: list): for path in test_paths: teardown_test_file(path) def sort_index_for_equal_values(series, ascending=False): if series.index.dtype == np.float64: # HACK: workaround for pandas bug: # https://github.com/pandas-dev/pandas/issues/34455 series.index = series.index.astype("str") res = series.groupby(series, sort=False).apply( lambda df: df.sort_index(ascending=ascending) ) if res.index.nlevels > series.index.nlevels: # Sometimes GroupBy adds an extra level with 'by' to the result index. # GroupBy is very inconsistent about when it's doing this, so that's # why this clumsy if-statement is used. res.index = res.index.droplevel(0) res.name = series.name return res
true
true
f72a54e9a3329047951044887f34ffc35ca51dd9
310
py
Python
jukebox/urls.py
bharadhwaj/jukebox
7223e6c686ac2868c6284270564db6d557b17fc5
[ "MIT" ]
1
2018-06-12T10:51:15.000Z
2018-06-12T10:51:15.000Z
jukebox/urls.py
bharadhwaj/jukebox
7223e6c686ac2868c6284270564db6d557b17fc5
[ "MIT" ]
3
2020-06-05T18:26:16.000Z
2021-06-10T20:30:23.000Z
jukebox/urls.py
bharadhwaj/jukebox
7223e6c686ac2868c6284270564db6d557b17fc5
[ "MIT" ]
null
null
null
from django.urls import path from . import views app_name = 'links' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('vote/', views.VoteView.as_view(), name='vote'), path('votes/', views.vote, name='votes'), path('result/', views.ResultView.as_view(), name='result'), ]
28.181818
63
0.651613
from django.urls import path from . import views app_name = 'links' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('vote/', views.VoteView.as_view(), name='vote'), path('votes/', views.vote, name='votes'), path('result/', views.ResultView.as_view(), name='result'), ]
true
true
f72a55db61c854785fc42c069c7252d364540690
23,064
py
Python
main.py
mpast/earth-engine-app
496fc6cfe95403a42374e439a4027c09760af964
[ "Apache-2.0" ]
2
2018-06-19T20:33:32.000Z
2018-07-13T16:03:30.000Z
main.py
mpast/earth-engine-app
496fc6cfe95403a42374e439a4027c09760af964
[ "Apache-2.0" ]
1
2020-11-15T17:56:09.000Z
2020-11-15T17:56:09.000Z
main.py
mpast/earth-engine-app
496fc6cfe95403a42374e439a4027c09760af964
[ "Apache-2.0" ]
null
null
null
from flask import Flask, render_template, request import config import os import json import ee import time import calendar import datetime import threading import logging, logging.config, yaml from pymemcache.client.hash import Client #from google.appengine.api import memcache as mc ################################################################################################## # CONSTANT DEFINITIONS ################################################################################################## EE_CREDENTIALS = ee.ServiceAccountCredentials(config.EE_ACCOUNT, config.EE_PRIVATE_KEY_FILE) HIGH_COLLECTION_ID = 'srtm90_v4' LIGHTS_COLLECTION_ID = 'NOAA/DMSP-OLS/NIGHTTIME_LIGHTS' TEMPERATURE_COLLECTION_ID = 'MODIS/MOD11A2' REDUCTION_SCALE_METERS = 20000 COUNTRIES_FILE = 'static/countries.txt' COUNTRIES_PATH = 'static/countries/' DETAILS_PATH = 'static/details/' CACHE = 0 # When use memcache SAVE = 0 # When we save data to precompute it in details folder INITIAL_MAP = '5' #logging #LOGGER_TYPE = 'file' LOGGER_TYPE = 'console' logging.config.dictConfig(yaml.load(open('logging.conf'))) logger = logging.getLogger(LOGGER_TYPE) ################################################################################################## # FUNCTIONS ################################################################################################## def json_serializer(key, value): if type(value) == str: return value, 1 return json.dumps(value), 2 def json_deserializer(key, value, flags): if flags == 1: return value if flags == 2: return json.loads(value) raise Exception('Unknown serialization format') mc = Client(('localhost', 11211), serializer = json_serializer, deserializer = json_deserializer) def createCountries(filename): file = open(filename, 'r') return file.read().splitlines() COUNTRIES_ID = createCountries(COUNTRIES_FILE) def change_dict(dct): if 'features' in dct: return dct['features'][0] return dct # Add a band containing image date as years since 1991. def CreateTimeBand(img): year = ee.Date(img.get('system:time_start')).get('year').subtract(1991) return ee.Image(year).byte().addBands(img) def CreateTimeBandTemp(img): year = ee.Date(img.get('system:time_start')).get('year').subtract(2013) return ee.Image(year).byte().addBands(img) def GetFeature(country_id): """Returns an ee.Feature for the country with the given ID.""" if CACHE: try: geojson = mc.get('geojson_' + country_id) if geojson is not None: return ee.Feature(geojson) except Exception as e: logger.debug('Error GetFeature cache: ' + str(e)) # Note: The country IDs are read from the filesystem in the initialization path = COUNTRIES_PATH + country_id + '.geo.json' path = os.path.join(os.path.split(__file__)[0], path) try: with open(path, 'r') as f: t = f.read() elem = json.loads(t, object_hook = change_dict) if CACHE: mc.set('geojson_' + country_id, elem) f.close() return ee.Feature(elem) except Exception as e: logger.debug('Error GetFeature reading file ' + path) def coordsToFeature(coords): feature = json.loads(coords, object_hook = change_dict) return ee.Feature(feature) def GetMapFromId(id): if id == '0': return GetHighMap() elif id == '1': return GetLightsMap() elif id == '2': return GetTemperatureMap() elif id == '3': return GetWaterOccurrenceMap() elif id == '4': return GetWaterChangeMap() elif id == '5': return GetForestChangeMap() elif id == '6': return GetVegetationMap() else: raise Exception("Map does not exists") ################################################################################################## # HIGH MAP ################################################################################################## def GetHighMap(): return ee.Image(HIGH_COLLECTION_ID).getMapId({ 'min': '0', 'max': '1000', 'palette': '0000ff, 008000, ff0000' }) def ComputeCountryTimeSeriesHigh(country_id, feature = None, zoom = 1): """Returns mean elevation for the country.""" img = ee.Image(HIGH_COLLECTION_ID) img = img.select('elevation') scale = 50000 if feature is None: feature = GetFeature(country_id) else: scale = scale / zoom reduction = img.reduceRegion(ee.Reducer.mean(), feature.geometry(), scale) feature = ee.Feature(None, { 'elevation': reduction.get('elevation') }) chart_data = feature.getInfo() return chart_data['properties'] ################################################################################################## # LIGHTS MAP ################################################################################################## def GetLightsMap(): """Returns the MapID for the night-time lights trend map.""" collection = ee.ImageCollection(LIGHTS_COLLECTION_ID) collection = collection.select('stable_lights').map(CreateTimeBand) # Fit a linear trend to the nighttime lights collection. fit = collection.reduce(ee.Reducer.linearFit()) return fit.getMapId({ 'min': '0', 'max': '0.18,20,-0.18', 'bands': 'scale,offset,scale', }) def ComputeCountryTimeSeriesLights(country_id, feature = None, zoom = 1): """Returns a series of brightness over time for the country.""" collection = ee.ImageCollection(LIGHTS_COLLECTION_ID) collection = collection.select('stable_lights').sort('system:time_start') scale = REDUCTION_SCALE_METERS if feature is None: feature = GetFeature(country_id) else: scale = scale / zoom # Compute the mean brightness in the region in each image. def ComputeMeanLights(img): reduction = img.reduceRegion(ee.Reducer.mean(), feature.geometry(), scale) return ee.Feature(None, { 'stable_lights': reduction.get('stable_lights'), 'system:time_start': img.get('system:time_start') }) chart_data = collection.map(ComputeMeanLights).getInfo() # Extract the results as a list of lists. def ExtractMeanLights(feature): if 'stable_lights' in feature['properties'] and feature['properties']['stable_lights'] is not None: return [ feature['properties']['system:time_start'], feature['properties']['stable_lights'] ] return map(ExtractMeanLights, chart_data['features']) ################################################################################################## # TEMPERATURE MAP ################################################################################################## def GetTemperatureMap(): """Returns the MapID for the temperature map""" collection = ee.ImageCollection(TEMPERATURE_COLLECTION_ID) collection = collection.select('LST_Day_1km')#.map(CreateTimeBand) fit = collection.median().toFloat().multiply(ee.Image(0.02)).subtract(ee.Image(273.15)) return fit.getMapId({ 'min': '0', 'max': '40', 'palette':'0000ff,32cd32,ffff00,ff8c00,ff0000' }) def ComputeCountryTimeSeriesTemp(country_id, feature = None, zoom = 1): """Returns a series of surface temperature over time for the country.""" collection = ee.ImageCollection(TEMPERATURE_COLLECTION_ID) collection = collection.select('LST_Day_1km') scale = 30000 if feature is None: feature = GetFeature(country_id) else: scale = scale / zoom # Compute the mean temperature in the region in each image. def ComputeMeanTemp(img): reduction = img.reduceRegion(ee.Reducer.mean(),feature.geometry(), scale) return ee.Feature(None, { 'temperature': reduction.get('LST_Day_1km'), 'system:time_start': img.get('system:time_start') }) chart_data = collection.map(ComputeMeanTemp).getInfo() def toCelsius(kelvin): scale = 0.02 return kelvin * scale - 273.15 # Extract the results as a list of lists. def ExtractMeanTemp(feature): if 'temperature' in feature['properties'] and feature['properties']['temperature'] is not None: tempInCelsius = toCelsius(feature['properties']['temperature']) return [ feature['properties']['system:time_start'], tempInCelsius ] return map(ExtractMeanTemp, chart_data['features']) ################################################################################################## # WATER OCCURRENCE MAP ################################################################################################## def GetWaterOccurrenceMap(): img = ee.Image('JRC/GSW1_0/GlobalSurfaceWater') img = img.select('occurrence') return img.getMapId({ 'min': '0', 'max': '100', 'palette': 'ff0000,0000ff' }) def ComputeCountryTimeSeriesWaterOccurence(country_id, feature = None, zoom = 1): """Returns a series of water occurrence over time for the country.""" image = ee.Image('JRC/GSW1_0/GlobalSurfaceWater') image = image.select('change_abs') scale = REDUCTION_SCALE_METERS if feature is None: feature = GetFeature(country_id) else: scale = scale / zoom # Compute the mean temperature in the region in each image. def ComputeMeanWaterOccurence(img): reduction = img.reduceRegion(ee.Reducer.histogram(), feature.geometry(), scale) return ee.Feature(None, { 'system:time_start' : img.get('system:time_start'), 'water': reduction.get('change_abs') }) chart_data = ComputeMeanWaterOccurence(image).getInfo() return chart_data['properties']['water'] ################################################################################################## # WATER CHANGE MAP ################################################################################################## def GetWaterChangeMap(): img = ee.Image('JRC/GSW1_0/GlobalSurfaceWater') img = img.select('change_abs') return img.getMapId({ 'min': '-50', 'max': '50', 'palette': 'ff0000,000000,00ff00' }) def ComputeCountryTimeSeriesWaterChange(country_id, feature = None, zoom = 1): """Returns a series of water change over time for the country.""" collection = ee.ImageCollection('JRC/GSW1_0/YearlyHistory') collection = collection.select('waterClass') scale = REDUCTION_SCALE_METERS if feature is None: feature = GetFeature(country_id) else: scale = scale / zoom # Compute the mean temperature in the region in each image. def ComputeMeanWaterChange(img): reduction = img.reduceRegion(ee.Reducer.mean(), feature.geometry(), scale) return ee.Feature(None, { 'system:time_start' : img.get('system:time_start'), 'water': reduction.get('waterClass') }) chart_data = collection.map(ComputeMeanWaterChange).getInfo() # Extract the results as a list of lists. def ExtractMeanWaterChange(feature): if 'water' in feature['properties'] and feature['properties']['water'] is not None: return [ feature['properties']['system:time_start'], feature['properties']['water'] ] return map(ExtractMeanWaterChange, chart_data['features']) ################################################################################################## # FOREST CHANGE MAP ################################################################################################## def GetForestChangeMap(): img = ee.Image('UMD/hansen/global_forest_change_2015') return img.getMapId({ 'bands': 'loss, treecover2000, gain', 'max': '1, 255, 1' }) def ComputeCountryTimeSeriesForestChange(country_id, feature = None, zoom = 1): """Returns country forest change.""" collection = ee.Image('UMD/hansen/global_forest_change_2015') scale = 14000 if feature is None: feature = GetFeature(country_id) else: scale = scale / zoom # Compute the mean temperature in the region in each image. def ComputeMeanForestChange(img): reduction = img.reduceRegion(ee.Reducer.mean(), feature.geometry(), scale) return ee.Feature(None, { 'treecover2000' : reduction.get('treecover2000'), 'loss': reduction.get('loss'), 'gain': reduction.get('gain') }) chart_data = ComputeMeanForestChange(collection).getInfo() # Extract the results as a list of lists. def ExtractMeanForestChange(feature): if 'loss' in feature['properties'] and feature['properties']['loss'] is not None: return [ feature['properties']['treecover2000'], feature['properties']['gain'], feature['properties']['loss'] ] return ExtractMeanForestChange(chart_data) ################################################################################################## # VEGETATION INDEX MAP ################################################################################################## def GetVegetationMap(): img = ee.Image(ee.ImageCollection('MODIS/MCD43A4_NDVI').mean()) return img.getMapId({ 'min': '0', 'max': '1', 'palette' : 'FFFFFF,CC9966,CC9900,996600,33CC00,009900,006600,000000' }) def ComputeCountryTimeSeriesVegetation(country_id, feature = None, zoom = 1): """Returns a series of vegetation over time for the country.""" collection = ee.ImageCollection('MODIS/MCD43A4_NDVI') collection = collection.select('NDVI') scale = REDUCTION_SCALE_METERS if feature is None: feature = GetFeature(country_id) else: scale = scale / zoom # Compute the mean temperature in the region in each image. def ComputeMeanVegetation(img): reduction = img.reduceRegion(ee.Reducer.mean(), feature.geometry(), scale) return ee.Feature(None, { 'system:time_start' : img.get('system:time_start'), 'NDVI': reduction.get('NDVI') }) chart_data = collection.map(ComputeMeanVegetation).getInfo() # Extract the results as a list of lists. def ExtractMeanVegetation(feature): if 'NDVI' in feature['properties'] and feature['properties']['NDVI'] is not None: return [ feature['properties']['system:time_start'], feature['properties']['NDVI'] ] return map(ExtractMeanVegetation, chart_data['features']) def ComputeCountryTimeSeries(map_id, country_id, feature = None, zoom = 1): """Returns a series of the specific map over time for the country.""" if map_id == '0': return ComputeCountryTimeSeriesHigh(country_id, feature, zoom) elif map_id == '1': return ComputeCountryTimeSeriesLights(country_id, feature, zoom) elif map_id == '2': return ComputeCountryTimeSeriesTemp(country_id, feature, zoom) elif map_id == '3': return ComputeCountryTimeSeriesWaterOccurence(country_id, feature, zoom) elif map_id == '4': return ComputeCountryTimeSeriesWaterChange(country_id, feature, zoom) elif map_id == '5': return ComputeCountryTimeSeriesForestChange(country_id, feature, zoom) elif map_id == '6': return ComputeCountryTimeSeriesVegetation(country_id, feature, zoom) else: raise Exception("Map type does not exists") ################################################################################################## # APP ROUTES ################################################################################################## # API app = Flask(__name__) app.jinja_env.auto_reload = True app.config.update( DEBUG=False, TEMPLATES_AUTO_RELOAD=False ) @app.before_request def before_request(): # When you import jinja2 macros, they get cached which is annoying for local # development, so wipe the cache every request. #app.jinja_env.cache = dict() # Initialize Earth Engine ee.Initialize(EE_CREDENTIALS) #ee.Initialize() # Define root route @app.route('/') def main(): mapid = GetMapFromId(INITIAL_MAP) # Add variables to the template template_values = { 'map': INITIAL_MAP, 'mapid': mapid['mapid'], 'token': mapid['token'], 'API_KEY': config.API_KEY, 'countries' : json.dumps(COUNTRIES_ID) } # Render the template index.html return render_template('index.html', values = template_values) @app.route('/map/<id>') def get(id): mapid = GetMapFromId(id) # Add variables to the template template_values = { 'map' : id, 'mapid': mapid['mapid'], 'token': mapid['token'], 'API_KEY': config.API_KEY, 'countries' : json.dumps(COUNTRIES_ID) } # Render the template reload.html return render_template('reload.html', values = template_values) @app.route('/save/<map_id>') def saveCountryTimeSeries(map_id): error = 0 message = '' if CACHE: elems = dict() if SAVE: path = DETAILS_PATH + 'mapid_' + map_id + '.json' details_file = open(path, 'w') else: thread = threading.Thread() thread.start() for country_id in COUNTRIES_ID: key = 'details' + '_'+ map_id + '_' + country_id details = dict() try: if map_id == '0' or map_id == '3': details = ComputeCountryTimeSeries(map_id, country_id) if details is not None: mc.set(key, json.dumps(details)) elif map_id == '5': details['forestChange'] = ComputeCountryTimeSeries(map_id, country_id) if details['forestChange'] is not None: mc.set(key, json.dumps(details)) else: details['timeSeries'] = list(ComputeCountryTimeSeries(map_id, country_id)) if details['timeSeries'] is not None: mc.set(key, json.dumps(details)) elems[country_id] = details except Exception as e: error = 1 message = str(e) logger.debug('Error saveCountryTimeSeries: ' + message) if SAVE and not error: json.dump(elems, details_file , separators = (',', ':')) details_file.close() return json.dumps({'status' : error, 'message' : message}) @app.route('/static/<map_id>') def staticCountryTimeSeries(map_id): error = 0 message = '' if SAVE: elems = dict() path = DETAILS_PATH + 'mapid_' + map_id + '.json' details_file = open(path, 'w') for country_id in COUNTRIES_ID: key = 'details' + '_'+ map_id + '_' + country_id details = dict() try: if map_id == '0' or map_id == '3': details = ComputeCountryTimeSeries(map_id, country_id) if details is not None: elems[country_id] = details elif map_id == '5': details['forestChange'] = ComputeCountryTimeSeries(map_id, country_id) if details['forestChange'] is not None: elems[country_id] = details else: details['timeSeries'] = list(ComputeCountryTimeSeries(map_id, country_id)) if details['timeSeries'] is not None: elems[country_id] = details except Exception as e: error = 1 message = str(e) logger.debug('Error saveCountryTimeSeries: ' + message) if not error: json.dump(elems, details_file , separators = (',', ':')) details_file.close() return json.dumps({'status' : error, 'message' : message}) @app.route('/details/<map_id>/<country_id>') def GetCountryTimeSeries(map_id, country_id): if CACHE: try: key = 'details' + '_'+ map_id + '_' + country_id details = mc.get(key) if details is not None: return details except Exception as e: logger.debug('Error cache GetCountryTimeSeries: ' + str(e)) details = dict() try: if map_id == '0' or map_id == '3': details = ComputeCountryTimeSeries(map_id, country_id) if CACHE and details is not None: mc.set(key, json.dumps(details)) elif map_id == '5': details['forestChange'] = ComputeCountryTimeSeries(map_id, country_id) if CACHE and details['forestChange'] is not None: mc.set(key, json.dumps(details)) else: details['timeSeries'] = list(ComputeCountryTimeSeries(map_id, country_id)) if CACHE and details['timeSeries'] is not None: mc.set(key, json.dumps(details)) except ee.EEException as e: # Handle exceptions from the EE client library. details['error'] = str(e) logger.debug('Error GetCountryTimeSeries: ' + details['error']) # Send the results to the browser. return json.dumps(details) @app.route('/details/<map_id>') def GetAllCountriesDetails(map_id): if CACHE: try: key = 'details' + '_' + map_id countries = mc.get(key) if countries is not None: return countries except Exception as e: logger.debug('Error cache GetAllCountriesDetails' + str(e)) countries = list() for country_id in COUNTRIES_ID: try: key = 'details' + '_'+ map_id + '_' + country_id country = mc.get(key) except Exception as e: logger.debug('Error cache GetAllCountriesDetails: ' + country_id) try: if country is None: elem = {'name' : getCountryName(country_id), 'data' : ComputeCountryTimeSeries(map_id, country_id) } else: elem = {'name' : getCountryName(country_id), 'data' : country } countries.append(json.dumps(elem)) except Exception as e: logger.debug('Error GetAllCountriesDetails, country: ' + country_id + ' : ' + str(e)) key = 'details' + '_'+ map_id mc.set(key, json.dumps(countries)) else: countries = dict() countries['error'] = 'Not implemented yet' return json.dumps(countries) @app.route('/custom/<map_id>/<zoom>', methods = ['POST']) def GetCustomSeries(map_id, zoom): """Get time series from a custom polygon""" key = list(request.form.keys())[0] details = dict() try: feature = coordsToFeature(key) if feature is not None: try: zoom = int(zoom) if map_id == '0' or map_id == '3': details = ComputeCountryTimeSeries(map_id, None, feature, zoom) elif map_id == '5': details['forestChange'] = ComputeCountryTimeSeries(map_id, None, feature, zoom) else: details['timeSeries'] = list(ComputeCountryTimeSeries(map_id, None, feature, zoom)) except ee.EEException as e: # Handle exceptions from the EE client library. details['error'] = str(e) logger.debug('Error GetCustomSeries: ' + details['error']) except Exception as e: details['error'] = str(e) logger.debug('Error GetCustomSeries: ' + details['error']) # Send the results to the browser. return json.dumps(details) @app.route('/country/<country_id>') def getCountryName(country_id): """Get country name from country id""" if CACHE: try: key = 'name_' + country_id name = mc.get(key) if name is not None: return name except Exception as e: logger.debug('Error cache getCountryName:' + str(e)) path = COUNTRIES_PATH + country_id + '.geo.json' path = os.path.join(os.path.split(__file__)[0], path) try: with open(path, 'r') as f: t = f.read() elem = json.loads(t, object_hook = change_dict) name = elem['properties']['name'] if CACHE and name is not None: mc.set(key, name) f.close() return name except Exception as e: logger.debug('Error getCountryName reading file ' + path + ' : ' + str(e)) # Run application in selected port if __name__ == '__main__': app.run('0.0.0.0', 8080, threaded=True)
32.995708
110
0.614161
from flask import Flask, render_template, request import config import os import json import ee import time import calendar import datetime import threading import logging, logging.config, yaml from pymemcache.client.hash import Client
true
true
f72a5625c654c8cd33973153b20dd9ad97e848d4
17,876
py
Python
pyeccodes/defs/grib2/tables/25/4_0_table.py
ecmwf/pyeccodes
dce2c72d3adcc0cb801731366be53327ce13a00b
[ "Apache-2.0" ]
7
2020-04-14T09:41:17.000Z
2021-08-06T09:38:19.000Z
pyeccodes/defs/grib2/tables/24/4_0_table.py
ecmwf/pyeccodes
dce2c72d3adcc0cb801731366be53327ce13a00b
[ "Apache-2.0" ]
null
null
null
pyeccodes/defs/grib2/tables/24/4_0_table.py
ecmwf/pyeccodes
dce2c72d3adcc0cb801731366be53327ce13a00b
[ "Apache-2.0" ]
3
2020-04-30T12:44:48.000Z
2020-12-15T08:40:26.000Z
def load(h): return ({'abbr': 0, 'code': 0, 'title': 'Analysis or forecast at a horizontal level or in a horizontal ' 'layer at a point in time'}, {'abbr': 1, 'code': 1, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time'}, {'abbr': 2, 'code': 2, 'title': 'Derived forecasts based on all ensemble members at a horizontal ' 'level or in a horizontal layer at a point in time'}, {'abbr': 3, 'code': 3, 'title': 'Derived forecasts based on a cluster of ensemble members over a ' 'rectangular area at a horizontal level or in a horizontal layer at ' 'a point in time'}, {'abbr': 4, 'code': 4, 'title': 'Derived forecasts based on a cluster of ensemble members over a ' 'circular area at a horizontal level or in a horizontal layer at a ' 'point in time'}, {'abbr': 5, 'code': 5, 'title': 'Probability forecasts at a horizontal level or in a horizontal ' 'layer at a point in time'}, {'abbr': 6, 'code': 6, 'title': 'Percentile forecasts at a horizontal level or in a horizontal ' 'layer at a point in time'}, {'abbr': 7, 'code': 7, 'title': 'Analysis or forecast error at a horizontal level or in a ' 'horizontal layer at a point in time'}, {'abbr': 8, 'code': 8, 'title': 'Average, accumulation, extreme values or other statistically ' 'processed values at a horizontal level or in a horizontal layer in ' 'a continuous or non-continuous time interval'}, {'abbr': 9, 'code': 9, 'title': 'Probability forecasts at a horizontal level or in a horizontal ' 'layer in a continuous or non-continuous time interval'}, {'abbr': 10, 'code': 10, 'title': 'Percentile forecasts at a horizontal level or in a horizontal ' 'layer in a continuous or non-continuous time interval'}, {'abbr': 11, 'code': 11, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer, in a continuous or ' 'non-continuous interval'}, {'abbr': 12, 'code': 12, 'title': 'Derived forecasts based on all ensemble members at a horizontal ' 'level or in a horizontal layer, in a continuous or non-continuous ' 'interval'}, {'abbr': 13, 'code': 13, 'title': 'Derived forecasts based on a cluster of ensemble members over a ' 'rectangular area, at a horizontal level or in a horizontal layer, ' 'in a continuous or non-continuous interval'}, {'abbr': 14, 'code': 14, 'title': 'Derived forecasts based on a cluster of ensemble members over a ' 'circular area, at a horizontal level or in a horizontal layer, in ' 'a continuous or non-continuous interval'}, {'abbr': 15, 'code': 15, 'title': 'Average, accumulation, extreme values, or other statistically ' 'processed values over a spatial area at a horizontal level or in a ' 'horizontal layer at a point in time'}, {'abbr': 20, 'code': 20, 'title': 'Radar product'}, {'abbr': 30, 'code': 30, 'title': 'Satellite product', 'units': 'deprecated'}, {'abbr': 31, 'code': 31, 'title': 'Satellite product'}, {'abbr': 32, 'code': 32, 'title': 'Analysis or forecast at a horizontal level or in a horizontal ' 'layer at a point in time for simulated (synthetic) satellite data'}, {'abbr': 33, 'code': 33, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'simulated (synthetic) satellite data'}, {'abbr': 34, 'code': 34, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer, in a continuous or ' 'non-continuous interval for simulated (synthetic) satellite data'}, {'abbr': 35, 'code': 35, 'title': 'Satellite product with or without associated quality values'}, {'abbr': 40, 'code': 40, 'title': 'Analysis or forecast at a horizontal level or in a horizontal ' 'layer at a point in time for atmospheric chemical constituents'}, {'abbr': 41, 'code': 41, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'atmospheric chemical constituents'}, {'abbr': 42, 'code': 42, 'title': 'Average, accumulation and/or extreme values or other statistically ' 'processed values at a horizontal level or in a horizontal layer in ' 'a continuous or non-continuous time interval for atmospheric ' 'chemical constituents'}, {'abbr': 43, 'code': 43, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer in a continuous or ' 'non-continuous time interval for atmospheric chemical ' 'constituents'}, {'abbr': 44, 'code': 44, 'title': 'Analysis or forecast at a horizontal level or in a horizontal ' 'layer at a point in time for aerosol'}, {'abbr': 45, 'code': 45, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'aerosol'}, {'abbr': 46, 'code': 46, 'title': 'Average, accumulation, and/or extreme values or other ' 'statistically processed values at a horizontal level or in a ' 'horizontal layer in a continuous or non-continuous time interval ' 'for aerosol'}, {'abbr': 47, 'code': 47, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer in a continuous or ' 'non-continuous time interval for aerosol'}, {'abbr': 48, 'code': 48, 'title': 'Analysis or forecast at a horizontal level or in a horizontal ' 'layer at a point in time for optical properties of aerosol'}, {'abbr': 49, 'code': 49, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'optical properties of aerosol'}, {'abbr': 51, 'code': 51, 'title': 'Categorical forecasts at a horizontal level or in a horizontal ' 'layer at a point in time'}, {'abbr': 53, 'code': 53, 'title': 'Partitioned parameters at a horizontal level or in a horizontal ' 'layer at a point in time'}, {'abbr': 54, 'code': 54, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'partitioned parameters'}, {'abbr': 55, 'code': 55, 'title': 'Spatio-temporal changing tiles at a horizontal level or horizontal ' 'layer at a point in time'}, {'abbr': 56, 'code': 56, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'spatio-temporal changing tile parameters', 'units': 'deprecated'}, {'abbr': 57, 'code': 57, 'title': 'Analysis or forecast at a horizontal level or in a horizontal ' 'layer at a point in time for atmospheric chemical constituents ' 'based on a distribution function'}, {'abbr': 58, 'code': 58, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'atmospheric chemical constituents based on a distribution ' 'function'}, {'abbr': 59, 'code': 59, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'spatio-temporal changing tile parameters', 'units': 'corrected version of template 4.56'}, {'abbr': 60, 'code': 60, 'title': 'Individual ensemble reforecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time'}, {'abbr': 61, 'code': 61, 'title': 'Individual ensemble reforecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer, in a continuous or ' 'non-continuous time interval'}, {'abbr': 62, 'code': 62, 'title': 'Average, accumulation and/or extreme values or other statistically ' 'processed values at a horizontal level or in a horizontal layer in ' 'a continuous or non-continuous time interval for spatio-temporal ' 'changing tiles at a horizontal level or horizontal layer at a ' 'point in time'}, {'abbr': 63, 'code': 63, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer in a continuous or ' 'non-continuous time interval for spatio-temporal changing tiles'}, {'abbr': 67, 'code': 67, 'title': 'Average, accumulation and/or extreme values or other statistically ' 'processed values at a horizontal level or in a horizontal layer in ' 'a continuous or non-continuous time interval for atmospheric ' 'chemical constituents based on a distribution function'}, {'abbr': 68, 'code': 68, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer in a continuous or ' 'non-continuous time interval for atmospheric chemical constituents ' 'based on a distribution function'}, {'abbr': 70, 'code': 70, 'title': 'Post-processing analysis or forecast at a horizontal level or in a ' 'horizontal layer at a point in time'}, {'abbr': 71, 'code': 71, 'title': 'Post-processing individual ensemble forecast, control and ' 'perturbed, at a horizontal level or in a horizontal layer at a ' 'point in time'}, {'abbr': 72, 'code': 72, 'title': 'Post-processing average, accumulation, extreme values or other ' 'statistically processed values at a horizontal level or in a ' 'horizontal layer in a continuous or non-continuous time interval'}, {'abbr': 73, 'code': 73, 'title': 'Post-processing individual ensemble forecast, control and ' 'perturbed, at a horizontal level or in a horizontal layer, in a ' 'continuous or non-continuous time interval'}, {'abbr': 76, 'code': 76, 'title': 'Analysis or forecast at a horizontal level or in a horizontal ' 'layer at a point in time for atmospheric chemical constituents ' 'with source/sink'}, {'abbr': 77, 'code': 77, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'atmospheric chemical constituents with source/sink'}, {'abbr': 78, 'code': 78, 'title': 'Average, accumulation, and/or extreme values or other ' 'statistically processed values at a horizontal level or in a ' 'horizontal layer in a continuous or non-continuous time interval ' 'for atmospheric chemical constituents with source/sink'}, {'abbr': 79, 'code': 79, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer in a continuous or ' 'non-continuous time interval for atmospheric chemical constituents ' 'with source/sink'}, {'abbr': 80, 'code': 80, 'title': 'Analysis or forecast at a horizontal level or in a horizontal ' 'layer at a point in time for optical properties of aerosol with ' 'source/sink'}, {'abbr': 81, 'code': 81, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'optical properties of aerosol with source/sink'}, {'abbr': 82, 'code': 82, 'title': 'Average, accumulation, and/or extreme values or other ' 'statistically processed values at a horizontal level or in a ' 'horizontal layer in a continuous or non-continuous time interval ' 'for aerosol with source/sink'}, {'abbr': 83, 'code': 83, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer in a continuous or ' 'non-continuous time interval for aerosol with source/sink'}, {'abbr': 91, 'code': 91, 'title': 'Categorical forecasts at a horizontal level or in a horizontal ' 'layer in a continuous or non-continuous time interval'}, {'abbr': 254, 'code': 254, 'title': 'CCITT IA5 character string'}, {'abbr': 1000, 'code': 1000, 'title': 'Cross-section of analysis and forecast at a point in time'}, {'abbr': 1001, 'code': 1001, 'title': 'Cross-section of averaged or otherwise statistically processed ' 'analysis or forecast over a range of time'}, {'abbr': 1002, 'code': 1002, 'title': 'Cross-section of analysis and forecast, averaged or otherwise ' 'statistically processed over latitude or longitude'}, {'abbr': 1100, 'code': 1100, 'title': 'Hovmoller-type grid with no averaging or other statistical ' 'processing'}, {'abbr': 1101, 'code': 1101, 'title': 'Hovmoller-type grid with averaging or other statistical ' 'processing'}, {'abbr': 50001, 'code': 50001, 'title': 'Forecasting Systems with Variable Resolution in a point in time'}, {'abbr': 50011, 'code': 50011, 'title': 'Forecasting Systems with Variable Resolution in a continous or non ' 'countinous time interval'}, {'abbr': 40033, 'code': 40033, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'simulated (synthetic) satellite data'}, {'abbr': 40034, 'code': 40034, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer, in a continuous or ' 'non-continuous interval for simulated (synthetic) satellite data'}, {'abbr': 65535, 'code': 65535, 'title': 'Missing'})
55.688474
91
0.519579
def load(h): return ({'abbr': 0, 'code': 0, 'title': 'Analysis or forecast at a horizontal level or in a horizontal ' 'layer at a point in time'}, {'abbr': 1, 'code': 1, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time'}, {'abbr': 2, 'code': 2, 'title': 'Derived forecasts based on all ensemble members at a horizontal ' 'level or in a horizontal layer at a point in time'}, {'abbr': 3, 'code': 3, 'title': 'Derived forecasts based on a cluster of ensemble members over a ' 'rectangular area at a horizontal level or in a horizontal layer at ' 'a point in time'}, {'abbr': 4, 'code': 4, 'title': 'Derived forecasts based on a cluster of ensemble members over a ' 'circular area at a horizontal level or in a horizontal layer at a ' 'point in time'}, {'abbr': 5, 'code': 5, 'title': 'Probability forecasts at a horizontal level or in a horizontal ' 'layer at a point in time'}, {'abbr': 6, 'code': 6, 'title': 'Percentile forecasts at a horizontal level or in a horizontal ' 'layer at a point in time'}, {'abbr': 7, 'code': 7, 'title': 'Analysis or forecast error at a horizontal level or in a ' 'horizontal layer at a point in time'}, {'abbr': 8, 'code': 8, 'title': 'Average, accumulation, extreme values or other statistically ' 'processed values at a horizontal level or in a horizontal layer in ' 'a continuous or non-continuous time interval'}, {'abbr': 9, 'code': 9, 'title': 'Probability forecasts at a horizontal level or in a horizontal ' 'layer in a continuous or non-continuous time interval'}, {'abbr': 10, 'code': 10, 'title': 'Percentile forecasts at a horizontal level or in a horizontal ' 'layer in a continuous or non-continuous time interval'}, {'abbr': 11, 'code': 11, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer, in a continuous or ' 'non-continuous interval'}, {'abbr': 12, 'code': 12, 'title': 'Derived forecasts based on all ensemble members at a horizontal ' 'level or in a horizontal layer, in a continuous or non-continuous ' 'interval'}, {'abbr': 13, 'code': 13, 'title': 'Derived forecasts based on a cluster of ensemble members over a ' 'rectangular area, at a horizontal level or in a horizontal layer, ' 'in a continuous or non-continuous interval'}, {'abbr': 14, 'code': 14, 'title': 'Derived forecasts based on a cluster of ensemble members over a ' 'circular area, at a horizontal level or in a horizontal layer, in ' 'a continuous or non-continuous interval'}, {'abbr': 15, 'code': 15, 'title': 'Average, accumulation, extreme values, or other statistically ' 'processed values over a spatial area at a horizontal level or in a ' 'horizontal layer at a point in time'}, {'abbr': 20, 'code': 20, 'title': 'Radar product'}, {'abbr': 30, 'code': 30, 'title': 'Satellite product', 'units': 'deprecated'}, {'abbr': 31, 'code': 31, 'title': 'Satellite product'}, {'abbr': 32, 'code': 32, 'title': 'Analysis or forecast at a horizontal level or in a horizontal ' 'layer at a point in time for simulated (synthetic) satellite data'}, {'abbr': 33, 'code': 33, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'simulated (synthetic) satellite data'}, {'abbr': 34, 'code': 34, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer, in a continuous or ' 'non-continuous interval for simulated (synthetic) satellite data'}, {'abbr': 35, 'code': 35, 'title': 'Satellite product with or without associated quality values'}, {'abbr': 40, 'code': 40, 'title': 'Analysis or forecast at a horizontal level or in a horizontal ' 'layer at a point in time for atmospheric chemical constituents'}, {'abbr': 41, 'code': 41, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'atmospheric chemical constituents'}, {'abbr': 42, 'code': 42, 'title': 'Average, accumulation and/or extreme values or other statistically ' 'processed values at a horizontal level or in a horizontal layer in ' 'a continuous or non-continuous time interval for atmospheric ' 'chemical constituents'}, {'abbr': 43, 'code': 43, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer in a continuous or ' 'non-continuous time interval for atmospheric chemical ' 'constituents'}, {'abbr': 44, 'code': 44, 'title': 'Analysis or forecast at a horizontal level or in a horizontal ' 'layer at a point in time for aerosol'}, {'abbr': 45, 'code': 45, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'aerosol'}, {'abbr': 46, 'code': 46, 'title': 'Average, accumulation, and/or extreme values or other ' 'statistically processed values at a horizontal level or in a ' 'horizontal layer in a continuous or non-continuous time interval ' 'for aerosol'}, {'abbr': 47, 'code': 47, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer in a continuous or ' 'non-continuous time interval for aerosol'}, {'abbr': 48, 'code': 48, 'title': 'Analysis or forecast at a horizontal level or in a horizontal ' 'layer at a point in time for optical properties of aerosol'}, {'abbr': 49, 'code': 49, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'optical properties of aerosol'}, {'abbr': 51, 'code': 51, 'title': 'Categorical forecasts at a horizontal level or in a horizontal ' 'layer at a point in time'}, {'abbr': 53, 'code': 53, 'title': 'Partitioned parameters at a horizontal level or in a horizontal ' 'layer at a point in time'}, {'abbr': 54, 'code': 54, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'partitioned parameters'}, {'abbr': 55, 'code': 55, 'title': 'Spatio-temporal changing tiles at a horizontal level or horizontal ' 'layer at a point in time'}, {'abbr': 56, 'code': 56, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'spatio-temporal changing tile parameters', 'units': 'deprecated'}, {'abbr': 57, 'code': 57, 'title': 'Analysis or forecast at a horizontal level or in a horizontal ' 'layer at a point in time for atmospheric chemical constituents ' 'based on a distribution function'}, {'abbr': 58, 'code': 58, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'atmospheric chemical constituents based on a distribution ' 'function'}, {'abbr': 59, 'code': 59, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'spatio-temporal changing tile parameters', 'units': 'corrected version of template 4.56'}, {'abbr': 60, 'code': 60, 'title': 'Individual ensemble reforecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time'}, {'abbr': 61, 'code': 61, 'title': 'Individual ensemble reforecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer, in a continuous or ' 'non-continuous time interval'}, {'abbr': 62, 'code': 62, 'title': 'Average, accumulation and/or extreme values or other statistically ' 'processed values at a horizontal level or in a horizontal layer in ' 'a continuous or non-continuous time interval for spatio-temporal ' 'changing tiles at a horizontal level or horizontal layer at a ' 'point in time'}, {'abbr': 63, 'code': 63, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer in a continuous or ' 'non-continuous time interval for spatio-temporal changing tiles'}, {'abbr': 67, 'code': 67, 'title': 'Average, accumulation and/or extreme values or other statistically ' 'processed values at a horizontal level or in a horizontal layer in ' 'a continuous or non-continuous time interval for atmospheric ' 'chemical constituents based on a distribution function'}, {'abbr': 68, 'code': 68, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer in a continuous or ' 'non-continuous time interval for atmospheric chemical constituents ' 'based on a distribution function'}, {'abbr': 70, 'code': 70, 'title': 'Post-processing analysis or forecast at a horizontal level or in a ' 'horizontal layer at a point in time'}, {'abbr': 71, 'code': 71, 'title': 'Post-processing individual ensemble forecast, control and ' 'perturbed, at a horizontal level or in a horizontal layer at a ' 'point in time'}, {'abbr': 72, 'code': 72, 'title': 'Post-processing average, accumulation, extreme values or other ' 'statistically processed values at a horizontal level or in a ' 'horizontal layer in a continuous or non-continuous time interval'}, {'abbr': 73, 'code': 73, 'title': 'Post-processing individual ensemble forecast, control and ' 'perturbed, at a horizontal level or in a horizontal layer, in a ' 'continuous or non-continuous time interval'}, {'abbr': 76, 'code': 76, 'title': 'Analysis or forecast at a horizontal level or in a horizontal ' 'layer at a point in time for atmospheric chemical constituents ' 'with source/sink'}, {'abbr': 77, 'code': 77, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'atmospheric chemical constituents with source/sink'}, {'abbr': 78, 'code': 78, 'title': 'Average, accumulation, and/or extreme values or other ' 'statistically processed values at a horizontal level or in a ' 'horizontal layer in a continuous or non-continuous time interval ' 'for atmospheric chemical constituents with source/sink'}, {'abbr': 79, 'code': 79, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer in a continuous or ' 'non-continuous time interval for atmospheric chemical constituents ' 'with source/sink'}, {'abbr': 80, 'code': 80, 'title': 'Analysis or forecast at a horizontal level or in a horizontal ' 'layer at a point in time for optical properties of aerosol with ' 'source/sink'}, {'abbr': 81, 'code': 81, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'optical properties of aerosol with source/sink'}, {'abbr': 82, 'code': 82, 'title': 'Average, accumulation, and/or extreme values or other ' 'statistically processed values at a horizontal level or in a ' 'horizontal layer in a continuous or non-continuous time interval ' 'for aerosol with source/sink'}, {'abbr': 83, 'code': 83, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer in a continuous or ' 'non-continuous time interval for aerosol with source/sink'}, {'abbr': 91, 'code': 91, 'title': 'Categorical forecasts at a horizontal level or in a horizontal ' 'layer in a continuous or non-continuous time interval'}, {'abbr': 254, 'code': 254, 'title': 'CCITT IA5 character string'}, {'abbr': 1000, 'code': 1000, 'title': 'Cross-section of analysis and forecast at a point in time'}, {'abbr': 1001, 'code': 1001, 'title': 'Cross-section of averaged or otherwise statistically processed ' 'analysis or forecast over a range of time'}, {'abbr': 1002, 'code': 1002, 'title': 'Cross-section of analysis and forecast, averaged or otherwise ' 'statistically processed over latitude or longitude'}, {'abbr': 1100, 'code': 1100, 'title': 'Hovmoller-type grid with no averaging or other statistical ' 'processing'}, {'abbr': 1101, 'code': 1101, 'title': 'Hovmoller-type grid with averaging or other statistical ' 'processing'}, {'abbr': 50001, 'code': 50001, 'title': 'Forecasting Systems with Variable Resolution in a point in time'}, {'abbr': 50011, 'code': 50011, 'title': 'Forecasting Systems with Variable Resolution in a continous or non ' 'countinous time interval'}, {'abbr': 40033, 'code': 40033, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer at a point in time for ' 'simulated (synthetic) satellite data'}, {'abbr': 40034, 'code': 40034, 'title': 'Individual ensemble forecast, control and perturbed, at a ' 'horizontal level or in a horizontal layer, in a continuous or ' 'non-continuous interval for simulated (synthetic) satellite data'}, {'abbr': 65535, 'code': 65535, 'title': 'Missing'})
true
true
f72a562854148934a239bcf74e1945d7133782f2
3,310
py
Python
Chapter05/Chapter_5/Chapter_5_5.py
YMandCL/Hands-On-Deep-Learning-for-Games
0225661409c3bf59ae6b7996c254bb485ebd10cb
[ "MIT" ]
33
2018-12-29T15:39:20.000Z
2022-03-18T14:36:11.000Z
Chapter05/Chapter_5/Chapter_5_5.py
YMandCL/Hands-On-Deep-Learning-for-Games
0225661409c3bf59ae6b7996c254bb485ebd10cb
[ "MIT" ]
4
2019-05-01T08:30:47.000Z
2020-08-14T21:13:53.000Z
Chapter05/Chapter_5/Chapter_5_5.py
YMandCL/Hands-On-Deep-Learning-for-Games
0225661409c3bf59ae6b7996c254bb485ebd10cb
[ "MIT" ]
14
2019-01-13T15:52:08.000Z
2021-10-10T06:14:39.000Z
# -*- coding: utf-8 -*- # source from https://github.com/keon/deep-q-learning/blob/master/dqn.py import random import gym import numpy as np from collections import deque from keras.models import Sequential from keras.layers import Dense from keras.optimizers import Adam EPISODES = 1000 class DQNAgent: def __init__(self, state_size, action_size): self.state_size = state_size self.action_size = action_size self.memory = deque(maxlen=2000) self.gamma = 0.95 # discount rate self.epsilon = 1.0 # exploration rate self.epsilon_min = 0.01 self.epsilon_decay = 0.995 self.learning_rate = 0.001 self.model = self._build_model() def _build_model(self): # Neural Net for Deep-Q learning Model model = Sequential() model.add(Dense(24, input_dim=self.state_size, activation='relu')) model.add(Dense(24, activation='relu')) model.add(Dense(self.action_size, activation='linear')) model.compile(loss='mse', optimizer=Adam(lr=self.learning_rate)) return model def remember(self, state, action, reward, next_state, done): self.memory.append((state, action, reward, next_state, done)) def act(self, state): if np.random.rand() <= self.epsilon: return random.randrange(self.action_size) act_values = self.model.predict(state) return np.argmax(act_values[0]) # returns action def replay(self, batch_size): minibatch = random.sample(self.memory, batch_size) for state, action, reward, next_state, done in minibatch: target = reward if not done: target = (reward + self.gamma * np.amax(self.model.predict(next_state)[0])) target_f = self.model.predict(state) target_f[0][action] = target self.model.fit(state, target_f, epochs=1, verbose=0) if self.epsilon > self.epsilon_min: self.epsilon *= self.epsilon_decay def load(self, name): self.model.load_weights(name) def save(self, name): self.model.save_weights(name) if __name__ == "__main__": env = gym.make('MountainCar-v0') state_size = env.observation_space.shape[0] action_size = env.action_space.n agent = DQNAgent(state_size, action_size) # agent.load("./save/cartpole-dqn.h5") done = False batch_size = 32 for e in range(EPISODES): state = env.reset() state = np.reshape(state, [1, state_size]) for time in range(500): # env.render() action = agent.act(state) env.render() next_state, reward, done, _ = env.step(action) reward = reward if not done else -10 next_state = np.reshape(next_state, [1, state_size]) agent.remember(state, action, reward, next_state, done) state = next_state if done: print("episode: {}/{}, score: {}, e: {:.2}" .format(e, EPISODES, time, agent.epsilon)) break if len(agent.memory) > batch_size: agent.replay(batch_size) # if e % 10 == 0: # agent.save("./save/cartpole-dqn.h5")
35.978261
74
0.600302
import random import gym import numpy as np from collections import deque from keras.models import Sequential from keras.layers import Dense from keras.optimizers import Adam EPISODES = 1000 class DQNAgent: def __init__(self, state_size, action_size): self.state_size = state_size self.action_size = action_size self.memory = deque(maxlen=2000) self.gamma = 0.95 self.epsilon = 1.0 self.epsilon_min = 0.01 self.epsilon_decay = 0.995 self.learning_rate = 0.001 self.model = self._build_model() def _build_model(self): model = Sequential() model.add(Dense(24, input_dim=self.state_size, activation='relu')) model.add(Dense(24, activation='relu')) model.add(Dense(self.action_size, activation='linear')) model.compile(loss='mse', optimizer=Adam(lr=self.learning_rate)) return model def remember(self, state, action, reward, next_state, done): self.memory.append((state, action, reward, next_state, done)) def act(self, state): if np.random.rand() <= self.epsilon: return random.randrange(self.action_size) act_values = self.model.predict(state) return np.argmax(act_values[0]) def replay(self, batch_size): minibatch = random.sample(self.memory, batch_size) for state, action, reward, next_state, done in minibatch: target = reward if not done: target = (reward + self.gamma * np.amax(self.model.predict(next_state)[0])) target_f = self.model.predict(state) target_f[0][action] = target self.model.fit(state, target_f, epochs=1, verbose=0) if self.epsilon > self.epsilon_min: self.epsilon *= self.epsilon_decay def load(self, name): self.model.load_weights(name) def save(self, name): self.model.save_weights(name) if __name__ == "__main__": env = gym.make('MountainCar-v0') state_size = env.observation_space.shape[0] action_size = env.action_space.n agent = DQNAgent(state_size, action_size) done = False batch_size = 32 for e in range(EPISODES): state = env.reset() state = np.reshape(state, [1, state_size]) for time in range(500): action = agent.act(state) env.render() next_state, reward, done, _ = env.step(action) reward = reward if not done else -10 next_state = np.reshape(next_state, [1, state_size]) agent.remember(state, action, reward, next_state, done) state = next_state if done: print("episode: {}/{}, score: {}, e: {:.2}" .format(e, EPISODES, time, agent.epsilon)) break if len(agent.memory) > batch_size: agent.replay(batch_size)
true
true
f72a56bc327beb68eaff0e6ebaf52a3e7b6095e4
1,956
py
Python
fastseq/ops/ngram_repeat_block.py
nttcs-ds/fastseq
f1338f1125612df318c9d1f030a8457397ed05a6
[ "MIT" ]
346
2020-11-28T14:25:21.000Z
2022-03-25T14:50:22.000Z
fastseq/ops/ngram_repeat_block.py
nttcs-ds/fastseq
f1338f1125612df318c9d1f030a8457397ed05a6
[ "MIT" ]
22
2020-12-03T18:52:04.000Z
2022-02-26T05:19:14.000Z
fastseq/ops/ngram_repeat_block.py
nttcs-ds/fastseq
f1338f1125612df318c9d1f030a8457397ed05a6
[ "MIT" ]
35
2020-11-30T21:37:45.000Z
2022-03-23T01:54:51.000Z
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. """ Wrapper for ngram_repeat_block cuda extension """ from torch import nn from torch.autograd import Function import ngram_repeat_block_cuda class NGramRepeatBlockFunction(Function): """ forward inputs to ngram_repeat_block cuda extension backward method not needed. """ def forward(self, tokens, lprobs, bsz, step, beam_size, no_repeat_ngram_size): """ Args: tokens(Tensor): Input tokens(Bsz*beam, seq_len) lprobs(Tensor): likelihood probability Expected to be updated in place.(Bsz*beam, vocab_size) bsz(int): batch size step(int): current step beam_size(int): beam size no_repeat_ngram_size(int): Ngram size """ outputs = ngram_repeat_block_cuda.forward(tokens, lprobs, bsz, step, beam_size, no_repeat_ngram_size) return outputs def backward (*args): raise NotImplementedError class NGramRepeatBlock(nn.Module): """ Wrapper class for calling ngram_repeat_block cuda extension """ def __init__(self): super(NGramRepeatBlock, self).__init__() def reset_parameters(self): pass def forward(self, tokens, lprobs, bsz, step, beam_size, no_repeat_ngram_size): """ Args: tokens(Tensor): Input tokens(Bsz*beam, seq_len) lprobs(Tensor): likelihood probability, Expected to be updated in place.(Bsz*beam, vocab_size) bsz(int): batch size step(int): current step beam_size(int): beam size no_repeat_ngram_size(int): Ngram size """ assert tokens.size(0) == bsz*beam_size assert lprobs.size(0) == bsz*beam_size tokens = tokens.contiguous() lprobs = lprobs.contiguous() return NGramRepeatBlockFunction.apply(tokens, lprobs, bsz, step, beam_size, no_repeat_ngram_size)
32.6
71
0.657975
from torch import nn from torch.autograd import Function import ngram_repeat_block_cuda class NGramRepeatBlockFunction(Function): def forward(self, tokens, lprobs, bsz, step, beam_size, no_repeat_ngram_size): outputs = ngram_repeat_block_cuda.forward(tokens, lprobs, bsz, step, beam_size, no_repeat_ngram_size) return outputs def backward (*args): raise NotImplementedError class NGramRepeatBlock(nn.Module): def __init__(self): super(NGramRepeatBlock, self).__init__() def reset_parameters(self): pass def forward(self, tokens, lprobs, bsz, step, beam_size, no_repeat_ngram_size): assert tokens.size(0) == bsz*beam_size assert lprobs.size(0) == bsz*beam_size tokens = tokens.contiguous() lprobs = lprobs.contiguous() return NGramRepeatBlockFunction.apply(tokens, lprobs, bsz, step, beam_size, no_repeat_ngram_size)
true
true
f72a57059f2c092dba9f5b18eb5c0724c3267d04
3,464
py
Python
app/cito_engine/views/tools.py
twatchy/cito_engine
a62dce3c76567dd36b7efcaa70e03728b335f44e
[ "Apache-2.0" ]
null
null
null
app/cito_engine/views/tools.py
twatchy/cito_engine
a62dce3c76567dd36b7efcaa70e03728b335f44e
[ "Apache-2.0" ]
null
null
null
app/cito_engine/views/tools.py
twatchy/cito_engine
a62dce3c76567dd36b7efcaa70e03728b335f44e
[ "Apache-2.0" ]
null
null
null
"""Copyright 2014 Cyrus Dasadia 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 django.shortcuts import redirect, render_to_response from django.forms.formsets import formset_factory from django.contrib.auth.decorators import login_required from django.template import RequestContext from cito_engine.forms import tools_form, events @login_required(login_url='/login/') def bulk_upload_events(request): BulkEventsFormset = formset_factory(events.EventForm, extra=0) render_vars = dict() if request.method != 'POST': return redirect('/incidents/') else: # If we got a bunch of lines for events if 'list_of_items' in request.POST: list_of_events = request.POST.get('list_of_items') severity = request.POST.get('severity') category = request.POST.get('category') team = request.POST.get('team') initial_data = [] if list_of_events: for event_summary in list_of_events.splitlines(): initial_data.append({'summary': event_summary, 'description': event_summary, 'severity': severity, 'team': team, 'category': category, }) render_vars['formset'] = BulkEventsFormset(initial=initial_data) else: render_vars['errors'] = ['List was empty!'] # We got the formset elif 'form-INITIAL_FORMS' in request.POST: render_vars['formset'] = BulkEventsFormset(request.POST) user_teams = request.user.team_set.all() if render_vars['formset'].is_valid(): for form in render_vars['formset']: if form.cleaned_data.get('team') not in user_teams: render_vars['errors'] = ['Cannot add event for %s, you are not a member of this team.' % form.cleaned_data.get('team')] return render_to_response('bulk_upload.html', render_vars, context_instance=RequestContext(request)) else: form.save() return redirect('/events/') return render_to_response('bulk_upload.html', render_vars, context_instance=RequestContext(request)) @login_required(login_url='/login/') def show_bulk_upload_form(request, upload_item): form = tools_form.BulkUploadForm() render_vars = dict() render_vars['form'] = form render_vars['box_title'] = 'Bulk add events' render_vars['page_title'] = 'Bulk add events' if upload_item == 'events': render_vars['form_action'] = '/tools/bulkupload/events/confirm/' return render_to_response('generic_form.html', render_vars, context_instance=RequestContext(request))
44.987013
112
0.618938
from django.shortcuts import redirect, render_to_response from django.forms.formsets import formset_factory from django.contrib.auth.decorators import login_required from django.template import RequestContext from cito_engine.forms import tools_form, events @login_required(login_url='/login/') def bulk_upload_events(request): BulkEventsFormset = formset_factory(events.EventForm, extra=0) render_vars = dict() if request.method != 'POST': return redirect('/incidents/') else: if 'list_of_items' in request.POST: list_of_events = request.POST.get('list_of_items') severity = request.POST.get('severity') category = request.POST.get('category') team = request.POST.get('team') initial_data = [] if list_of_events: for event_summary in list_of_events.splitlines(): initial_data.append({'summary': event_summary, 'description': event_summary, 'severity': severity, 'team': team, 'category': category, }) render_vars['formset'] = BulkEventsFormset(initial=initial_data) else: render_vars['errors'] = ['List was empty!'] elif 'form-INITIAL_FORMS' in request.POST: render_vars['formset'] = BulkEventsFormset(request.POST) user_teams = request.user.team_set.all() if render_vars['formset'].is_valid(): for form in render_vars['formset']: if form.cleaned_data.get('team') not in user_teams: render_vars['errors'] = ['Cannot add event for %s, you are not a member of this team.' % form.cleaned_data.get('team')] return render_to_response('bulk_upload.html', render_vars, context_instance=RequestContext(request)) else: form.save() return redirect('/events/') return render_to_response('bulk_upload.html', render_vars, context_instance=RequestContext(request)) @login_required(login_url='/login/') def show_bulk_upload_form(request, upload_item): form = tools_form.BulkUploadForm() render_vars = dict() render_vars['form'] = form render_vars['box_title'] = 'Bulk add events' render_vars['page_title'] = 'Bulk add events' if upload_item == 'events': render_vars['form_action'] = '/tools/bulkupload/events/confirm/' return render_to_response('generic_form.html', render_vars, context_instance=RequestContext(request))
true
true
f72a587cdb19c1c9ab6d907b4c8b9dbcba84d995
3,925
py
Python
ros/src/twist_controller/dbw_test.py
kenji-miyake/udacity-CarND-term2-Capstone
e50e826c9700a2bc549e809e2548b1a6d686012c
[ "MIT" ]
null
null
null
ros/src/twist_controller/dbw_test.py
kenji-miyake/udacity-CarND-term2-Capstone
e50e826c9700a2bc549e809e2548b1a6d686012c
[ "MIT" ]
null
null
null
ros/src/twist_controller/dbw_test.py
kenji-miyake/udacity-CarND-term2-Capstone
e50e826c9700a2bc549e809e2548b1a6d686012c
[ "MIT" ]
null
null
null
#!/usr/bin/env python import os import csv import rospy from std_msgs.msg import Bool from dbw_mkz_msgs.msg import ThrottleCmd, SteeringCmd, BrakeCmd, SteeringReport ''' You can use this file to test your DBW code against a bag recorded with a reference implementation. The bag can be found at https://s3-us-west-1.amazonaws.com/udacity-selfdrivingcar/files/reference.bag.zip To use the downloaded bag file, rename it to 'dbw_test.rosbag.bag' and place it in the CarND-Capstone/data folder. Then with roscore running, you can then use roslaunch with the dbw_test.launch file found in <project_repo>/ros/src/twist_controller/launch. This file will produce 3 csv files which you can process to figure out how your DBW node is performing on various commands. `/actual/*` are commands from the recorded bag while `/vehicle/*` are the output of your node. ''' class DBWTestNode(object): def __init__(self): rospy.init_node('dbw_test_node') rospy.Subscriber('/vehicle/steering_cmd', SteeringCmd, self.steer_cb) rospy.Subscriber('/vehicle/throttle_cmd', ThrottleCmd, self.throttle_cb) rospy.Subscriber('/vehicle/brake_cmd', BrakeCmd, self.brake_cb) rospy.Subscriber('/actual/steering_cmd', SteeringCmd, self.actual_steer_cb) rospy.Subscriber('/actual/throttle_cmd', ThrottleCmd, self.actual_throttle_cb) rospy.Subscriber('/actual/brake_cmd', BrakeCmd, self.actual_brake_cb) rospy.Subscriber('/vehicle/dbw_enabled', Bool, self.dbw_enabled_cb) self.steer = self.throttle = self.brake = None self.steer_data = [] self.throttle_data = [] self.brake_data = [] self.dbw_enabled = False base_path = os.path.dirname(os.path.abspath(__file__)) self.steerfile = os.path.join(base_path, 'steers.csv') self.throttlefile = os.path.join(base_path, 'throttles.csv') self.brakefile = os.path.join(base_path, 'brakes.csv') self.loop() def loop(self): rate = rospy.Rate(10) # 10Hz while not rospy.is_shutdown(): rate.sleep() fieldnames = ['actual', 'proposed'] with open(self.steerfile, 'w') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() writer.writerows(self.steer_data) with open(self.throttlefile, 'w') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() writer.writerows(self.throttle_data) with open(self.brakefile, 'w') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() writer.writerows(self.brake_data) def dbw_enabled_cb(self, msg): self.dbw_enabled = msg.data def steer_cb(self, msg): self.steer = msg.steering_wheel_angle_cmd def throttle_cb(self, msg): self.throttle = msg.pedal_cmd def brake_cb(self, msg): self.brake = msg.pedal_cmd def actual_steer_cb(self, msg): if self.dbw_enabled and self.steer is not None: self.steer_data.append({'actual': msg.steering_wheel_angle_cmd, 'proposed': self.steer}) self.steer = None def actual_throttle_cb(self, msg): if self.dbw_enabled and self.throttle is not None: self.throttle_data.append({'actual': msg.pedal_cmd, 'proposed': self.throttle}) self.throttle = None def actual_brake_cb(self, msg): if self.dbw_enabled and self.brake is not None: self.brake_data.append({'actual': msg.pedal_cmd, 'proposed': self.brake}) self.brake = None if __name__ == '__main__': DBWTestNode()
34.734513
114
0.644076
import os import csv import rospy from std_msgs.msg import Bool from dbw_mkz_msgs.msg import ThrottleCmd, SteeringCmd, BrakeCmd, SteeringReport class DBWTestNode(object): def __init__(self): rospy.init_node('dbw_test_node') rospy.Subscriber('/vehicle/steering_cmd', SteeringCmd, self.steer_cb) rospy.Subscriber('/vehicle/throttle_cmd', ThrottleCmd, self.throttle_cb) rospy.Subscriber('/vehicle/brake_cmd', BrakeCmd, self.brake_cb) rospy.Subscriber('/actual/steering_cmd', SteeringCmd, self.actual_steer_cb) rospy.Subscriber('/actual/throttle_cmd', ThrottleCmd, self.actual_throttle_cb) rospy.Subscriber('/actual/brake_cmd', BrakeCmd, self.actual_brake_cb) rospy.Subscriber('/vehicle/dbw_enabled', Bool, self.dbw_enabled_cb) self.steer = self.throttle = self.brake = None self.steer_data = [] self.throttle_data = [] self.brake_data = [] self.dbw_enabled = False base_path = os.path.dirname(os.path.abspath(__file__)) self.steerfile = os.path.join(base_path, 'steers.csv') self.throttlefile = os.path.join(base_path, 'throttles.csv') self.brakefile = os.path.join(base_path, 'brakes.csv') self.loop() def loop(self): rate = rospy.Rate(10) while not rospy.is_shutdown(): rate.sleep() fieldnames = ['actual', 'proposed'] with open(self.steerfile, 'w') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() writer.writerows(self.steer_data) with open(self.throttlefile, 'w') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() writer.writerows(self.throttle_data) with open(self.brakefile, 'w') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() writer.writerows(self.brake_data) def dbw_enabled_cb(self, msg): self.dbw_enabled = msg.data def steer_cb(self, msg): self.steer = msg.steering_wheel_angle_cmd def throttle_cb(self, msg): self.throttle = msg.pedal_cmd def brake_cb(self, msg): self.brake = msg.pedal_cmd def actual_steer_cb(self, msg): if self.dbw_enabled and self.steer is not None: self.steer_data.append({'actual': msg.steering_wheel_angle_cmd, 'proposed': self.steer}) self.steer = None def actual_throttle_cb(self, msg): if self.dbw_enabled and self.throttle is not None: self.throttle_data.append({'actual': msg.pedal_cmd, 'proposed': self.throttle}) self.throttle = None def actual_brake_cb(self, msg): if self.dbw_enabled and self.brake is not None: self.brake_data.append({'actual': msg.pedal_cmd, 'proposed': self.brake}) self.brake = None if __name__ == '__main__': DBWTestNode()
true
true
f72a59ba76c94957d9f4a188c1bbef848032ed01
20,211
py
Python
xalpha/cons.py
Razorro/xalpha
bcecd53dc9d081deb1b8235437a4f6b74951c23d
[ "MIT" ]
null
null
null
xalpha/cons.py
Razorro/xalpha
bcecd53dc9d081deb1b8235437a4f6b74951c23d
[ "MIT" ]
null
null
null
xalpha/cons.py
Razorro/xalpha
bcecd53dc9d081deb1b8235437a4f6b74951c23d
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ basic constants and utility functions """ import datetime as dt import os import time import logging import inspect from decimal import Decimal import requests from functools import wraps from simplejson.errors import JSONDecodeError import pandas as pd from pyecharts.options import ( AxisOpts, DataZoomOpts, LegendOpts, TooltipOpts, VisualMapOpts, ) from numpy import sqrt from scipy import optimize from xalpha import __path__ from .exceptions import HttpStatusError logger = logging.getLogger(__name__) # date obj of today # today = lambda: dt.datetime.combine(dt.date.today(), dt.time.min) tz_bj = dt.timezone(dt.timedelta(hours=8)) def today_obj(): """ today obj in beijing timezone with no tzinfo :return: datetime.datetime """ now = dt.datetime.now(tz=tz_bj) return now.replace(hour=0, minute=0, second=0, microsecond=0).replace(tzinfo=None) # datetime obj for yesterdate date with time set to be 0:0:0 yesterdayobj = lambda: (dt.datetime.now(tz_bj).replace(tzinfo=None) - dt.timedelta(1)) # string for yesterday, only used for indexinfo url yesterday = lambda: dt.datetime.strftime(yesterdayobj(), "%Y%m%d") # string for yesterday with dash yesterdaydash = lambda: dt.datetime.strftime(yesterdayobj(), "%Y-%m-%d") # list: all the trade date of domestic stock market in the form of string caldate = pd.read_csv(os.path.join(__path__[0], "caldate.csv")) opendate = list(caldate[caldate["is_open"] == 1]["cal_date"]) # opendate = list(ts.trade_cal()[ts.trade_cal()['isOpen']==1]['calendarDate']) opendate_set = set(opendate) # for speed checking? # fund code list which always round down for the purchase share approximation droplist = ["003318", "000311", "000601", "009989"] sqrt_days_in_year = sqrt(250.0) def calendar_selfcheck(): # 国内链接 githubusercontent.com 大概率存在问题,因此设计成联网自动更新日历大概率无用。 # 也许之后考虑一些较稳定的第三方资源托管服务 current_year = dt.datetime.now().year if str(current_year) != opendate[-1][:4]: logger.warning( "Please update xalpha via `pip install -U xalpha` to keep the trade calendar up-to-date" ) print("请更新 xalpha 版本以更新最新年份的 A 股交易日历, 否则将可能无法正确获取和处理最新的基金净值") calendar_selfcheck() region_trans = { "瑞士": "CH", "日本": "JP", "韩国": "KR", "美国": "US", "香港": "HK", "中国香港": "HK", "德国": "DE", "英国": "UK", "法国": "FR", "中国": "CN", "墨西哥": "MX", "澳大利亚": "AU", "新加坡": "SG", "印度": "IN", "台湾": "TW", "中国台湾": "TW", } # extract from xa.misc.get_tdx_holidays holidays = { "AU": [ "2020-01-01", "2020-01-27", "2020-04-10", "2020-04-13", "2020-04-25", "2020-06-08", "2020-12-24", "2020-12-25", "2020-12-28", "2020-12-31", "2021-01-01", "2021-01-26", "2021-04-02", "2021-04-05", "2021-06-14", "2021-12-24", "2021-12-27", "2021-12-28", "2021-12-31", ], "CH": [ "2020-01-01", "2020-01-02", "2020-04-10", "2020-04-13", "2020-05-01", "2020-05-21", "2020-06-01", "2020-12-24", "2020-12-25", "2020-12-31", "2021-01-01", "2021-04-02", "2021-04-05", "2021-05-13", "2021-05-24", "2021-12-24", "2021-12-31", ], "CN": [ "2020-01-01", "2020-01-24", "2020-01-27", "2020-01-28", "2020-01-29", "2020-01-30", "2020-01-31", "2020-04-06", "2020-05-01", "2020-05-04", "2020-05-05", "2020-06-25", "2020-06-26", "2020-10-01", "2020-10-02", "2020-10-05", "2020-10-06", "2020-10-07", "2020-10-08", "2021-01-01", "2021-02-11", "2021-02-12", "2021-02-15", "2021-02-16", "2021-02-17", "2021-04-05", "2021-05-03", "2021-05-04", "2021-05-05", "2021-06-14", "2021-09-20", "2021-09-21", "2021-10-01", "2021-10-04", "2021-10-05", "2021-10-06", "2021-10-07", ], "DE": [ "2020-01-01", "2020-04-10", "2020-04-13", "2020-05-01", "2020-06-01", "2020-12-24", "2020-12-25", "2020-12-31", "2021-01-01", "2021-04-02", "2021-04-05", "2021-05-24", "2021-12-24", "2021-12-31", ], "FR": [ "2020-01-01", "2020-04-10", "2020-04-13", "2020-05-01", "2020-12-24", "2020-12-25", "2020-12-31", "2021-01-01", "2021-04-02", "2021-04-05", "2021-12-24", "2021-12-31", ], "HK": [ "2020-01-01", "2020-01-27", "2020-01-28", "2020-04-10", "2020-04-13", "2020-04-30", "2020-05-01", "2020-06-25", "2020-07-01", "2020-10-01", "2020-10-02", "2020-10-26", "2020-12-25", "2021-01-01", "2021-02-11", "2021-02-12", "2021-02-15", "2021-04-02", "2021-04-05", "2021-04-06", "2021-05-19", "2021-06-14", "2021-07-01", "2021-09-22", "2021-10-01", "2021-10-14", "2021-12-24", "2021-12-27", "2021-12-31", ], "IN": [ "2020-02-21", "2020-03-10", "2020-04-02", "2020-04-06", "2020-04-10", "2020-04-14", "2020-05-01", "2020-05-25", "2020-10-02", "2020-11-16", "2020-11-30", "2020-12-25", "2021-01-26", "2021-03-11", "2021-03-29", "2021-04-02", "2021-04-14", "2021-04-21", "2021-05-13", "2021-07-20", "2021-08-19", "2021-09-10", "2021-10-15", "2021-11-04", "2021-11-19", ], "JP": [ "2020-01-01", "2020-01-02", "2020-01-03", "2020-01-13", "2020-02-11", "2020-02-24", "2020-03-20", "2020-04-29", "2020-05-04", "2020-05-05", "2020-05-06", "2020-07-23", "2020-07-24", "2020-08-10", "2020-09-21", "2020-09-22", "2020-11-03", "2020-11-23", "2020-12-31", "2021-01-01", "2021-01-11", "2021-02-11", "2021-02-23", "2021-04-29", "2021-05-03", "2021-05-04", "2021-05-05", "2021-07-22", "2021-07-23", "2021-08-09", "2021-09-20", "2021-09-23", "2021-11-03", "2021-11-23", "2021-12-31", ], "KR": [ "2020-01-01", "2020-01-24", "2020-01-27", "2020-04-30", "2020-05-01", "2020-05-05", "2020-09-30", "2020-10-01", "2020-10-02", "2020-10-09", "2020-12-25", "2020-12-31", "2021-01-01", "2021-02-11", "2021-02-12", "2021-03-01", "2021-05-05", "2021-05-19", "2021-09-20", "2021-09-21", "2021-09-22", "2021-12-31", ], "SG": [ "2020-01-01", "2020-01-24", "2020-04-10", "2020-05-01", "2020-05-07", "2020-05-21", "2020-07-31", "2020-08-10", "2020-12-24", "2020-12-25", "2020-12-31", "2021-01-01", "2021-02-11", "2021-02-12", "2021-04-02", "2021-05-13", "2021-05-26", "2021-07-20", "2021-08-09", "2021-11-04", "2021-12-24", "2021-12-31", ], "TW": [ "2020-01-01", "2020-01-21", "2020-01-22", "2020-01-23", "2020-01-24", "2020-01-27", "2020-01-28", "2020-01-29", "2020-02-28", "2020-04-02", "2020-04-03", "2020-05-01", "2020-06-25", "2020-06-26", "2020-10-01", "2020-10-02", "2020-10-09", "2021-01-01", "2021-02-08", "2021-02-09", "2021-02-10", "2021-02-11", "2021-02-12", "2021-02-15", "2021-02-16", "2021-03-01", "2021-04-02", "2021-04-05", "2021-04-30", "2021-06-14", "2021-09-20", "2021-09-21", "2021-10-11", "2021-12-31", ], "UK": [ "2020-01-01", "2020-04-10", "2020-04-13", "2020-05-08", "2020-05-25", "2020-08-31", "2020-12-24", "2020-12-25", "2020-12-28", "2020-12-31", "2021-01-01", "2021-01-01", "2021-04-02", "2021-04-05", "2021-05-03", "2021-05-31", "2021-08-30", "2021-12-24", "2021-12-27", "2021-12-28", "2021-12-31", "2022-01-03", ], "US": [ "2020-01-01", "2020-01-20", "2020-02-17", "2020-03-08", "2020-04-10", "2020-05-25", "2020-07-03", "2020-09-07", "2020-11-01", "2020-11-26", "2020-11-27", "2020-12-24", "2020-12-25", "2021-01-01", "2021-01-01", "2021-01-18", "2021-02-15", "2021-03-14", "2021-04-02", "2021-05-31", "2021-07-05", "2021-09-06", "2021-11-07", "2021-11-25", "2021-11-26", "2021-12-24", ], } connection_errors = ( HttpStatusError, ConnectionResetError, requests.exceptions.RequestException, requests.exceptions.ConnectionError, requests.exceptions.SSLError, JSONDecodeError, ) line_opts = { "datazoom_opts": [ DataZoomOpts(is_show=True, type_="slider", range_start=50, range_end=100), DataZoomOpts( is_show=True, type_="slider", orient="vertical", range_start=50, range_end=100, ), ], "tooltip_opts": TooltipOpts( is_show=True, trigger="axis", trigger_on="mousemove", axis_pointer_type="cross" ), } heatmap_opts = { "visualmap_opts": VisualMapOpts( min_=-1, max_=1, orient="horizontal", pos_right="middle", pos_top="bottom" ) } # pie_opts = { # "tooltip_opts": TooltipOpts(), # "legend_opts": LegendOpts(orient="vertical", pos_left="left"), # } themeriver_opts = { "xaxis_opts": AxisOpts(type_="time"), "datazoom_opts": [DataZoomOpts(range_start=60, range_end=100)], "tooltip_opts": TooltipOpts(trigger_on="mousemove", trigger="item"), "legend_opts": LegendOpts(pos_top="top"), } def xnpv(rate, cashflows): """ give the current cash value based on future cashflows :param rate: float, the preset year rate :param cashflows: a list, in which each element is a tuple of the form (date, amount), where date is a datetime object and amount is an integer or floating number. Cash outflows (investments) are represented with negative amounts, and cash inflows (returns) are positive amounts. :returns: a single float value which is the NPV of the given cash flows """ chron_order = sorted(cashflows, key=lambda x: x[0]) t0 = chron_order[0][0] return sum([cf / (1 + rate) ** ((t - t0).days / 365.0) for (t, cf) in chron_order]) def xirr(cashflows, guess=0.1): """ calculate the Internal Rate of Return of a series of cashflows at irregular intervals. :param cashflows: a list, in which each element is a tuple of the form (date, amount), where date is a datetime object and amount is an integer or floating number. Cash outflows (investments) are represented with negative amounts, and cash inflows (returns) are positive amounts. :param guess: floating number, a guess at the xirr rate solution to be used as a starting point for the numerical solution :returns: the IRR as a single floating number """ return optimize.newton(lambda r: xnpv(r, cashflows), guess) def myround(num, label=1): """ correct implementation of round with round half up, round to 2 decimals :param num: the floating number, to be rounded :param label: integer 1 or 2, 1 for round half up while 2 for always round down :returns: the float number after rounding, with two decimals """ if label == 1: res = float( Decimal(str(num)).quantize(Decimal("0.01"), rounding="ROUND_HALF_UP") ) elif ( label == 2 ): # for jingshunchangcheng... who just omit the overflow share behind 2 decimal res = float(Decimal(str(num)).quantize(Decimal("0.01"), rounding="ROUND_DOWN")) return res def convert_date(date): """ convert date into datetime object :param date: string of form '2017-01-01' or datetime object :returns: corresponding datetime object """ if isinstance(date, str): return pd.Timestamp(date) else: return date def _date_check(dtobj, check=False): if not isinstance(dtobj, dt.datetime): dtobj = dt.datetime.strptime(dtobj.replace("/", "").replace("-", ""), "%Y%m%d") if check and (dtobj.year > dt.datetime.now().year or dtobj.year < 1991): raise ValueError( "date goes beyond market range: %s" % dtobj.strftime("%Y-%m-%d") ) return dtobj def next_onday(dtobj): dtobj = _date_check(dtobj, check=True) dtobj += dt.timedelta(1) while dtobj.strftime("%Y-%m-%d") not in opendate_set: dtobj += dt.timedelta(1) return dtobj def last_onday(dtobj): dtobj = _date_check(dtobj, check=True) dtobj -= dt.timedelta(1) while dtobj.strftime("%Y-%m-%d") not in opendate_set: dtobj -= dt.timedelta(1) return dtobj def avail_dates(dtlist, future=False): """ make every day in the list the next open day :param dtlist: datetime obj list :param future: bool, default False, indicating the latest day in the list is yesterday :return: datetime obj list """ ndtlist = [] for d in dtlist: if d.strftime("%Y-%m-%d") not in opendate_set: nd = next_onday(d) else: nd = d if future is False: if (nd - yesterdayobj()).days > 0: continue ndtlist.append(nd) return ndtlist def scale_dict(d, scale=1, ulimit=100, dlimit=50, aim=None): t = sum([v for _, v in d.items()]) if t * scale > ulimit: scale = ulimit / t elif t * scale < dlimit: scale = dlimit / t if aim: scale = aim / t for k, v in d.items(): d[k] = v * scale return d def _float(n): try: n = n.replace(",", "") if n.endswith("K") or n.endswith("k"): n = float(n[:-1]) * 1000 elif n.endswith("M") or n.endswith("m"): n = float(n[:-1]) * 1000 * 1000 elif n.endswith("G") or n.endswith("g") or n.endswith("B") or n.endswith("b"): n = float(n[:-1]) * 1000 * 1000 * 1000 elif n == "-": logger.info("_float met -, taken as 0") return 0 elif n.endswith("%"): logger.info("_float met with %% as %s" % n) return float(n[:-1]) / 100 except AttributeError: pass if not n: logger.info("_float met with None as input arguments") return 0.0 return float(n) def reconnect(tries=5, timeout=12): def robustify(f): default_header = { 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,' 'application/signed-exchange;v=b3;q=0.9', 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6,ja;q=0.5', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/89.0.4389.114 Safari/537.36 Edg/89.0.774.76', } @wraps(f) def wrapper(*args, **kws): import xalpha.provider as xp if getattr(xp, "proxy", None): kws["proxies"] = {"http": xp.proxy, "https": xp.proxy} kws["timeout"] = timeout logger.debug("Using proxy %s" % xp.proxy) if args: url = args[0] else: url = kws.get("url", "") headers = kws.get("headers", {}) if len(headers) == 0: headers.update(default_header) kws["headers"] = headers for count in range(tries): try: logger.debug("Fetching url: %s . Inside function `%s`" % (url, inspect.stack()[1].function)) r = f(*args, **kws) if getattr(r, "status_code", 200) != 200: # in case r is a json dict raise HttpStatusError return r except connection_errors as e: logger.warning("Fails at fetching url: %s. Try again." % url) if count == tries - 1: logger.error("Still wrong at fetching url: %s. after %s tries." % (url, tries)) logger.error("Fails due to %s" % e.args[0]) raise e time.sleep(0.5 * count) return wrapper return robustify rget = reconnect()(requests.get) rpost = reconnect()(requests.post) @reconnect() def rget_json(*args, **kws): r = requests.get(*args, **kws) return r.json() @reconnect() def rpost_json(*args, **kws): r = requests.post(*args, **kws) return r.json() # def rget(*args, **kws): # tries = 5 # for count in range(tries): # try: # r = requests.get(*args, **kws) # return r # except connection_errors as e: # if count == tries - 1: # print(*args, sep="\n") # print("still wrong after several tries") # raise e # time.sleep(0.5*count) # # # def rget_json(*args, **kws): # tries = 5 # for count in range(tries): # try: # r = requests.get(*args, **kws) # return r.json() # except connection_errors as e: # if count == tries - 1: # print(*args, sep="\n") # print("still wrong after several tries") # raise e # time.sleep(0.5*count) # # # def rpost(*args, **kws): # tries = 5 # for count in range(tries): # try: # r = requests.post(*args, **kws) # return r # except connection_errors as e: # if count == tries - 1: # print(*args, sep="\n") # print("still wrong after several tries") # raise e # time.sleep(0.5*count) # # # def rpost_json(*args, **kws): # tries = 5 # for count in range(tries): # try: # r = requests.post(*args, **kws) # return r.json() # except connection_errors as e: # if count == tries - 1: # print(*args, sep="\n") # print("still wrong after several tries") # raise e # time.sleep(0.5*count) ## simple subsitution for holdings.py holdings = {} holdings["501018"] = { "etfs/etfs-brent-1mth-uk": 17.51, "etfs/etfs-brent-crude": 15.04, "etfs/etfs-crude-oil": 7.34, "etfs/ipath-series-b-sp-gsci-crd-oil-tr": 0.06, "etfs/powershares-db-oil-fund": 11.6, "etfs/ubs-cmci-oil-sf-usd": 8.68, "etfs/united-states-12-month-oil": 8.14, "etfs/united-states-brent-oil-fund-lp": 15.42, "etfs/united-states-oil-fund": 9.63, } holdings["501018rt"] = { "commodities/brent-oil": {"weight": 49, "time": -1}, "commodities/crude-oil": {"weight": 45, "time": 4}, }
25.978149
112
0.502647
import datetime as dt import os import time import logging import inspect from decimal import Decimal import requests from functools import wraps from simplejson.errors import JSONDecodeError import pandas as pd from pyecharts.options import ( AxisOpts, DataZoomOpts, LegendOpts, TooltipOpts, VisualMapOpts, ) from numpy import sqrt from scipy import optimize from xalpha import __path__ from .exceptions import HttpStatusError logger = logging.getLogger(__name__) tz_bj = dt.timezone(dt.timedelta(hours=8)) def today_obj(): now = dt.datetime.now(tz=tz_bj) return now.replace(hour=0, minute=0, second=0, microsecond=0).replace(tzinfo=None) yesterdayobj = lambda: (dt.datetime.now(tz_bj).replace(tzinfo=None) - dt.timedelta(1)) yesterday = lambda: dt.datetime.strftime(yesterdayobj(), "%Y%m%d") yesterdaydash = lambda: dt.datetime.strftime(yesterdayobj(), "%Y-%m-%d") caldate = pd.read_csv(os.path.join(__path__[0], "caldate.csv")) opendate = list(caldate[caldate["is_open"] == 1]["cal_date"]) opendate_set = set(opendate) droplist = ["003318", "000311", "000601", "009989"] sqrt_days_in_year = sqrt(250.0) def calendar_selfcheck(): current_year = dt.datetime.now().year if str(current_year) != opendate[-1][:4]: logger.warning( "Please update xalpha via `pip install -U xalpha` to keep the trade calendar up-to-date" ) print("请更新 xalpha 版本以更新最新年份的 A 股交易日历, 否则将可能无法正确获取和处理最新的基金净值") calendar_selfcheck() region_trans = { "瑞士": "CH", "日本": "JP", "韩国": "KR", "美国": "US", "香港": "HK", "中国香港": "HK", "德国": "DE", "英国": "UK", "法国": "FR", "中国": "CN", "墨西哥": "MX", "澳大利亚": "AU", "新加坡": "SG", "印度": "IN", "台湾": "TW", "中国台湾": "TW", } holidays = { "AU": [ "2020-01-01", "2020-01-27", "2020-04-10", "2020-04-13", "2020-04-25", "2020-06-08", "2020-12-24", "2020-12-25", "2020-12-28", "2020-12-31", "2021-01-01", "2021-01-26", "2021-04-02", "2021-04-05", "2021-06-14", "2021-12-24", "2021-12-27", "2021-12-28", "2021-12-31", ], "CH": [ "2020-01-01", "2020-01-02", "2020-04-10", "2020-04-13", "2020-05-01", "2020-05-21", "2020-06-01", "2020-12-24", "2020-12-25", "2020-12-31", "2021-01-01", "2021-04-02", "2021-04-05", "2021-05-13", "2021-05-24", "2021-12-24", "2021-12-31", ], "CN": [ "2020-01-01", "2020-01-24", "2020-01-27", "2020-01-28", "2020-01-29", "2020-01-30", "2020-01-31", "2020-04-06", "2020-05-01", "2020-05-04", "2020-05-05", "2020-06-25", "2020-06-26", "2020-10-01", "2020-10-02", "2020-10-05", "2020-10-06", "2020-10-07", "2020-10-08", "2021-01-01", "2021-02-11", "2021-02-12", "2021-02-15", "2021-02-16", "2021-02-17", "2021-04-05", "2021-05-03", "2021-05-04", "2021-05-05", "2021-06-14", "2021-09-20", "2021-09-21", "2021-10-01", "2021-10-04", "2021-10-05", "2021-10-06", "2021-10-07", ], "DE": [ "2020-01-01", "2020-04-10", "2020-04-13", "2020-05-01", "2020-06-01", "2020-12-24", "2020-12-25", "2020-12-31", "2021-01-01", "2021-04-02", "2021-04-05", "2021-05-24", "2021-12-24", "2021-12-31", ], "FR": [ "2020-01-01", "2020-04-10", "2020-04-13", "2020-05-01", "2020-12-24", "2020-12-25", "2020-12-31", "2021-01-01", "2021-04-02", "2021-04-05", "2021-12-24", "2021-12-31", ], "HK": [ "2020-01-01", "2020-01-27", "2020-01-28", "2020-04-10", "2020-04-13", "2020-04-30", "2020-05-01", "2020-06-25", "2020-07-01", "2020-10-01", "2020-10-02", "2020-10-26", "2020-12-25", "2021-01-01", "2021-02-11", "2021-02-12", "2021-02-15", "2021-04-02", "2021-04-05", "2021-04-06", "2021-05-19", "2021-06-14", "2021-07-01", "2021-09-22", "2021-10-01", "2021-10-14", "2021-12-24", "2021-12-27", "2021-12-31", ], "IN": [ "2020-02-21", "2020-03-10", "2020-04-02", "2020-04-06", "2020-04-10", "2020-04-14", "2020-05-01", "2020-05-25", "2020-10-02", "2020-11-16", "2020-11-30", "2020-12-25", "2021-01-26", "2021-03-11", "2021-03-29", "2021-04-02", "2021-04-14", "2021-04-21", "2021-05-13", "2021-07-20", "2021-08-19", "2021-09-10", "2021-10-15", "2021-11-04", "2021-11-19", ], "JP": [ "2020-01-01", "2020-01-02", "2020-01-03", "2020-01-13", "2020-02-11", "2020-02-24", "2020-03-20", "2020-04-29", "2020-05-04", "2020-05-05", "2020-05-06", "2020-07-23", "2020-07-24", "2020-08-10", "2020-09-21", "2020-09-22", "2020-11-03", "2020-11-23", "2020-12-31", "2021-01-01", "2021-01-11", "2021-02-11", "2021-02-23", "2021-04-29", "2021-05-03", "2021-05-04", "2021-05-05", "2021-07-22", "2021-07-23", "2021-08-09", "2021-09-20", "2021-09-23", "2021-11-03", "2021-11-23", "2021-12-31", ], "KR": [ "2020-01-01", "2020-01-24", "2020-01-27", "2020-04-30", "2020-05-01", "2020-05-05", "2020-09-30", "2020-10-01", "2020-10-02", "2020-10-09", "2020-12-25", "2020-12-31", "2021-01-01", "2021-02-11", "2021-02-12", "2021-03-01", "2021-05-05", "2021-05-19", "2021-09-20", "2021-09-21", "2021-09-22", "2021-12-31", ], "SG": [ "2020-01-01", "2020-01-24", "2020-04-10", "2020-05-01", "2020-05-07", "2020-05-21", "2020-07-31", "2020-08-10", "2020-12-24", "2020-12-25", "2020-12-31", "2021-01-01", "2021-02-11", "2021-02-12", "2021-04-02", "2021-05-13", "2021-05-26", "2021-07-20", "2021-08-09", "2021-11-04", "2021-12-24", "2021-12-31", ], "TW": [ "2020-01-01", "2020-01-21", "2020-01-22", "2020-01-23", "2020-01-24", "2020-01-27", "2020-01-28", "2020-01-29", "2020-02-28", "2020-04-02", "2020-04-03", "2020-05-01", "2020-06-25", "2020-06-26", "2020-10-01", "2020-10-02", "2020-10-09", "2021-01-01", "2021-02-08", "2021-02-09", "2021-02-10", "2021-02-11", "2021-02-12", "2021-02-15", "2021-02-16", "2021-03-01", "2021-04-02", "2021-04-05", "2021-04-30", "2021-06-14", "2021-09-20", "2021-09-21", "2021-10-11", "2021-12-31", ], "UK": [ "2020-01-01", "2020-04-10", "2020-04-13", "2020-05-08", "2020-05-25", "2020-08-31", "2020-12-24", "2020-12-25", "2020-12-28", "2020-12-31", "2021-01-01", "2021-01-01", "2021-04-02", "2021-04-05", "2021-05-03", "2021-05-31", "2021-08-30", "2021-12-24", "2021-12-27", "2021-12-28", "2021-12-31", "2022-01-03", ], "US": [ "2020-01-01", "2020-01-20", "2020-02-17", "2020-03-08", "2020-04-10", "2020-05-25", "2020-07-03", "2020-09-07", "2020-11-01", "2020-11-26", "2020-11-27", "2020-12-24", "2020-12-25", "2021-01-01", "2021-01-01", "2021-01-18", "2021-02-15", "2021-03-14", "2021-04-02", "2021-05-31", "2021-07-05", "2021-09-06", "2021-11-07", "2021-11-25", "2021-11-26", "2021-12-24", ], } connection_errors = ( HttpStatusError, ConnectionResetError, requests.exceptions.RequestException, requests.exceptions.ConnectionError, requests.exceptions.SSLError, JSONDecodeError, ) line_opts = { "datazoom_opts": [ DataZoomOpts(is_show=True, type_="slider", range_start=50, range_end=100), DataZoomOpts( is_show=True, type_="slider", orient="vertical", range_start=50, range_end=100, ), ], "tooltip_opts": TooltipOpts( is_show=True, trigger="axis", trigger_on="mousemove", axis_pointer_type="cross" ), } heatmap_opts = { "visualmap_opts": VisualMapOpts( min_=-1, max_=1, orient="horizontal", pos_right="middle", pos_top="bottom" ) } themeriver_opts = { "xaxis_opts": AxisOpts(type_="time"), "datazoom_opts": [DataZoomOpts(range_start=60, range_end=100)], "tooltip_opts": TooltipOpts(trigger_on="mousemove", trigger="item"), "legend_opts": LegendOpts(pos_top="top"), } def xnpv(rate, cashflows): chron_order = sorted(cashflows, key=lambda x: x[0]) t0 = chron_order[0][0] return sum([cf / (1 + rate) ** ((t - t0).days / 365.0) for (t, cf) in chron_order]) def xirr(cashflows, guess=0.1): return optimize.newton(lambda r: xnpv(r, cashflows), guess) def myround(num, label=1): if label == 1: res = float( Decimal(str(num)).quantize(Decimal("0.01"), rounding="ROUND_HALF_UP") ) elif ( label == 2 ): res = float(Decimal(str(num)).quantize(Decimal("0.01"), rounding="ROUND_DOWN")) return res def convert_date(date): if isinstance(date, str): return pd.Timestamp(date) else: return date def _date_check(dtobj, check=False): if not isinstance(dtobj, dt.datetime): dtobj = dt.datetime.strptime(dtobj.replace("/", "").replace("-", ""), "%Y%m%d") if check and (dtobj.year > dt.datetime.now().year or dtobj.year < 1991): raise ValueError( "date goes beyond market range: %s" % dtobj.strftime("%Y-%m-%d") ) return dtobj def next_onday(dtobj): dtobj = _date_check(dtobj, check=True) dtobj += dt.timedelta(1) while dtobj.strftime("%Y-%m-%d") not in opendate_set: dtobj += dt.timedelta(1) return dtobj def last_onday(dtobj): dtobj = _date_check(dtobj, check=True) dtobj -= dt.timedelta(1) while dtobj.strftime("%Y-%m-%d") not in opendate_set: dtobj -= dt.timedelta(1) return dtobj def avail_dates(dtlist, future=False): ndtlist = [] for d in dtlist: if d.strftime("%Y-%m-%d") not in opendate_set: nd = next_onday(d) else: nd = d if future is False: if (nd - yesterdayobj()).days > 0: continue ndtlist.append(nd) return ndtlist def scale_dict(d, scale=1, ulimit=100, dlimit=50, aim=None): t = sum([v for _, v in d.items()]) if t * scale > ulimit: scale = ulimit / t elif t * scale < dlimit: scale = dlimit / t if aim: scale = aim / t for k, v in d.items(): d[k] = v * scale return d def _float(n): try: n = n.replace(",", "") if n.endswith("K") or n.endswith("k"): n = float(n[:-1]) * 1000 elif n.endswith("M") or n.endswith("m"): n = float(n[:-1]) * 1000 * 1000 elif n.endswith("G") or n.endswith("g") or n.endswith("B") or n.endswith("b"): n = float(n[:-1]) * 1000 * 1000 * 1000 elif n == "-": logger.info("_float met -, taken as 0") return 0 elif n.endswith("%"): logger.info("_float met with %% as %s" % n) return float(n[:-1]) / 100 except AttributeError: pass if not n: logger.info("_float met with None as input arguments") return 0.0 return float(n) def reconnect(tries=5, timeout=12): def robustify(f): default_header = { 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,' 'application/signed-exchange;v=b3;q=0.9', 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6,ja;q=0.5', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/89.0.4389.114 Safari/537.36 Edg/89.0.774.76', } @wraps(f) def wrapper(*args, **kws): import xalpha.provider as xp if getattr(xp, "proxy", None): kws["proxies"] = {"http": xp.proxy, "https": xp.proxy} kws["timeout"] = timeout logger.debug("Using proxy %s" % xp.proxy) if args: url = args[0] else: url = kws.get("url", "") headers = kws.get("headers", {}) if len(headers) == 0: headers.update(default_header) kws["headers"] = headers for count in range(tries): try: logger.debug("Fetching url: %s . Inside function `%s`" % (url, inspect.stack()[1].function)) r = f(*args, **kws) if getattr(r, "status_code", 200) != 200: raise HttpStatusError return r except connection_errors as e: logger.warning("Fails at fetching url: %s. Try again." % url) if count == tries - 1: logger.error("Still wrong at fetching url: %s. after %s tries." % (url, tries)) logger.error("Fails due to %s" % e.args[0]) raise e time.sleep(0.5 * count) return wrapper return robustify rget = reconnect()(requests.get) rpost = reconnect()(requests.post) @reconnect() def rget_json(*args, **kws): r = requests.get(*args, **kws) return r.json() @reconnect() def rpost_json(*args, **kws): r = requests.post(*args, **kws) return r.json() { "etfs/etfs-brent-1mth-uk": 17.51, "etfs/etfs-brent-crude": 15.04, "etfs/etfs-crude-oil": 7.34, "etfs/ipath-series-b-sp-gsci-crd-oil-tr": 0.06, "etfs/powershares-db-oil-fund": 11.6, "etfs/ubs-cmci-oil-sf-usd": 8.68, "etfs/united-states-12-month-oil": 8.14, "etfs/united-states-brent-oil-fund-lp": 15.42, "etfs/united-states-oil-fund": 9.63, } holdings["501018rt"] = { "commodities/brent-oil": {"weight": 49, "time": -1}, "commodities/crude-oil": {"weight": 45, "time": 4}, }
true
true
f72a5a03842d93e765331b1fe8130fe4969fd3ea
3,462
py
Python
temperature.py
balena-io-playground/balena-edison-monitoring-artik
d02ba51cda8edcbc0decc80d0dab7f724dc46014
[ "Apache-2.0" ]
2
2020-04-25T08:46:41.000Z
2021-02-11T17:36:27.000Z
temperature.py
balena-io-playground/balena-edison-monitoring-artik
d02ba51cda8edcbc0decc80d0dab7f724dc46014
[ "Apache-2.0" ]
null
null
null
temperature.py
balena-io-playground/balena-edison-monitoring-artik
d02ba51cda8edcbc0decc80d0dab7f724dc46014
[ "Apache-2.0" ]
null
null
null
""" Temperature monitoring with Intel Edison and Samsung ARTIK Cloud """ import sys import os import time from math import log import statistics from collections import deque import artikcloud from artikcloud.rest import ApiException import pyupm_grove as grove import mraa import requests # Setting credentials from the environmental variables DEVICE_ID = os.getenv('ARTIKCLOUD_DEVICE_ID') DEVICE_TOKEN = os.getenv('ARTIKCLOUD_DEVICE_TOKEN') try: AVERAGE = int(os.getenv('AVERAGE', 5)) except: AVERAGE = 5 finally: print("INFO: averaging over {} readings".format(AVERAGE)) PERIOD = 1 # Setting up ARTIK Cloud connection artikcloud.configuration.access_token = DEVICE_TOKEN # Setting up messaging messages_api = artikcloud.MessagesApi() # Create the temperature sensor object using AIO pin 0 temp = grove.GroveTemp(0) print(temp.name()) led = mraa.Gpio(4) led.dir(mraa.DIR_OUT) def reboot_device(): """Restart application through the resin Supervisor """ params = {'apikey': os.getenv('RESIN_SUPERVISOR_API_KEY')} payload = {'appId': os.getenv('RESIN_APP_ID')} supervisor_address = os.getenv('RESIN_SUPERVISOR_ADDRESS') print("Restarting Application") r = requests.post("{}/v1/reboot".format(supervisor_address), supervisor_address, params=params, json=payload) if r.status_code == 200: sys.exit(0) def temp_convert(sensor): """Adapted from UPM source code https://github.com/intel-iot-devkit/upm/blob/4faa71d239f3549556a61df1a9c6f81c3d06bda2/src/grove/grovetemp.cxx#L54-L63 """ a = sensor.raw_value() if a < 0: return -300 m_scale, m_r0, m_b = 1.0, 100000.0, 4275.0 # Apply scale factor after error check a *= m_scale r = (1023.0-a)*m_r0/a t = 1.0/(log(r/m_r0)/m_b + 1.0/298.15)-273.15 return t # Throw away readings to settle down print("Throw-away readings to settle") for i in range(5): celsius = temp_convert(temp) print("Current temperature: {0:.2f}".format(celsius)) time.sleep(1) print("Starting proper readings") i = 0 error_count = 0 readings = deque(maxlen=AVERAGE) while True: loopstart = time.time() celsius = temp_convert(temp) readings.append(celsius) meancelsius = statistics.mean(readings) print("Current temperature: {0:.2f} (mean: {1:.2f})".format(celsius, meancelsius)) if i % 600 == 0: # Send a new message message = artikcloud.Message() message.type = "message" message.sdid = "{}".format(DEVICE_ID) message.ts = int(round(time.time() * 1000)) # timestamp, required message.data = {'Temperature': meancelsius} try: response = messages_api.send_message(message) print(response) except ApiException as error: print("API ERROR: {}".format(str(error))) error_count += 1 except: error = sys.exc_info()[0] print("ERROR: {}".format(error)) error_count += 1 else: error_count = 0 finally: if error_count > 5: reboot_device() i = 0 led.write(1) time.sleep(0.1) led.write(0) i += 1 newsleep = (loopstart + PERIOD) - time.time() if newsleep < 0: print("WARNING: loop took {}s while period is {}!".format(PERIOD - newsleep, PERIOD)) else: time.sleep(newsleep)
29.589744
121
0.644136
import sys import os import time from math import log import statistics from collections import deque import artikcloud from artikcloud.rest import ApiException import pyupm_grove as grove import mraa import requests DEVICE_ID = os.getenv('ARTIKCLOUD_DEVICE_ID') DEVICE_TOKEN = os.getenv('ARTIKCLOUD_DEVICE_TOKEN') try: AVERAGE = int(os.getenv('AVERAGE', 5)) except: AVERAGE = 5 finally: print("INFO: averaging over {} readings".format(AVERAGE)) PERIOD = 1 artikcloud.configuration.access_token = DEVICE_TOKEN messages_api = artikcloud.MessagesApi() temp = grove.GroveTemp(0) print(temp.name()) led = mraa.Gpio(4) led.dir(mraa.DIR_OUT) def reboot_device(): params = {'apikey': os.getenv('RESIN_SUPERVISOR_API_KEY')} payload = {'appId': os.getenv('RESIN_APP_ID')} supervisor_address = os.getenv('RESIN_SUPERVISOR_ADDRESS') print("Restarting Application") r = requests.post("{}/v1/reboot".format(supervisor_address), supervisor_address, params=params, json=payload) if r.status_code == 200: sys.exit(0) def temp_convert(sensor): a = sensor.raw_value() if a < 0: return -300 m_scale, m_r0, m_b = 1.0, 100000.0, 4275.0 a *= m_scale r = (1023.0-a)*m_r0/a t = 1.0/(log(r/m_r0)/m_b + 1.0/298.15)-273.15 return t print("Throw-away readings to settle") for i in range(5): celsius = temp_convert(temp) print("Current temperature: {0:.2f}".format(celsius)) time.sleep(1) print("Starting proper readings") i = 0 error_count = 0 readings = deque(maxlen=AVERAGE) while True: loopstart = time.time() celsius = temp_convert(temp) readings.append(celsius) meancelsius = statistics.mean(readings) print("Current temperature: {0:.2f} (mean: {1:.2f})".format(celsius, meancelsius)) if i % 600 == 0: message = artikcloud.Message() message.type = "message" message.sdid = "{}".format(DEVICE_ID) message.ts = int(round(time.time() * 1000)) message.data = {'Temperature': meancelsius} try: response = messages_api.send_message(message) print(response) except ApiException as error: print("API ERROR: {}".format(str(error))) error_count += 1 except: error = sys.exc_info()[0] print("ERROR: {}".format(error)) error_count += 1 else: error_count = 0 finally: if error_count > 5: reboot_device() i = 0 led.write(1) time.sleep(0.1) led.write(0) i += 1 newsleep = (loopstart + PERIOD) - time.time() if newsleep < 0: print("WARNING: loop took {}s while period is {}!".format(PERIOD - newsleep, PERIOD)) else: time.sleep(newsleep)
true
true
f72a5a2e708a8aa2bbfc8ad3b14c6e6ce0a4298f
701
py
Python
P2/dsa_shuffling_queue.py
MC-DeltaT/DSA-Practicals
5c77cac1cfee5d756b84722e563813c153486770
[ "MIT" ]
null
null
null
P2/dsa_shuffling_queue.py
MC-DeltaT/DSA-Practicals
5c77cac1cfee5d756b84722e563813c153486770
[ "MIT" ]
null
null
null
P2/dsa_shuffling_queue.py
MC-DeltaT/DSA-Practicals
5c77cac1cfee5d756b84722e563813c153486770
[ "MIT" ]
null
null
null
from dsa_queue import DSAQueue class DSAShufflingQueue(DSAQueue): def enqueue(self, obj: object) -> None: if self.is_full(): raise ValueError("Queue is full.") self._array[self._size] = obj self._size += 1 def dequeue(self) -> object: tmp = self.peek() for i in range(0, self._size - 1): self._array[i] = self._array[i + 1] self._size -= 1 return tmp def peek(self) -> object: if self.is_empty(): raise ValueError("Queue is empty.") return self._array[0] # For visualisation purposes only. def as_list(self) -> list: return list(self._array[:self.get_size()])
26.961538
50
0.574893
from dsa_queue import DSAQueue class DSAShufflingQueue(DSAQueue): def enqueue(self, obj: object) -> None: if self.is_full(): raise ValueError("Queue is full.") self._array[self._size] = obj self._size += 1 def dequeue(self) -> object: tmp = self.peek() for i in range(0, self._size - 1): self._array[i] = self._array[i + 1] self._size -= 1 return tmp def peek(self) -> object: if self.is_empty(): raise ValueError("Queue is empty.") return self._array[0] def as_list(self) -> list: return list(self._array[:self.get_size()])
true
true
f72a5b5dc1100cba5f9f50fe40bb4f01308226b6
294
py
Python
nn/optim/optimizer.py
dimaischenko/nn
a7f5887ec816e6b3bbfc57e6864ab3ae320161a6
[ "Apache-2.0" ]
null
null
null
nn/optim/optimizer.py
dimaischenko/nn
a7f5887ec816e6b3bbfc57e6864ab3ae320161a6
[ "Apache-2.0" ]
null
null
null
nn/optim/optimizer.py
dimaischenko/nn
a7f5887ec816e6b3bbfc57e6864ab3ae320161a6
[ "Apache-2.0" ]
null
null
null
class Optimizer(object): """Base abstract class for all optimizers Get network parameters and its gradients and create steps """ def __init__(self, params, grad_params): self.params = params self.grad_params = grad_params def step(self): pass
21
48
0.64966
class Optimizer(object): def __init__(self, params, grad_params): self.params = params self.grad_params = grad_params def step(self): pass
true
true
f72a5c44fcb11c06bc86b2be7515980898efe20d
2,349
py
Python
tests/conftest.py
madkote/rasa-nlu-contrib
38804da8a1debb172a3ad06a9b867a0ae8ee9b59
[ "Apache-2.0" ]
18
2019-05-07T10:28:32.000Z
2022-01-22T02:30:30.000Z
tests/conftest.py
madkote/rasa-nlu-contrib
38804da8a1debb172a3ad06a9b867a0ae8ee9b59
[ "Apache-2.0" ]
2
2019-06-14T17:57:27.000Z
2020-11-30T02:39:39.000Z
tests/conftest.py
madkote/rasa-nlu-contrib
38804da8a1debb172a3ad06a9b867a0ae8ee9b59
[ "Apache-2.0" ]
15
2019-03-18T02:21:13.000Z
2022-01-22T02:32:19.000Z
import logging import os import pytest from rasa_nlu import data_router, config from rasa_nlu.components import ComponentBuilder from rasa_nlu.model import Trainer from rasa_nlu.utils import zip_folder from rasa_nlu import training_data logging.basicConfig(level="DEBUG") CONFIG_DEFAULTS_PATH = "sample_configs/config_defaults.yml" DEFAULT_DATA_PATH = "data/examples/rasa/demo-rasa.json" TEST_MODEL_PATH = "test_models/test_model_pretrained_embeddings" # see `rasa_nlu.data_router` for details. avoids deadlock in # `deferred_from_future` function during tests data_router.DEFERRED_RUN_IN_REACTOR_THREAD = False @pytest.fixture(scope="session") def component_builder(): return ComponentBuilder() @pytest.fixture(scope="session") def spacy_nlp(component_builder, default_config): spacy_nlp_config = {'name': 'SpacyNLP'} return component_builder.create_component(spacy_nlp_config, default_config).nlp @pytest.fixture(scope="session") def ner_crf_pos_feature_config(): return { "features": [ ["low", "title", "upper", "pos", "pos2"], ["bias", "low", "suffix3", "suffix2", "upper", "title", "digit", "pos", "pos2", "pattern"], ["low", "title", "upper", "pos", "pos2"]] } @pytest.fixture(scope="session") def mitie_feature_extractor(component_builder, default_config): mitie_nlp_config = {'name': 'MitieNLP'} return component_builder.create_component(mitie_nlp_config, default_config).extractor @pytest.fixture(scope="session") def default_config(): return config.load(CONFIG_DEFAULTS_PATH) @pytest.fixture(scope="session") def zipped_nlu_model(): spacy_config_path = "sample_configs/config_pretrained_embeddings_spacy.yml" cfg = config.load(spacy_config_path) trainer = Trainer(cfg) td = training_data.load_data(DEFAULT_DATA_PATH) trainer.train(td) trainer.persist("test_models", project_name="test_model_pretrained_embeddings") model_dir_list = os.listdir(TEST_MODEL_PATH) # directory name of latest model model_dir = sorted(model_dir_list)[-1] # path of that directory model_path = os.path.join(TEST_MODEL_PATH, model_dir) zip_path = zip_folder(model_path) return zip_path
28.646341
79
0.707961
import logging import os import pytest from rasa_nlu import data_router, config from rasa_nlu.components import ComponentBuilder from rasa_nlu.model import Trainer from rasa_nlu.utils import zip_folder from rasa_nlu import training_data logging.basicConfig(level="DEBUG") CONFIG_DEFAULTS_PATH = "sample_configs/config_defaults.yml" DEFAULT_DATA_PATH = "data/examples/rasa/demo-rasa.json" TEST_MODEL_PATH = "test_models/test_model_pretrained_embeddings" data_router.DEFERRED_RUN_IN_REACTOR_THREAD = False @pytest.fixture(scope="session") def component_builder(): return ComponentBuilder() @pytest.fixture(scope="session") def spacy_nlp(component_builder, default_config): spacy_nlp_config = {'name': 'SpacyNLP'} return component_builder.create_component(spacy_nlp_config, default_config).nlp @pytest.fixture(scope="session") def ner_crf_pos_feature_config(): return { "features": [ ["low", "title", "upper", "pos", "pos2"], ["bias", "low", "suffix3", "suffix2", "upper", "title", "digit", "pos", "pos2", "pattern"], ["low", "title", "upper", "pos", "pos2"]] } @pytest.fixture(scope="session") def mitie_feature_extractor(component_builder, default_config): mitie_nlp_config = {'name': 'MitieNLP'} return component_builder.create_component(mitie_nlp_config, default_config).extractor @pytest.fixture(scope="session") def default_config(): return config.load(CONFIG_DEFAULTS_PATH) @pytest.fixture(scope="session") def zipped_nlu_model(): spacy_config_path = "sample_configs/config_pretrained_embeddings_spacy.yml" cfg = config.load(spacy_config_path) trainer = Trainer(cfg) td = training_data.load_data(DEFAULT_DATA_PATH) trainer.train(td) trainer.persist("test_models", project_name="test_model_pretrained_embeddings") model_dir_list = os.listdir(TEST_MODEL_PATH) model_dir = sorted(model_dir_list)[-1] model_path = os.path.join(TEST_MODEL_PATH, model_dir) zip_path = zip_folder(model_path) return zip_path
true
true
f72a5c88f96eb156e3a5960ef301b4efb90b71f7
7,657
py
Python
models/resnet_imagenet.py
huawei-noah/Disout
dd4a131ee27043fd3da638056808216944722336
[ "BSD-3-Clause" ]
222
2020-05-19T04:41:44.000Z
2022-03-25T20:31:01.000Z
models/resnet_imagenet.py
huawei-noah/Disout
dd4a131ee27043fd3da638056808216944722336
[ "BSD-3-Clause" ]
13
2020-05-19T09:01:40.000Z
2020-12-02T06:15:29.000Z
models/resnet_imagenet.py
huawei-noah/Disout
dd4a131ee27043fd3da638056808216944722336
[ "BSD-3-Clause" ]
40
2020-05-19T07:08:55.000Z
2022-03-14T00:21:03.000Z
#Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. #This program is free software; you can redistribute it and/or modify it under the terms of the BSD 3-Clause License. #This program 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. See the BSD 3-Clause License for more details. import torch.nn as nn import math import sys sys.path.append("..") from disout import Disout,LinearScheduler dploc = [73, 77, 81, 88, 92, 96, 100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140, 144, 148, 152, 156, 160, 164, 168, 173,177, 181, 188, 192, 196, 200, 204, 208, 212] convloc =[75, 79, 90, 90, 94, 98, 106, 106, 110, 114, 122, 122, 126, 130, 138, 138, 142, 146, 154, 154, 158, 162, 171, 171, 175, 179, 190, 190, 194, 198, 206, 206, 210, 214] def conv3x3(in_planes, out_planes, stride=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,padding=1, bias=False) class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None,dist_prob=None,block_size=None,alpha=None,nr_steps=None): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,padding=1, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False) self.bn3 = nn.BatchNorm2d(planes * 4) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride def forward(self, x): residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if self.downsample is not None: residual = self.downsample(x) out += residual out = self.relu(out) return out class Bottleneck_disout(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None,dist_prob=0.05,block_size=6,alpha=30,nr_steps=5e3): super(Bottleneck_disout, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.disout1=LinearScheduler(Disout(dist_prob=dist_prob,block_size=block_size,alpha=alpha), start_value=0.,stop_value=dist_prob,nr_steps=nr_steps) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,padding=1, bias=False) self.disout2=LinearScheduler(Disout(dist_prob=dist_prob,block_size=block_size,alpha=alpha), start_value=0.,stop_value=dist_prob,nr_steps=nr_steps) self.bn2 = nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False) self.disout3=LinearScheduler(Disout(dist_prob=dist_prob,block_size=block_size,alpha=alpha), start_value=0.,stop_value=dist_prob,nr_steps=nr_steps) self.bn3 = nn.BatchNorm2d(planes * 4) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride self.disout4=LinearScheduler(Disout(dist_prob=dist_prob,block_size=block_size,alpha=alpha), start_value=0.,stop_value=dist_prob,nr_steps=nr_steps) def forward(self, x): residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out=self.disout1(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out=self.disout2(out) out = self.conv3(out) out = self.bn3(out) out=self.disout3(out) if self.downsample is not None: residual = self.downsample(x) residual=self.disout4(residual) out += residual out = self.relu(out) return out class ResNet_disout(nn.Module): def __init__(self, layers, num_classes=1000,dist_prob=0.05,block_size=6,alpha=30,nr_steps=5e3): super(ResNet_disout, self).__init__() self.inplanes = 64 self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,bias=False) self.bn1 = nn.BatchNorm2d(64) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) self.layer1 = self._make_layer(Bottleneck, 64, layers[0]) self.layer2 = self._make_layer(Bottleneck, 128, layers[1], stride=2) self.layer3 = self._make_layer(Bottleneck_disout, 256, layers[2], stride=2, dist_prob=dist_prob/4,block_size=block_size,alpha=alpha,nr_steps=nr_steps) self.layer4 = self._make_layer(Bottleneck_disout, 512, layers[3], stride=2, dist_prob=dist_prob,block_size=block_size,alpha=alpha,nr_steps=nr_steps) self.avgpool = nn.AvgPool2d(7, stride=1) self.fc = nn.Linear(512 * Bottleneck.expansion, num_classes) for name,m in self.named_modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m,nn.BatchNorm2d) and 'bn3'in name: m.weight.data.fill_(0) m.bias.data.zero_() elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() def _make_layer(self, block, planes, blocks, stride=1,dist_prob=0.05,block_size=6,alpha=30,nr_steps=5e3): downsample = None if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False), nn.BatchNorm2d(planes * block.expansion),) layers = [] layers.append(block(self.inplanes, planes, stride, downsample, dist_prob=dist_prob,block_size=block_size,alpha=alpha,nr_steps=nr_steps)) self.inplanes = planes * block.expansion for i in range(1, blocks): layers.append(block(self.inplanes, planes, dist_prob=dist_prob,block_size=block_size,alpha=alpha,nr_steps=nr_steps)) return nn.Sequential(*layers) def forward(self, x): gpu_id = str(x.get_device()) modulelist=list(self.modules()) for imodu in range(len(dploc)): modulelist[dploc[imodu]].weight_behind[gpu_id]=modulelist[convloc[imodu]].weight.data x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) x = self.avgpool(x) x = x.view(x.size(0), -1) x = self.fc(x) return x def resnet50_disout(dist_prob=0.05,block_size=6,alpha=30,nr_steps=5e3): model = ResNet_disout([3, 4, 6, 3],dist_prob=dist_prob,block_size=block_size,alpha=alpha,nr_steps=nr_steps) return model
39.673575
227
0.614079
import torch.nn as nn import math import sys sys.path.append("..") from disout import Disout,LinearScheduler dploc = [73, 77, 81, 88, 92, 96, 100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140, 144, 148, 152, 156, 160, 164, 168, 173,177, 181, 188, 192, 196, 200, 204, 208, 212] convloc =[75, 79, 90, 90, 94, 98, 106, 106, 110, 114, 122, 122, 126, 130, 138, 138, 142, 146, 154, 154, 158, 162, 171, 171, 175, 179, 190, 190, 194, 198, 206, 206, 210, 214] def conv3x3(in_planes, out_planes, stride=1): return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,padding=1, bias=False) class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None,dist_prob=None,block_size=None,alpha=None,nr_steps=None): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,padding=1, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False) self.bn3 = nn.BatchNorm2d(planes * 4) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride def forward(self, x): residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if self.downsample is not None: residual = self.downsample(x) out += residual out = self.relu(out) return out class Bottleneck_disout(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None,dist_prob=0.05,block_size=6,alpha=30,nr_steps=5e3): super(Bottleneck_disout, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.disout1=LinearScheduler(Disout(dist_prob=dist_prob,block_size=block_size,alpha=alpha), start_value=0.,stop_value=dist_prob,nr_steps=nr_steps) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,padding=1, bias=False) self.disout2=LinearScheduler(Disout(dist_prob=dist_prob,block_size=block_size,alpha=alpha), start_value=0.,stop_value=dist_prob,nr_steps=nr_steps) self.bn2 = nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False) self.disout3=LinearScheduler(Disout(dist_prob=dist_prob,block_size=block_size,alpha=alpha), start_value=0.,stop_value=dist_prob,nr_steps=nr_steps) self.bn3 = nn.BatchNorm2d(planes * 4) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride self.disout4=LinearScheduler(Disout(dist_prob=dist_prob,block_size=block_size,alpha=alpha), start_value=0.,stop_value=dist_prob,nr_steps=nr_steps) def forward(self, x): residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out=self.disout1(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out=self.disout2(out) out = self.conv3(out) out = self.bn3(out) out=self.disout3(out) if self.downsample is not None: residual = self.downsample(x) residual=self.disout4(residual) out += residual out = self.relu(out) return out class ResNet_disout(nn.Module): def __init__(self, layers, num_classes=1000,dist_prob=0.05,block_size=6,alpha=30,nr_steps=5e3): super(ResNet_disout, self).__init__() self.inplanes = 64 self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,bias=False) self.bn1 = nn.BatchNorm2d(64) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) self.layer1 = self._make_layer(Bottleneck, 64, layers[0]) self.layer2 = self._make_layer(Bottleneck, 128, layers[1], stride=2) self.layer3 = self._make_layer(Bottleneck_disout, 256, layers[2], stride=2, dist_prob=dist_prob/4,block_size=block_size,alpha=alpha,nr_steps=nr_steps) self.layer4 = self._make_layer(Bottleneck_disout, 512, layers[3], stride=2, dist_prob=dist_prob,block_size=block_size,alpha=alpha,nr_steps=nr_steps) self.avgpool = nn.AvgPool2d(7, stride=1) self.fc = nn.Linear(512 * Bottleneck.expansion, num_classes) for name,m in self.named_modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m,nn.BatchNorm2d) and 'bn3'in name: m.weight.data.fill_(0) m.bias.data.zero_() elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() def _make_layer(self, block, planes, blocks, stride=1,dist_prob=0.05,block_size=6,alpha=30,nr_steps=5e3): downsample = None if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False), nn.BatchNorm2d(planes * block.expansion),) layers = [] layers.append(block(self.inplanes, planes, stride, downsample, dist_prob=dist_prob,block_size=block_size,alpha=alpha,nr_steps=nr_steps)) self.inplanes = planes * block.expansion for i in range(1, blocks): layers.append(block(self.inplanes, planes, dist_prob=dist_prob,block_size=block_size,alpha=alpha,nr_steps=nr_steps)) return nn.Sequential(*layers) def forward(self, x): gpu_id = str(x.get_device()) modulelist=list(self.modules()) for imodu in range(len(dploc)): modulelist[dploc[imodu]].weight_behind[gpu_id]=modulelist[convloc[imodu]].weight.data x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) x = self.avgpool(x) x = x.view(x.size(0), -1) x = self.fc(x) return x def resnet50_disout(dist_prob=0.05,block_size=6,alpha=30,nr_steps=5e3): model = ResNet_disout([3, 4, 6, 3],dist_prob=dist_prob,block_size=block_size,alpha=alpha,nr_steps=nr_steps) return model
true
true
f72a5cd00105d9d13c7915d5db1087ad43337300
237
py
Python
src/fecc_object/ConstantObject.py
castor91/fecc
bc46059c0d7a428d15b95050b70dec374b4bea28
[ "MIT" ]
1
2018-02-04T14:48:15.000Z
2018-02-04T14:48:15.000Z
src/fecc_object/ConstantObject.py
castor91/fecc
bc46059c0d7a428d15b95050b70dec374b4bea28
[ "MIT" ]
null
null
null
src/fecc_object/ConstantObject.py
castor91/fecc
bc46059c0d7a428d15b95050b70dec374b4bea28
[ "MIT" ]
null
null
null
from AbstractObject import * class ConstantObject(AbstractObject): def __init__(self, value): super(ConstantObject, self).__init__(value._value) def generate(self, out_code): out_code.append(PUSH(self._value))
23.7
58
0.7173
from AbstractObject import * class ConstantObject(AbstractObject): def __init__(self, value): super(ConstantObject, self).__init__(value._value) def generate(self, out_code): out_code.append(PUSH(self._value))
true
true
f72a5d57fc6b542d719802c50c2de09ed475adb4
265
py
Python
output/models/nist_data/atomic/g_month_day/schema_instance/nistschema_sv_iv_atomic_g_month_day_pattern_2_xsd/__init__.py
tefra/xsdata-w3c-tests
b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f
[ "MIT" ]
1
2021-08-14T17:59:21.000Z
2021-08-14T17:59:21.000Z
output/models/nist_data/atomic/g_month_day/schema_instance/nistschema_sv_iv_atomic_g_month_day_pattern_2_xsd/__init__.py
tefra/xsdata-w3c-tests
b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f
[ "MIT" ]
4
2020-02-12T21:30:44.000Z
2020-04-15T20:06:46.000Z
output/models/nist_data/atomic/g_month_day/schema_instance/nistschema_sv_iv_atomic_g_month_day_pattern_2_xsd/__init__.py
tefra/xsdata-w3c-tests
b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f
[ "MIT" ]
null
null
null
from output.models.nist_data.atomic.g_month_day.schema_instance.nistschema_sv_iv_atomic_g_month_day_pattern_2_xsd.nistschema_sv_iv_atomic_g_month_day_pattern_2 import NistschemaSvIvAtomicGMonthDayPattern2 __all__ = [ "NistschemaSvIvAtomicGMonthDayPattern2", ]
44.166667
204
0.898113
from output.models.nist_data.atomic.g_month_day.schema_instance.nistschema_sv_iv_atomic_g_month_day_pattern_2_xsd.nistschema_sv_iv_atomic_g_month_day_pattern_2 import NistschemaSvIvAtomicGMonthDayPattern2 __all__ = [ "NistschemaSvIvAtomicGMonthDayPattern2", ]
true
true
f72a5db6ab6073da6de701cf534352393ace0f69
3,681
py
Python
ml_source/src/blocktorch/blocktorch/pipelines/components/estimators/classifiers/logistic_regression_classifier.py
blocktorch/blocktorch
044aa269813ab22c5fd27f84272e5fb540fc522b
[ "MIT" ]
1
2021-09-23T12:23:02.000Z
2021-09-23T12:23:02.000Z
ml_source/src/blocktorch/blocktorch/pipelines/components/estimators/classifiers/logistic_regression_classifier.py
blocktorch/blocktorch
044aa269813ab22c5fd27f84272e5fb540fc522b
[ "MIT" ]
null
null
null
ml_source/src/blocktorch/blocktorch/pipelines/components/estimators/classifiers/logistic_regression_classifier.py
blocktorch/blocktorch
044aa269813ab22c5fd27f84272e5fb540fc522b
[ "MIT" ]
null
null
null
"""Logistic Regression Classifier.""" import numpy as np from sklearn.linear_model import LogisticRegression as SKLogisticRegression from skopt.space import Real from blocktorch.model_family import ModelFamily from blocktorch.pipelines.components.estimators import Estimator from blocktorch.problem_types import ProblemTypes class LogisticRegressionClassifier(Estimator): """Logistic Regression Classifier. Args: penalty ({"l1", "l2", "elasticnet", "none"}): The norm used in penalization. Defaults to "l2". C (float): Inverse of regularization strength. Must be a positive float. Defaults to 1.0. multi_class ({"auto", "ovr", "multinomial"}): If the option chosen is "ovr", then a binary problem is fit for each label. For "multinomial" the loss minimised is the multinomial loss fit across the entire probability distribution, even when the data is binary. "multinomial" is unavailable when solver="liblinear". "auto" selects "ovr" if the data is binary, or if solver="liblinear", and otherwise selects "multinomial". Defaults to "auto". solver ({"newton-cg", "lbfgs", "liblinear", "sag", "saga"}): Algorithm to use in the optimization problem. For small datasets, "liblinear" is a good choice, whereas "sag" and "saga" are faster for large ones. For multiclass problems, only "newton-cg", "sag", "saga" and "lbfgs" handle multinomial loss; "liblinear" is limited to one-versus-rest schemes. - "newton-cg", "lbfgs", "sag" and "saga" handle L2 or no penalty - "liblinear" and "saga" also handle L1 penalty - "saga" also supports "elasticnet" penalty - "liblinear" does not support setting penalty='none' Defaults to "lbfgs". n_jobs (int): Number of parallel threads used to run xgboost. Note that creating thread contention will significantly slow down the algorithm. Defaults to -1. random_seed (int): Seed for the random number generator. Defaults to 0. """ name = "Logistic Regression Classifier" hyperparameter_ranges = { "penalty": ["l2"], "C": Real(0.01, 10), } """{ "penalty": ["l2"], "C": Real(0.01, 10), }""" model_family = ModelFamily.LINEAR_MODEL """ModelFamily.LINEAR_MODEL""" supported_problem_types = [ ProblemTypes.BINARY, ProblemTypes.MULTICLASS, ProblemTypes.TIME_SERIES_BINARY, ProblemTypes.TIME_SERIES_MULTICLASS, ] """[ ProblemTypes.BINARY, ProblemTypes.MULTICLASS, ProblemTypes.TIME_SERIES_BINARY, ProblemTypes.TIME_SERIES_MULTICLASS, ]""" def __init__( self, penalty="l2", C=1.0, multi_class="auto", solver="lbfgs", n_jobs=-1, random_seed=0, **kwargs, ): parameters = { "penalty": penalty, "C": C, "n_jobs": n_jobs, "multi_class": multi_class, "solver": solver, } parameters.update(kwargs) lr_classifier = SKLogisticRegression(random_state=random_seed, **parameters) super().__init__( parameters=parameters, component_obj=lr_classifier, random_seed=random_seed ) @property def feature_importance(self): """Feature importance for fitted logistic regression classifier.""" coef_ = self._component_obj.coef_ # binary classification case if len(coef_) <= 2: return coef_[0] else: # multiclass classification case return np.linalg.norm(coef_, axis=0, ord=2)
40.01087
166
0.640315
import numpy as np from sklearn.linear_model import LogisticRegression as SKLogisticRegression from skopt.space import Real from blocktorch.model_family import ModelFamily from blocktorch.pipelines.components.estimators import Estimator from blocktorch.problem_types import ProblemTypes class LogisticRegressionClassifier(Estimator): name = "Logistic Regression Classifier" hyperparameter_ranges = { "penalty": ["l2"], "C": Real(0.01, 10), } model_family = ModelFamily.LINEAR_MODEL supported_problem_types = [ ProblemTypes.BINARY, ProblemTypes.MULTICLASS, ProblemTypes.TIME_SERIES_BINARY, ProblemTypes.TIME_SERIES_MULTICLASS, ] def __init__( self, penalty="l2", C=1.0, multi_class="auto", solver="lbfgs", n_jobs=-1, random_seed=0, **kwargs, ): parameters = { "penalty": penalty, "C": C, "n_jobs": n_jobs, "multi_class": multi_class, "solver": solver, } parameters.update(kwargs) lr_classifier = SKLogisticRegression(random_state=random_seed, **parameters) super().__init__( parameters=parameters, component_obj=lr_classifier, random_seed=random_seed ) @property def feature_importance(self): coef_ = self._component_obj.coef_ if len(coef_) <= 2: return coef_[0] else: return np.linalg.norm(coef_, axis=0, ord=2)
true
true
f72a5eb729d896a5a7b9e4172a18b461bd416d06
953
py
Python
app/programs/original/rain.py
mike-wendt/unicorn-remote
e649c069482446f08b0baf579de05f065ad7ab89
[ "MIT" ]
37
2017-07-30T16:43:22.000Z
2021-12-12T09:40:11.000Z
app/programs/original/rain.py
kfechter/unicorn-remote
39466cad9e7420b51ffa11fa7554756a934f2d24
[ "MIT" ]
7
2017-11-18T19:22:18.000Z
2021-09-08T15:59:00.000Z
app/programs/original/rain.py
kfechter/unicorn-remote
39466cad9e7420b51ffa11fa7554756a934f2d24
[ "MIT" ]
8
2018-04-21T05:31:40.000Z
2020-12-09T19:43:32.000Z
import unicornhat as unicorn import time, colorsys import random def run(params): m = [[0 for i in range(8)] for i in range(8)] while True: if 1 in m[-1]: top = [0.5 * i for i in m[-1]] elif 0.5 in m[-1]: top = [0] * 8 else: top = [random.randint(0,1) for i in range(2)] + [0,0,0,0,0,0] random.shuffle(top) for i in range(len(top)): if top[i] == 1 and top[i-1] == 1: top[i] = 0 m.append(top) del m[0] for x in range(8): for y in range(8): h = 0.6 s = 0.6 v = m[x][y] * 0.8 rgb = colorsys.hsv_to_rgb(h, s, v) r = int(rgb[0]*255.0) g = int(rgb[1]*255.0) b = int(rgb[2]*255.0) unicorn.set_pixel(8-y-1, x, r, g, b) unicorn.show() time.sleep(0.05)
28.878788
73
0.408185
import unicornhat as unicorn import time, colorsys import random def run(params): m = [[0 for i in range(8)] for i in range(8)] while True: if 1 in m[-1]: top = [0.5 * i for i in m[-1]] elif 0.5 in m[-1]: top = [0] * 8 else: top = [random.randint(0,1) for i in range(2)] + [0,0,0,0,0,0] random.shuffle(top) for i in range(len(top)): if top[i] == 1 and top[i-1] == 1: top[i] = 0 m.append(top) del m[0] for x in range(8): for y in range(8): h = 0.6 s = 0.6 v = m[x][y] * 0.8 rgb = colorsys.hsv_to_rgb(h, s, v) r = int(rgb[0]*255.0) g = int(rgb[1]*255.0) b = int(rgb[2]*255.0) unicorn.set_pixel(8-y-1, x, r, g, b) unicorn.show() time.sleep(0.05)
true
true
f72a5f267601807387faccbf297e7207c244bae9
7,613
py
Python
GPyOpt/util/general.py
komorihi/GPyOpt
5c8424f92ffaa745d3daebca3f38de2569500d6d
[ "BSD-3-Clause" ]
null
null
null
GPyOpt/util/general.py
komorihi/GPyOpt
5c8424f92ffaa745d3daebca3f38de2569500d6d
[ "BSD-3-Clause" ]
null
null
null
GPyOpt/util/general.py
komorihi/GPyOpt
5c8424f92ffaa745d3daebca3f38de2569500d6d
[ "BSD-3-Clause" ]
null
null
null
# Copyright (c) 2016, the GPyOpt Authors # Licensed under the BSD 3-clause license (see LICENSE.txt) import numpy as np from scipy.special import erfc import time from ..core.errors import InvalidConfigError def compute_integrated_acquisition(acquisition,x): ''' Used to compute the acquisition function when samples of the hyper-parameters have been generated (used in GP_MCMC model). :param acquisition: acquisition function with GpyOpt model type GP_MCMC. :param x: location where the acquisition is evaluated. ''' acqu_x = 0 for i in range(acquisition.model.num_hmc_samples): acquisition.model.model.kern[:] = acquisition.model.hmc_samples[i,:] acqu_x += acquisition.acquisition_function(x) acqu_x = acqu_x/acquisition.model.num_hmc_samples return acqu_x def compute_integrated_acquisition_withGradients(acquisition,x): ''' Used to compute the acquisition function with gradients when samples of the hyper-parameters have been generated (used in GP_MCMC model). :param acquisition: acquisition function with GpyOpt model type GP_MCMC. :param x: location where the acquisition is evaluated. ''' acqu_x = 0 d_acqu_x = 0 for i in range(acquisition.model.num_hmc_samples): acquisition.model.model.kern[:] = acquisition.model.hmc_samples[i,:] acqu_x_sample, d_acqu_x_sample = acquisition.acquisition_function_withGradients(x) acqu_x += acqu_x_sample d_acqu_x += d_acqu_x_sample acqu_x = acqu_x/acquisition.model.num_hmc_samples d_acqu_x = d_acqu_x/acquisition.model.num_hmc_samples return acqu_x, d_acqu_x def best_guess(f,X): ''' Gets the best current guess from a vector. :param f: function to evaluate. :param X: locations. ''' n = X.shape[0] xbest = np.zeros(n) for i in range(n): ff = f(X[0:(i+1)]) xbest[i] = ff[np.argmin(ff)] return xbest def samples_multidimensional_uniform(bounds,num_data): ''' Generates a multidimensional grid uniformly distributed. :param bounds: tuple defining the box constrains. :num_data: number of data points to generate. ''' dim = len(bounds) Z_rand = np.zeros(shape=(num_data,dim)) for k in range(0,dim): Z_rand[:,k] = np.random.uniform(low=bounds[k][0],high=bounds[k][1],size=num_data) return Z_rand def reshape(x,input_dim): ''' Reshapes x into a matrix with input_dim columns ''' x = np.array(x) if x.size ==input_dim: x = x.reshape((1,input_dim)) return x def get_moments(model,x): ''' Moments (mean and sdev.) of a GP model at x ''' input_dim = model.X.shape[1] x = reshape(x,input_dim) fmin = min(model.predict(model.X)[0]) m, v = model.predict(x) s = np.sqrt(np.clip(v, 0, np.inf)) return (m,s, fmin) def get_d_moments(model,x): ''' Gradients with respect to x of the moments (mean and sdev.) of the GP :param model: GPy model. :param x: location where the gradients are evaluated. ''' input_dim = model.input_dim x = reshape(x,input_dim) _, v = model.predict(x) dmdx, dvdx = model.predictive_gradients(x) dmdx = dmdx[:,:,0] dsdx = dvdx / (2*np.sqrt(v)) return (dmdx, dsdx) def get_quantiles(acquisition_par, fmin, m, s): ''' Quantiles of the Gaussian distribution useful to determine the acquisition function values :param acquisition_par: parameter of the acquisition function :param fmin: current minimum. :param m: vector of means. :param s: vector of standard deviations. ''' if isinstance(s, np.ndarray): s[s<1e-10] = 1e-10 elif s< 1e-10: s = 1e-10 u = (fmin-m-acquisition_par)/s phi = np.exp(-0.5 * u**2) / np.sqrt(2*np.pi) Phi = 0.5 * erfc(-u / np.sqrt(2)) return (phi, Phi, u) def best_value(Y,sign=1): ''' Returns a vector whose components i are the minimum (default) or maximum of Y[:i] ''' n = Y.shape[0] Y_best = np.ones(n) for i in range(n): if sign == 1: Y_best[i]=Y[:(i+1)].min() else: Y_best[i]=Y[:(i+1)].max() return Y_best def spawn(f): ''' Function for parallel evaluation of the acquisition function ''' def fun(pipe,x): pipe.send(f(x)) pipe.close() return fun def evaluate_function(f,X): ''' Returns the evaluation of a function *f* and the time per evaluation ''' num_data, dim_data = X.shape Y_eval = np.zeros((num_data, dim_data)) Y_time = np.zeros((num_data, 1)) for i in range(num_data): time_zero = time.time() Y_eval[i,:] = f(X[i,:]) Y_time[i,:] = time.time() - time_zero return Y_eval, Y_time def values_to_array(input_values): ''' Transforms a values of int, float and tuples to a column vector numpy array ''' if type(input_values)==tuple: values = np.array(input_values).reshape(-1,1) elif type(input_values) == np.ndarray: values = np.atleast_2d(input_values) elif type(input_values)==int or type(input_values)==float or type(np.int64): values = np.atleast_2d(np.array(input_values)) else: print('Type to transform not recognized') return values def merge_values(values1,values2): ''' Merges two numpy arrays by calculating all possible combinations of rows ''' array1 = values_to_array(values1) array2 = values_to_array(values2) if array1.size == 0: return array2 if array2.size == 0: return array1 merged_array = [] for row_array1 in array1: for row_array2 in array2: merged_row = np.hstack((row_array1,row_array2)) merged_array.append(merged_row) return np.atleast_2d(merged_array) def round_optimum(x_opt,domain): """ Rounds the some value x_opt to a feasible value in the function domain. """ x_opt_rounded = x_opt.copy() counter = 0 for variable in domain: if variable.type == 'continuous': var_dim = 1 elif variable.type == 'discrete': var_dim = 1 x_opt_rounded[0,counter:(counter+var_dim)] = round_discrete(x_opt[0,counter:(counter+var_dim)],variable.domain) elif variable.type == 'categorical': var_dim = len(variable.domain) x_opt_rounded[0,counter:(counter+var_dim)] = round_categorical(x_opt[0,counter:(counter+var_dim)]) elif variable.type == 'bandit': var_dim = variable.domain.shape[1] x_opt_rounded[0,counter:(counter+var_dim)] = round_bandit(x_opt[0,counter:(counter+var_dim)],variable.domain) else: raise Exception('Wrong type of variable') counter += var_dim return x_opt_rounded def round_categorical(values): """ Rounds a categorical variable by taking setting to one the max of the given vector and to zero the rest of the entries. """ rounded_values = np.zeros(values.shape) rounded_values[np.argmax(values)] = 1 return rounded_values def round_discrete(value,domain): """ Rounds a discrete variable by selecting the closest point in the domain """ rounded_value = domain[0] for domain_value in domain: if np.abs(domain_value-value)< np.abs(rounded_value-value): rounded_value = domain_value return rounded_value def round_bandit(value,domain): """ Rounds a discrete variable by selecting the closest point in the domain """ idx = np.argmin(((domain- value)**2).sum(1)) return domain[idx,:]
29.507752
141
0.652305
import numpy as np from scipy.special import erfc import time from ..core.errors import InvalidConfigError def compute_integrated_acquisition(acquisition,x): acqu_x = 0 for i in range(acquisition.model.num_hmc_samples): acquisition.model.model.kern[:] = acquisition.model.hmc_samples[i,:] acqu_x += acquisition.acquisition_function(x) acqu_x = acqu_x/acquisition.model.num_hmc_samples return acqu_x def compute_integrated_acquisition_withGradients(acquisition,x): acqu_x = 0 d_acqu_x = 0 for i in range(acquisition.model.num_hmc_samples): acquisition.model.model.kern[:] = acquisition.model.hmc_samples[i,:] acqu_x_sample, d_acqu_x_sample = acquisition.acquisition_function_withGradients(x) acqu_x += acqu_x_sample d_acqu_x += d_acqu_x_sample acqu_x = acqu_x/acquisition.model.num_hmc_samples d_acqu_x = d_acqu_x/acquisition.model.num_hmc_samples return acqu_x, d_acqu_x def best_guess(f,X): n = X.shape[0] xbest = np.zeros(n) for i in range(n): ff = f(X[0:(i+1)]) xbest[i] = ff[np.argmin(ff)] return xbest def samples_multidimensional_uniform(bounds,num_data): dim = len(bounds) Z_rand = np.zeros(shape=(num_data,dim)) for k in range(0,dim): Z_rand[:,k] = np.random.uniform(low=bounds[k][0],high=bounds[k][1],size=num_data) return Z_rand def reshape(x,input_dim): x = np.array(x) if x.size ==input_dim: x = x.reshape((1,input_dim)) return x def get_moments(model,x): input_dim = model.X.shape[1] x = reshape(x,input_dim) fmin = min(model.predict(model.X)[0]) m, v = model.predict(x) s = np.sqrt(np.clip(v, 0, np.inf)) return (m,s, fmin) def get_d_moments(model,x): input_dim = model.input_dim x = reshape(x,input_dim) _, v = model.predict(x) dmdx, dvdx = model.predictive_gradients(x) dmdx = dmdx[:,:,0] dsdx = dvdx / (2*np.sqrt(v)) return (dmdx, dsdx) def get_quantiles(acquisition_par, fmin, m, s): if isinstance(s, np.ndarray): s[s<1e-10] = 1e-10 elif s< 1e-10: s = 1e-10 u = (fmin-m-acquisition_par)/s phi = np.exp(-0.5 * u**2) / np.sqrt(2*np.pi) Phi = 0.5 * erfc(-u / np.sqrt(2)) return (phi, Phi, u) def best_value(Y,sign=1): n = Y.shape[0] Y_best = np.ones(n) for i in range(n): if sign == 1: Y_best[i]=Y[:(i+1)].min() else: Y_best[i]=Y[:(i+1)].max() return Y_best def spawn(f): def fun(pipe,x): pipe.send(f(x)) pipe.close() return fun def evaluate_function(f,X): num_data, dim_data = X.shape Y_eval = np.zeros((num_data, dim_data)) Y_time = np.zeros((num_data, 1)) for i in range(num_data): time_zero = time.time() Y_eval[i,:] = f(X[i,:]) Y_time[i,:] = time.time() - time_zero return Y_eval, Y_time def values_to_array(input_values): if type(input_values)==tuple: values = np.array(input_values).reshape(-1,1) elif type(input_values) == np.ndarray: values = np.atleast_2d(input_values) elif type(input_values)==int or type(input_values)==float or type(np.int64): values = np.atleast_2d(np.array(input_values)) else: print('Type to transform not recognized') return values def merge_values(values1,values2): array1 = values_to_array(values1) array2 = values_to_array(values2) if array1.size == 0: return array2 if array2.size == 0: return array1 merged_array = [] for row_array1 in array1: for row_array2 in array2: merged_row = np.hstack((row_array1,row_array2)) merged_array.append(merged_row) return np.atleast_2d(merged_array) def round_optimum(x_opt,domain): x_opt_rounded = x_opt.copy() counter = 0 for variable in domain: if variable.type == 'continuous': var_dim = 1 elif variable.type == 'discrete': var_dim = 1 x_opt_rounded[0,counter:(counter+var_dim)] = round_discrete(x_opt[0,counter:(counter+var_dim)],variable.domain) elif variable.type == 'categorical': var_dim = len(variable.domain) x_opt_rounded[0,counter:(counter+var_dim)] = round_categorical(x_opt[0,counter:(counter+var_dim)]) elif variable.type == 'bandit': var_dim = variable.domain.shape[1] x_opt_rounded[0,counter:(counter+var_dim)] = round_bandit(x_opt[0,counter:(counter+var_dim)],variable.domain) else: raise Exception('Wrong type of variable') counter += var_dim return x_opt_rounded def round_categorical(values): rounded_values = np.zeros(values.shape) rounded_values[np.argmax(values)] = 1 return rounded_values def round_discrete(value,domain): rounded_value = domain[0] for domain_value in domain: if np.abs(domain_value-value)< np.abs(rounded_value-value): rounded_value = domain_value return rounded_value def round_bandit(value,domain): idx = np.argmin(((domain- value)**2).sum(1)) return domain[idx,:]
true
true
f72a6096610e02f8d2fd5a97a6ffa630d71313b8
167
py
Python
usuario/admin.py
UNIZAR-30226-2021-05/Lector--Backend
8cc285216972f7485781ece51a88d5f02dc85013
[ "MIT" ]
null
null
null
usuario/admin.py
UNIZAR-30226-2021-05/Lector--Backend
8cc285216972f7485781ece51a88d5f02dc85013
[ "MIT" ]
null
null
null
usuario/admin.py
UNIZAR-30226-2021-05/Lector--Backend
8cc285216972f7485781ece51a88d5f02dc85013
[ "MIT" ]
null
null
null
from django.contrib import admin # Register your models here. from .models import Usuario, Preferencias admin.site.register(Usuario) admin.site.register(Preferencias)
27.833333
41
0.826347
from django.contrib import admin from .models import Usuario, Preferencias admin.site.register(Usuario) admin.site.register(Preferencias)
true
true
f72a6262313ce7497db5b2c9b1f07193731722d5
56,933
gyp
Python
node_modules/nodegit/vendor/libgit2.gyp
nodeframe/dite
bfe7d02af159b39b42a2c88fde4ce369db021c85
[ "MIT" ]
12
2016-08-19T23:21:41.000Z
2022-02-17T13:40:25.000Z
vendor/libgit2.gyp
Acidburn0zzz/nodegit
b4e85cd641ebf537edfe2f41f4687057bc517c02
[ "MIT" ]
null
null
null
vendor/libgit2.gyp
Acidburn0zzz/nodegit
b4e85cd641ebf537edfe2f41f4687057bc517c02
[ "MIT" ]
8
2015-10-24T11:57:55.000Z
2022-02-15T15:05:11.000Z
{ # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. "variables": { "target_arch%": "x86", "library%": "static_library", "openssl_enable_asm%": 0, # only supported with the Visual Studio 2012 (VC11) toolchain. "gcc_version%": 0, "is_clang%": 0, }, "targets": [ { "target_name": "libgit2", "type": "static_library", "defines": [ "GIT_THREADS", "GIT_SSH", # Node's util.h may be accidentally included so use this to guard # against compilation error. "SRC_UTIL_H_", ], "dependencies": [ "zlib", "<(module_root_dir)/vendor/http_parser/http_parser.gyp:http_parser", "libssh2", "openssl" ], "sources": [ "libgit2/src/array.h", "libgit2/src/attr.c", "libgit2/src/attr.h", "libgit2/src/attr_file.c", "libgit2/src/attr_file.h", "libgit2/src/attrcache.c", "libgit2/src/attrcache.h", "libgit2/src/bitvec.h", "libgit2/src/blame.c", "libgit2/src/blame.h", "libgit2/src/blame_git.c", "libgit2/src/blame_git.h", "libgit2/src/blob.c", "libgit2/src/blob.h", "libgit2/src/branch.c", "libgit2/src/branch.h", "libgit2/src/bswap.h", "libgit2/src/buf_text.c", "libgit2/src/buf_text.h", "libgit2/src/buffer.c", "libgit2/src/buffer.h", "libgit2/src/cache.c", "libgit2/src/cache.h", "libgit2/src/cc-compat.h", "libgit2/src/checkout.c", "libgit2/src/checkout.h", "libgit2/src/cherrypick.c", "libgit2/src/clone.c", "libgit2/src/clone.h", "libgit2/src/commit.c", "libgit2/src/commit.h", "libgit2/src/commit_list.c", "libgit2/src/commit_list.h", "libgit2/src/common.h", "libgit2/src/config.c", "libgit2/src/config.h", "libgit2/src/config_cache.c", "libgit2/src/config_file.c", "libgit2/src/config_file.h", "libgit2/src/crlf.c", "libgit2/src/date.c", "libgit2/src/delta-apply.c", "libgit2/src/delta-apply.h", "libgit2/src/delta.c", "libgit2/src/delta.h", "libgit2/src/diff.c", "libgit2/src/diff.h", "libgit2/src/diff_driver.c", "libgit2/src/diff_driver.h", "libgit2/src/diff_file.c", "libgit2/src/diff_file.h", "libgit2/src/diff_patch.c", "libgit2/src/diff_patch.h", "libgit2/src/diff_print.c", "libgit2/src/diff_stats.c", "libgit2/src/diff_tform.c", "libgit2/src/diff_xdiff.c", "libgit2/src/diff_xdiff.h", "libgit2/src/errors.c", "libgit2/src/fetch.c", "libgit2/src/fetch.h", "libgit2/src/fetchhead.c", "libgit2/src/fetchhead.h", "libgit2/src/filebuf.c", "libgit2/src/filebuf.h", "libgit2/src/fileops.c", "libgit2/src/fileops.h", "libgit2/src/filter.c", "libgit2/src/filter.h", "libgit2/src/fnmatch.c", "libgit2/src/fnmatch.h", "libgit2/src/global.c", "libgit2/src/global.h", "libgit2/src/graph.c", "libgit2/src/hash.c", "libgit2/src/hash.h", "libgit2/src/hashsig.c", "libgit2/src/hashsig.h", "libgit2/src/ident.c", "libgit2/src/ignore.c", "libgit2/src/ignore.h", "libgit2/src/index.c", "libgit2/src/index.h", "libgit2/src/indexer.c", "libgit2/src/iterator.c", "libgit2/src/iterator.h", "libgit2/src/khash.h", "libgit2/src/map.h", "libgit2/src/merge.c", "libgit2/src/merge.h", "libgit2/src/merge_file.c", "libgit2/src/merge_file.h", "libgit2/src/message.c", "libgit2/src/message.h", "libgit2/src/mwindow.c", "libgit2/src/mwindow.h", "libgit2/src/netops.c", "libgit2/src/netops.h", "libgit2/src/notes.c", "libgit2/src/notes.h", "libgit2/src/object.c", "libgit2/src/object.h", "libgit2/src/object_api.c", "libgit2/src/odb.c", "libgit2/src/odb.h", "libgit2/src/odb_loose.c", "libgit2/src/odb_mempack.c", "libgit2/src/odb_pack.c", "libgit2/src/offmap.h", "libgit2/src/oid.c", "libgit2/src/oid.h", "libgit2/src/oidmap.h", "libgit2/src/pack-objects.c", "libgit2/src/pack-objects.h", "libgit2/src/pack.c", "libgit2/src/pack.h", "libgit2/src/path.c", "libgit2/src/path.h", "libgit2/src/pathspec.c", "libgit2/src/pathspec.h", "libgit2/src/pool.c", "libgit2/src/pool.h", "libgit2/src/posix.c", "libgit2/src/posix.h", "libgit2/src/pqueue.c", "libgit2/src/pqueue.h", "libgit2/src/push.c", "libgit2/src/push.h", "libgit2/src/refdb.c", "libgit2/src/refdb.h", "libgit2/src/refdb_fs.c", "libgit2/src/refdb_fs.h", "libgit2/src/reflog.c", "libgit2/src/reflog.h", "libgit2/src/refs.c", "libgit2/src/refs.h", "libgit2/src/refspec.c", "libgit2/src/refspec.h", "libgit2/src/remote.c", "libgit2/src/remote.h", "libgit2/src/repo_template.h", "libgit2/src/repository.c", "libgit2/src/repository.h", "libgit2/src/reset.c", "libgit2/src/revert.c", "libgit2/src/revparse.c", "libgit2/src/revwalk.c", "libgit2/src/revwalk.h", "libgit2/src/settings.c", "libgit2/src/sha1_lookup.c", "libgit2/src/sha1_lookup.h", "libgit2/src/signature.c", "libgit2/src/signature.h", "libgit2/src/sortedcache.c", "libgit2/src/sortedcache.h", "libgit2/src/stash.c", "libgit2/src/status.c", "libgit2/src/status.h", "libgit2/src/strmap.c", "libgit2/src/strmap.h", "libgit2/src/strnlen.h", "libgit2/src/submodule.c", "libgit2/src/submodule.h", "libgit2/src/sysdir.c", "libgit2/src/sysdir.h", "libgit2/src/tag.c", "libgit2/src/tag.h", "libgit2/src/thread-utils.c", "libgit2/src/thread-utils.h", "libgit2/src/trace.c", "libgit2/src/trace.h", "libgit2/src/transport.c", "libgit2/src/tree-cache.c", "libgit2/src/tree-cache.h", "libgit2/src/tree.c", "libgit2/src/tree.h", "libgit2/src/tsort.c", "libgit2/src/userdiff.h", "libgit2/src/util.c", "libgit2/src/util.h", "libgit2/src/vector.c", "libgit2/src/vector.h", "libgit2/src/zstream.c", "libgit2/src/zstream.h", "libgit2/src/hash/hash_generic.c", "libgit2/src/hash/hash_generic.h", "libgit2/src/hash/hash_openssl.h", "libgit2/src/transports/cred.c", "libgit2/src/transports/cred_helpers.c", "libgit2/src/transports/git.c", "libgit2/src/transports/http.c", "libgit2/src/transports/local.c", "libgit2/src/transports/smart.c", "libgit2/src/transports/smart.h", "libgit2/src/transports/smart_pkt.c", "libgit2/src/transports/smart_protocol.c", "libgit2/src/transports/ssh.c", "libgit2/src/xdiff/xdiff.h", "libgit2/src/xdiff/xdiffi.c", "libgit2/src/xdiff/xdiffi.h", "libgit2/src/xdiff/xemit.c", "libgit2/src/xdiff/xemit.h", "libgit2/src/xdiff/xhistogram.c", "libgit2/src/xdiff/xinclude.h", "libgit2/src/xdiff/xmacros.h", "libgit2/src/xdiff/xmerge.c", "libgit2/src/xdiff/xpatience.c", "libgit2/src/xdiff/xprepare.c", "libgit2/src/xdiff/xprepare.h", "libgit2/src/xdiff/xtypes.h", "libgit2/src/xdiff/xutils.c", "libgit2/src/xdiff/xutils.h", ], "conditions": [ ["OS!='win'", { "defines": [ "GIT_SSL" ], }], ["OS=='win'", {}, { "sources": [ "libgit2/src/unix/map.c", "libgit2/src/unix/posix.h", "libgit2/src/unix/realpath.c", ] }], ["OS=='linux'", { "cflags": [ "-DGIT_SSH", "-DGIT_SSL", "-w", ], }], ["OS=='win'", { "defines": [ "GIT_WINHTTP", ], "msvs_settings": { "VCLinkerTool": { "AdditionalDependencies": [ "ws2_32.lib", ], }, # Workaround of a strange bug: # TargetMachine + static_library + x64 = nothing. "conditions": [ ["target_arch=='x64'", { "VCLibrarianTool": { "AdditionalOptions": [ "/MACHINE:X64", ], }, }, { "VCLibrarianTool": { "AdditionalOptions": [ "/MACHINE:x86", ], }, }], ], }, "msvs_disabled_warnings": [ # Conversion from 'ssize_t' to 'int32_t', possible loss of data. 4244, # Conversion from 'size_t' to 'int', possible loss of data. 4267, # Different 'volatile' qualifiers. 4090, # 'volatile void *' differs in levels of indirection from 'int'. 4047, # 'InterlockedDecrement' undefined; assuming extern returning int. 4013, ], "sources": [ "libgit2/src/win32/dir.c", "libgit2/src/win32/dir.h", "libgit2/src/win32/error.c", "libgit2/src/win32/error.h", "libgit2/src/win32/findfile.c", "libgit2/src/win32/findfile.h", "libgit2/src/win32/git2.rc", "libgit2/src/win32/map.c", "libgit2/src/win32/mingw-compat.h", "libgit2/src/win32/msvc-compat.h", "libgit2/src/win32/posix.h", "libgit2/src/win32/posix_w32.c", "libgit2/src/win32/precompiled.c", "libgit2/src/win32/precompiled.h", "libgit2/src/win32/pthread.c", "libgit2/src/win32/pthread.h", "libgit2/src/win32/reparse.h", "libgit2/src/win32/utf-conv.c", "libgit2/src/win32/utf-conv.h", "libgit2/src/win32/version.h", "libgit2/src/win32/w32_util.c", "libgit2/src/win32/w32_util.h", "libgit2/src/win32/path_w32.c", "libgit2/src/win32/path_w32.h", "libgit2/src/transports/winhttp.c", "libgit2/deps/regex/regex.c", ], }, { "libraries": [ "-lpthread", ], "sources": [ "libgit2/src/unix/map.c", "libgit2/src/unix/posix.h", "libgit2/src/unix/realpath.c", ], "cflags": [ "-Wno-missing-field-initializers", "-Wno-unused-variable", "-Wno-deprecated-declarations", ], "xcode_settings": { "WARNING_CFLAGS": [ "-Wno-missing-field-initializers", "-Wno-unused-variable", "-Wno-deprecated-declarations", "-Wno-uninitialized", ], }, }, ] ], "include_dirs": [ "libgit2/include", "libgit2/src", "libgit2/deps/regex" ], "direct_dependent_settings": { "include_dirs": [ "libgit2/include", ], }, }, { "target_name": "zlib", "type": "static_library", "sources": [ "libgit2/deps/zlib/adler32.c", "libgit2/deps/zlib/crc32.c", "libgit2/deps/zlib/crc32.h", "libgit2/deps/zlib/deflate.c", "libgit2/deps/zlib/deflate.h", "libgit2/deps/zlib/inffast.c", "libgit2/deps/zlib/inffast.h", "libgit2/deps/zlib/inffixed.h", "libgit2/deps/zlib/inflate.c", "libgit2/deps/zlib/inflate.h", "libgit2/deps/zlib/inftrees.c", "libgit2/deps/zlib/inftrees.h", "libgit2/deps/zlib/trees.c", "libgit2/deps/zlib/trees.h", "libgit2/deps/zlib/zconf.h", "libgit2/deps/zlib/zlib.h", "libgit2/deps/zlib/zutil.c", "libgit2/deps/zlib/zutil.h", ], "defines": [ "NO_VIZ", "STDC", "NO_GZIP", ], "include_dirs": [ "libgit2/include", "libgit2/deps/regex", ], "direct_dependent_settings": { "include_dirs": [ "libgit2/deps/zlib", ], }, }, { "target_name": "libssh2", "type": "static_library", "defines": [ "NETSNMP_ENABLE_IPV6" ], "sources": [ "libssh2/src/agent.c", "libssh2/src/crypt.c", "libssh2/src/keepalive.c", "libssh2/src/libgcrypt.c", "libssh2/src/openssl.c", "libssh2/src/publickey.c", "libssh2/src/sftp.c", "libssh2/src/version.c", "libssh2/src/channel.c", "libssh2/src/global.c", "libssh2/src/kex.c", "libssh2/src/mac.c", "libssh2/src/packet.c", "libssh2/src/scp.c", "libssh2/src/transport.c", "libssh2/src/comp.c", "libssh2/src/hostkey.c", "libssh2/src/knownhost.c", "libssh2/src/misc.c", "libssh2/src/pem.c", "libssh2/src/session.c", "libssh2/src/userauth.c", ], "include_dirs": [ ".", "libssh2/include", ], "dependencies": [ "openssl" ], "direct_dependent_settings": { "include_dirs": [ "libssh2/include" ] }, "conditions": [ ["OS=='win'", { "include_dirs": [ "libssh2/src", "libssh2/win32", "libssh2/include" ], "direct_dependent_settings": { "include_dirs": [ "libssh2/src", "libssh2/win32", "libssh2/include" ] } }], ] }, { "target_name": "openssl", "type": "static_library", "defines": [ #No clue what these are for. "L_ENDIAN", "PURIFY", "_REENTRANT", "NO_WINDOWS_BRAINDEATH", ], "include_dirs": [ ".", "openssl/openssl", "openssl/openssl/crypto", "openssl/openssl/crypto/asn1", "openssl/openssl/crypto/evp", "openssl/openssl/crypto/md2", "openssl/openssl/crypto/modes", "openssl/openssl/crypto/store", "openssl/openssl/include", ], "direct_dependent_settings": { "include_dirs": [ "openssl/openssl/include", "openssl/openssl/include/openssl", ] }, "sources": [ "openssl/openssl/ssl/bio_ssl.c", "openssl/openssl/ssl/d1_both.c", "openssl/openssl/ssl/d1_clnt.c", "openssl/openssl/ssl/d1_enc.c", "openssl/openssl/ssl/d1_lib.c", "openssl/openssl/ssl/d1_meth.c", "openssl/openssl/ssl/d1_pkt.c", "openssl/openssl/ssl/d1_srtp.c", "openssl/openssl/ssl/d1_srvr.c", "openssl/openssl/ssl/kssl.c", "openssl/openssl/ssl/s23_clnt.c", "openssl/openssl/ssl/s23_lib.c", "openssl/openssl/ssl/s23_meth.c", "openssl/openssl/ssl/s23_pkt.c", "openssl/openssl/ssl/s23_srvr.c", "openssl/openssl/ssl/s2_clnt.c", "openssl/openssl/ssl/s2_enc.c", "openssl/openssl/ssl/s2_lib.c", "openssl/openssl/ssl/s2_meth.c", "openssl/openssl/ssl/s2_pkt.c", "openssl/openssl/ssl/s2_srvr.c", "openssl/openssl/ssl/s3_both.c", "openssl/openssl/ssl/s3_clnt.c", "openssl/openssl/ssl/s3_enc.c", "openssl/openssl/ssl/s3_lib.c", "openssl/openssl/ssl/s3_meth.c", "openssl/openssl/ssl/s3_pkt.c", "openssl/openssl/ssl/s3_srvr.c", "openssl/openssl/ssl/s3_cbc.c", "openssl/openssl/ssl/ssl_algs.c", "openssl/openssl/ssl/ssl_asn1.c", "openssl/openssl/ssl/ssl_cert.c", "openssl/openssl/ssl/ssl_ciph.c", "openssl/openssl/ssl/ssl_err.c", "openssl/openssl/ssl/ssl_err2.c", "openssl/openssl/ssl/ssl_lib.c", "openssl/openssl/ssl/ssl_rsa.c", "openssl/openssl/ssl/ssl_sess.c", "openssl/openssl/ssl/ssl_stat.c", "openssl/openssl/ssl/ssl_txt.c", "openssl/openssl/ssl/t1_clnt.c", "openssl/openssl/ssl/t1_enc.c", "openssl/openssl/ssl/t1_lib.c", "openssl/openssl/ssl/t1_meth.c", "openssl/openssl/ssl/t1_reneg.c", "openssl/openssl/ssl/t1_srvr.c", "openssl/openssl/ssl/tls_srp.c", "openssl/openssl/crypto/aes/aes_cfb.c", "openssl/openssl/crypto/aes/aes_ctr.c", "openssl/openssl/crypto/aes/aes_ecb.c", "openssl/openssl/crypto/aes/aes_ige.c", "openssl/openssl/crypto/aes/aes_misc.c", "openssl/openssl/crypto/aes/aes_ofb.c", "openssl/openssl/crypto/aes/aes_wrap.c", "openssl/openssl/crypto/asn1/a_bitstr.c", "openssl/openssl/crypto/asn1/a_bool.c", "openssl/openssl/crypto/asn1/a_bytes.c", "openssl/openssl/crypto/asn1/a_d2i_fp.c", "openssl/openssl/crypto/asn1/a_digest.c", "openssl/openssl/crypto/asn1/a_dup.c", "openssl/openssl/crypto/asn1/a_enum.c", "openssl/openssl/crypto/asn1/a_gentm.c", "openssl/openssl/crypto/asn1/a_i2d_fp.c", "openssl/openssl/crypto/asn1/a_int.c", "openssl/openssl/crypto/asn1/a_mbstr.c", "openssl/openssl/crypto/asn1/a_object.c", "openssl/openssl/crypto/asn1/a_octet.c", "openssl/openssl/crypto/asn1/a_print.c", "openssl/openssl/crypto/asn1/a_set.c", "openssl/openssl/crypto/asn1/a_sign.c", "openssl/openssl/crypto/asn1/a_strex.c", "openssl/openssl/crypto/asn1/a_strnid.c", "openssl/openssl/crypto/asn1/a_time.c", "openssl/openssl/crypto/asn1/a_type.c", "openssl/openssl/crypto/asn1/a_utctm.c", "openssl/openssl/crypto/asn1/a_utf8.c", "openssl/openssl/crypto/asn1/a_verify.c", "openssl/openssl/crypto/asn1/ameth_lib.c", "openssl/openssl/crypto/asn1/asn1_err.c", "openssl/openssl/crypto/asn1/asn1_gen.c", "openssl/openssl/crypto/asn1/asn1_lib.c", "openssl/openssl/crypto/asn1/asn1_par.c", "openssl/openssl/crypto/asn1/asn_mime.c", "openssl/openssl/crypto/asn1/asn_moid.c", "openssl/openssl/crypto/asn1/asn_pack.c", "openssl/openssl/crypto/asn1/bio_asn1.c", "openssl/openssl/crypto/asn1/bio_ndef.c", "openssl/openssl/crypto/asn1/d2i_pr.c", "openssl/openssl/crypto/asn1/d2i_pu.c", "openssl/openssl/crypto/asn1/evp_asn1.c", "openssl/openssl/crypto/asn1/f_enum.c", "openssl/openssl/crypto/asn1/f_int.c", "openssl/openssl/crypto/asn1/f_string.c", "openssl/openssl/crypto/asn1/i2d_pr.c", "openssl/openssl/crypto/asn1/i2d_pu.c", "openssl/openssl/crypto/asn1/n_pkey.c", "openssl/openssl/crypto/asn1/nsseq.c", "openssl/openssl/crypto/asn1/p5_pbe.c", "openssl/openssl/crypto/asn1/p5_pbev2.c", "openssl/openssl/crypto/asn1/p8_pkey.c", "openssl/openssl/crypto/asn1/t_bitst.c", "openssl/openssl/crypto/asn1/t_crl.c", "openssl/openssl/crypto/asn1/t_pkey.c", "openssl/openssl/crypto/asn1/t_req.c", "openssl/openssl/crypto/asn1/t_spki.c", "openssl/openssl/crypto/asn1/t_x509.c", "openssl/openssl/crypto/asn1/t_x509a.c", "openssl/openssl/crypto/asn1/tasn_dec.c", "openssl/openssl/crypto/asn1/tasn_enc.c", "openssl/openssl/crypto/asn1/tasn_fre.c", "openssl/openssl/crypto/asn1/tasn_new.c", "openssl/openssl/crypto/asn1/tasn_prn.c", "openssl/openssl/crypto/asn1/tasn_typ.c", "openssl/openssl/crypto/asn1/tasn_utl.c", "openssl/openssl/crypto/asn1/x_algor.c", "openssl/openssl/crypto/asn1/x_attrib.c", "openssl/openssl/crypto/asn1/x_bignum.c", "openssl/openssl/crypto/asn1/x_crl.c", "openssl/openssl/crypto/asn1/x_exten.c", "openssl/openssl/crypto/asn1/x_info.c", "openssl/openssl/crypto/asn1/x_long.c", "openssl/openssl/crypto/asn1/x_name.c", "openssl/openssl/crypto/asn1/x_nx509.c", "openssl/openssl/crypto/asn1/x_pkey.c", "openssl/openssl/crypto/asn1/x_pubkey.c", "openssl/openssl/crypto/asn1/x_req.c", "openssl/openssl/crypto/asn1/x_sig.c", "openssl/openssl/crypto/asn1/x_spki.c", "openssl/openssl/crypto/asn1/x_val.c", "openssl/openssl/crypto/asn1/x_x509.c", "openssl/openssl/crypto/asn1/x_x509a.c", "openssl/openssl/crypto/bf/bf_cfb64.c", "openssl/openssl/crypto/bf/bf_ecb.c", "openssl/openssl/crypto/bf/bf_ofb64.c", "openssl/openssl/crypto/bf/bf_skey.c", "openssl/openssl/crypto/bio/b_dump.c", "openssl/openssl/crypto/bio/b_print.c", "openssl/openssl/crypto/bio/b_sock.c", "openssl/openssl/crypto/bio/bf_buff.c", "openssl/openssl/crypto/bio/bf_nbio.c", "openssl/openssl/crypto/bio/bf_null.c", "openssl/openssl/crypto/bio/bio_cb.c", "openssl/openssl/crypto/bio/bio_err.c", "openssl/openssl/crypto/bio/bio_lib.c", "openssl/openssl/crypto/bio/bss_acpt.c", "openssl/openssl/crypto/bio/bss_bio.c", "openssl/openssl/crypto/bio/bss_conn.c", "openssl/openssl/crypto/bio/bss_dgram.c", "openssl/openssl/crypto/bio/bss_fd.c", "openssl/openssl/crypto/bio/bss_file.c", "openssl/openssl/crypto/bio/bss_log.c", "openssl/openssl/crypto/bio/bss_mem.c", "openssl/openssl/crypto/bio/bss_null.c", "openssl/openssl/crypto/bio/bss_sock.c", "openssl/openssl/crypto/bn/bn_add.c", "openssl/openssl/crypto/bn/bn_blind.c", "openssl/openssl/crypto/bn/bn_const.c", "openssl/openssl/crypto/bn/bn_ctx.c", "openssl/openssl/crypto/bn/bn_depr.c", "openssl/openssl/crypto/bn/bn_div.c", "openssl/openssl/crypto/bn/bn_err.c", "openssl/openssl/crypto/bn/bn_exp.c", "openssl/openssl/crypto/bn/bn_exp2.c", "openssl/openssl/crypto/bn/bn_gcd.c", "openssl/openssl/crypto/bn/bn_gf2m.c", "openssl/openssl/crypto/bn/bn_kron.c", "openssl/openssl/crypto/bn/bn_lib.c", "openssl/openssl/crypto/bn/bn_mod.c", "openssl/openssl/crypto/bn/bn_mont.c", "openssl/openssl/crypto/bn/bn_mpi.c", "openssl/openssl/crypto/bn/bn_mul.c", "openssl/openssl/crypto/bn/bn_nist.c", "openssl/openssl/crypto/bn/bn_prime.c", "openssl/openssl/crypto/bn/bn_print.c", "openssl/openssl/crypto/bn/bn_rand.c", "openssl/openssl/crypto/bn/bn_recp.c", "openssl/openssl/crypto/bn/bn_shift.c", "openssl/openssl/crypto/bn/bn_sqr.c", "openssl/openssl/crypto/bn/bn_sqrt.c", "openssl/openssl/crypto/bn/bn_word.c", "openssl/openssl/crypto/bn/bn_x931p.c", "openssl/openssl/crypto/buffer/buf_err.c", "openssl/openssl/crypto/buffer/buf_str.c", "openssl/openssl/crypto/buffer/buffer.c", "openssl/openssl/crypto/camellia/cmll_cfb.c", "openssl/openssl/crypto/camellia/cmll_ctr.c", "openssl/openssl/crypto/camellia/cmll_ecb.c", "openssl/openssl/crypto/camellia/cmll_ofb.c", "openssl/openssl/crypto/camellia/cmll_utl.c", "openssl/openssl/crypto/cast/c_cfb64.c", "openssl/openssl/crypto/cast/c_ecb.c", "openssl/openssl/crypto/cast/c_ofb64.c", "openssl/openssl/crypto/cast/c_skey.c", "openssl/openssl/crypto/cmac/cm_ameth.c", "openssl/openssl/crypto/cmac/cm_pmeth.c", "openssl/openssl/crypto/cmac/cmac.c", "openssl/openssl/crypto/cms/cms_asn1.c", "openssl/openssl/crypto/cms/cms_att.c", "openssl/openssl/crypto/cms/cms_cd.c", "openssl/openssl/crypto/cms/cms_dd.c", "openssl/openssl/crypto/cms/cms_enc.c", "openssl/openssl/crypto/cms/cms_env.c", "openssl/openssl/crypto/cms/cms_err.c", "openssl/openssl/crypto/cms/cms_ess.c", "openssl/openssl/crypto/cms/cms_io.c", "openssl/openssl/crypto/cms/cms_lib.c", "openssl/openssl/crypto/cms/cms_pwri.c", "openssl/openssl/crypto/cms/cms_sd.c", "openssl/openssl/crypto/cms/cms_smime.c", "openssl/openssl/crypto/comp/c_rle.c", "openssl/openssl/crypto/comp/c_zlib.c", "openssl/openssl/crypto/comp/comp_err.c", "openssl/openssl/crypto/comp/comp_lib.c", "openssl/openssl/crypto/conf/conf_api.c", "openssl/openssl/crypto/conf/conf_def.c", "openssl/openssl/crypto/conf/conf_err.c", "openssl/openssl/crypto/conf/conf_lib.c", "openssl/openssl/crypto/conf/conf_mall.c", "openssl/openssl/crypto/conf/conf_mod.c", "openssl/openssl/crypto/conf/conf_sap.c", "openssl/openssl/crypto/cpt_err.c", "openssl/openssl/crypto/cryptlib.c", "openssl/openssl/crypto/cversion.c", "openssl/openssl/crypto/des/cbc_cksm.c", "openssl/openssl/crypto/des/cbc_enc.c", "openssl/openssl/crypto/des/cfb64ede.c", "openssl/openssl/crypto/des/cfb64enc.c", "openssl/openssl/crypto/des/cfb_enc.c", "openssl/openssl/crypto/des/des_old.c", "openssl/openssl/crypto/des/des_old2.c", "openssl/openssl/crypto/des/ecb3_enc.c", "openssl/openssl/crypto/des/ecb_enc.c", "openssl/openssl/crypto/des/ede_cbcm_enc.c", "openssl/openssl/crypto/des/enc_read.c", "openssl/openssl/crypto/des/enc_writ.c", "openssl/openssl/crypto/des/fcrypt.c", "openssl/openssl/crypto/des/ofb64ede.c", "openssl/openssl/crypto/des/ofb64enc.c", "openssl/openssl/crypto/des/ofb_enc.c", "openssl/openssl/crypto/des/pcbc_enc.c", "openssl/openssl/crypto/des/qud_cksm.c", "openssl/openssl/crypto/des/rand_key.c", "openssl/openssl/crypto/des/read2pwd.c", "openssl/openssl/crypto/des/rpc_enc.c", "openssl/openssl/crypto/des/set_key.c", "openssl/openssl/crypto/des/str2key.c", "openssl/openssl/crypto/des/xcbc_enc.c", "openssl/openssl/crypto/dh/dh_ameth.c", "openssl/openssl/crypto/dh/dh_asn1.c", "openssl/openssl/crypto/dh/dh_check.c", "openssl/openssl/crypto/dh/dh_depr.c", "openssl/openssl/crypto/dh/dh_err.c", "openssl/openssl/crypto/dh/dh_gen.c", "openssl/openssl/crypto/dh/dh_key.c", "openssl/openssl/crypto/dh/dh_lib.c", "openssl/openssl/crypto/dh/dh_pmeth.c", "openssl/openssl/crypto/dh/dh_prn.c", "openssl/openssl/crypto/dsa/dsa_ameth.c", "openssl/openssl/crypto/dsa/dsa_asn1.c", "openssl/openssl/crypto/dsa/dsa_depr.c", "openssl/openssl/crypto/dsa/dsa_err.c", "openssl/openssl/crypto/dsa/dsa_gen.c", "openssl/openssl/crypto/dsa/dsa_key.c", "openssl/openssl/crypto/dsa/dsa_lib.c", "openssl/openssl/crypto/dsa/dsa_ossl.c", "openssl/openssl/crypto/dsa/dsa_pmeth.c", "openssl/openssl/crypto/dsa/dsa_prn.c", "openssl/openssl/crypto/dsa/dsa_sign.c", "openssl/openssl/crypto/dsa/dsa_vrf.c", "openssl/openssl/crypto/dso/dso_beos.c", "openssl/openssl/crypto/dso/dso_dl.c", "openssl/openssl/crypto/dso/dso_dlfcn.c", "openssl/openssl/crypto/dso/dso_err.c", "openssl/openssl/crypto/dso/dso_lib.c", "openssl/openssl/crypto/dso/dso_null.c", "openssl/openssl/crypto/dso/dso_openssl.c", "openssl/openssl/crypto/dso/dso_vms.c", "openssl/openssl/crypto/dso/dso_win32.c", "openssl/openssl/crypto/ebcdic.c", "openssl/openssl/crypto/ec/ec2_mult.c", "openssl/openssl/crypto/ec/ec2_oct.c", "openssl/openssl/crypto/ec/ec2_smpl.c", "openssl/openssl/crypto/ec/ec_ameth.c", "openssl/openssl/crypto/ec/ec_asn1.c", "openssl/openssl/crypto/ec/ec_check.c", "openssl/openssl/crypto/ec/ec_curve.c", "openssl/openssl/crypto/ec/ec_cvt.c", "openssl/openssl/crypto/ec/ec_err.c", "openssl/openssl/crypto/ec/ec_key.c", "openssl/openssl/crypto/ec/ec_lib.c", "openssl/openssl/crypto/ec/ec_mult.c", "openssl/openssl/crypto/ec/ec_oct.c", "openssl/openssl/crypto/ec/ec_pmeth.c", "openssl/openssl/crypto/ec/ec_print.c", "openssl/openssl/crypto/ec/eck_prn.c", "openssl/openssl/crypto/ec/ecp_mont.c", "openssl/openssl/crypto/ec/ecp_nist.c", "openssl/openssl/crypto/ec/ecp_nistp224.c", "openssl/openssl/crypto/ec/ecp_nistp256.c", "openssl/openssl/crypto/ec/ecp_nistp521.c", "openssl/openssl/crypto/ec/ecp_nistputil.c", "openssl/openssl/crypto/ec/ecp_oct.c", "openssl/openssl/crypto/ec/ecp_smpl.c", "openssl/openssl/crypto/ecdh/ech_err.c", "openssl/openssl/crypto/ecdh/ech_key.c", "openssl/openssl/crypto/ecdh/ech_lib.c", "openssl/openssl/crypto/ecdh/ech_ossl.c", "openssl/openssl/crypto/ecdsa/ecs_asn1.c", "openssl/openssl/crypto/ecdsa/ecs_err.c", "openssl/openssl/crypto/ecdsa/ecs_lib.c", "openssl/openssl/crypto/ecdsa/ecs_ossl.c", "openssl/openssl/crypto/ecdsa/ecs_sign.c", "openssl/openssl/crypto/ecdsa/ecs_vrf.c", "openssl/openssl/crypto/engine/eng_all.c", "openssl/openssl/crypto/engine/eng_cnf.c", "openssl/openssl/crypto/engine/eng_cryptodev.c", "openssl/openssl/crypto/engine/eng_ctrl.c", "openssl/openssl/crypto/engine/eng_dyn.c", "openssl/openssl/crypto/engine/eng_err.c", "openssl/openssl/crypto/engine/eng_fat.c", "openssl/openssl/crypto/engine/eng_init.c", "openssl/openssl/crypto/engine/eng_lib.c", "openssl/openssl/crypto/engine/eng_list.c", "openssl/openssl/crypto/engine/eng_openssl.c", "openssl/openssl/crypto/engine/eng_pkey.c", "openssl/openssl/crypto/engine/eng_rdrand.c", "openssl/openssl/crypto/engine/eng_rsax.c", "openssl/openssl/crypto/engine/eng_table.c", "openssl/openssl/crypto/engine/tb_asnmth.c", "openssl/openssl/crypto/engine/tb_cipher.c", "openssl/openssl/crypto/engine/tb_dh.c", "openssl/openssl/crypto/engine/tb_digest.c", "openssl/openssl/crypto/engine/tb_dsa.c", "openssl/openssl/crypto/engine/tb_ecdh.c", "openssl/openssl/crypto/engine/tb_ecdsa.c", "openssl/openssl/crypto/engine/tb_pkmeth.c", "openssl/openssl/crypto/engine/tb_rand.c", "openssl/openssl/crypto/engine/tb_rsa.c", "openssl/openssl/crypto/engine/tb_store.c", "openssl/openssl/crypto/err/err.c", "openssl/openssl/crypto/err/err_all.c", "openssl/openssl/crypto/err/err_prn.c", "openssl/openssl/crypto/evp/bio_b64.c", "openssl/openssl/crypto/evp/bio_enc.c", "openssl/openssl/crypto/evp/bio_md.c", "openssl/openssl/crypto/evp/bio_ok.c", "openssl/openssl/crypto/evp/c_all.c", "openssl/openssl/crypto/evp/c_allc.c", "openssl/openssl/crypto/evp/c_alld.c", "openssl/openssl/crypto/evp/digest.c", "openssl/openssl/crypto/evp/e_aes.c", "openssl/openssl/crypto/evp/e_aes_cbc_hmac_sha1.c", "openssl/openssl/crypto/evp/e_bf.c", "openssl/openssl/crypto/evp/e_camellia.c", "openssl/openssl/crypto/evp/e_cast.c", "openssl/openssl/crypto/evp/e_des.c", "openssl/openssl/crypto/evp/e_des3.c", "openssl/openssl/crypto/evp/e_idea.c", "openssl/openssl/crypto/evp/e_null.c", "openssl/openssl/crypto/evp/e_old.c", "openssl/openssl/crypto/evp/e_rc2.c", "openssl/openssl/crypto/evp/e_rc4.c", "openssl/openssl/crypto/evp/e_rc4_hmac_md5.c", "openssl/openssl/crypto/evp/e_rc5.c", "openssl/openssl/crypto/evp/e_seed.c", "openssl/openssl/crypto/evp/e_xcbc_d.c", "openssl/openssl/crypto/evp/encode.c", "openssl/openssl/crypto/evp/evp_acnf.c", "openssl/openssl/crypto/evp/evp_cnf.c", "openssl/openssl/crypto/evp/evp_enc.c", "openssl/openssl/crypto/evp/evp_err.c", "openssl/openssl/crypto/evp/evp_fips.c", "openssl/openssl/crypto/evp/evp_key.c", "openssl/openssl/crypto/evp/evp_lib.c", "openssl/openssl/crypto/evp/evp_pbe.c", "openssl/openssl/crypto/evp/evp_pkey.c", "openssl/openssl/crypto/evp/m_dss.c", "openssl/openssl/crypto/evp/m_dss1.c", "openssl/openssl/crypto/evp/m_ecdsa.c", "openssl/openssl/crypto/evp/m_md2.c", "openssl/openssl/crypto/evp/m_md4.c", "openssl/openssl/crypto/evp/m_md5.c", "openssl/openssl/crypto/evp/m_mdc2.c", "openssl/openssl/crypto/evp/m_null.c", "openssl/openssl/crypto/evp/m_ripemd.c", "openssl/openssl/crypto/evp/m_sha.c", "openssl/openssl/crypto/evp/m_sha1.c", "openssl/openssl/crypto/evp/m_sigver.c", "openssl/openssl/crypto/evp/m_wp.c", "openssl/openssl/crypto/evp/names.c", "openssl/openssl/crypto/evp/p5_crpt.c", "openssl/openssl/crypto/evp/p5_crpt2.c", "openssl/openssl/crypto/evp/p_dec.c", "openssl/openssl/crypto/evp/p_enc.c", "openssl/openssl/crypto/evp/p_lib.c", "openssl/openssl/crypto/evp/p_open.c", "openssl/openssl/crypto/evp/p_seal.c", "openssl/openssl/crypto/evp/p_sign.c", "openssl/openssl/crypto/evp/p_verify.c", "openssl/openssl/crypto/evp/pmeth_fn.c", "openssl/openssl/crypto/evp/pmeth_gn.c", "openssl/openssl/crypto/evp/pmeth_lib.c", "openssl/openssl/crypto/ex_data.c", "openssl/openssl/crypto/fips_ers.c", "openssl/openssl/crypto/hmac/hm_ameth.c", "openssl/openssl/crypto/hmac/hm_pmeth.c", "openssl/openssl/crypto/hmac/hmac.c", "openssl/openssl/crypto/idea/i_cbc.c", "openssl/openssl/crypto/idea/i_cfb64.c", "openssl/openssl/crypto/idea/i_ecb.c", "openssl/openssl/crypto/idea/i_ofb64.c", "openssl/openssl/crypto/idea/i_skey.c", "openssl/openssl/crypto/krb5/krb5_asn.c", "openssl/openssl/crypto/lhash/lh_stats.c", "openssl/openssl/crypto/lhash/lhash.c", "openssl/openssl/crypto/md2/md2_dgst.c", "openssl/openssl/crypto/md2/md2_one.c", "openssl/openssl/crypto/md4/md4_dgst.c", "openssl/openssl/crypto/md4/md4_one.c", "openssl/openssl/crypto/md5/md5_dgst.c", "openssl/openssl/crypto/md5/md5_one.c", "openssl/openssl/crypto/mdc2/mdc2_one.c", "openssl/openssl/crypto/mdc2/mdc2dgst.c", "openssl/openssl/crypto/mem.c", "openssl/openssl/crypto/mem_dbg.c", "openssl/openssl/crypto/modes/cbc128.c", "openssl/openssl/crypto/modes/ccm128.c", "openssl/openssl/crypto/modes/cfb128.c", "openssl/openssl/crypto/modes/ctr128.c", "openssl/openssl/crypto/modes/cts128.c", "openssl/openssl/crypto/modes/gcm128.c", "openssl/openssl/crypto/modes/ofb128.c", "openssl/openssl/crypto/modes/xts128.c", "openssl/openssl/crypto/o_dir.c", "openssl/openssl/crypto/o_fips.c", "openssl/openssl/crypto/o_init.c", "openssl/openssl/crypto/o_str.c", "openssl/openssl/crypto/o_time.c", "openssl/openssl/crypto/objects/o_names.c", "openssl/openssl/crypto/objects/obj_dat.c", "openssl/openssl/crypto/objects/obj_err.c", "openssl/openssl/crypto/objects/obj_lib.c", "openssl/openssl/crypto/objects/obj_xref.c", "openssl/openssl/crypto/ocsp/ocsp_asn.c", "openssl/openssl/crypto/ocsp/ocsp_cl.c", "openssl/openssl/crypto/ocsp/ocsp_err.c", "openssl/openssl/crypto/ocsp/ocsp_ext.c", "openssl/openssl/crypto/ocsp/ocsp_ht.c", "openssl/openssl/crypto/ocsp/ocsp_lib.c", "openssl/openssl/crypto/ocsp/ocsp_prn.c", "openssl/openssl/crypto/ocsp/ocsp_srv.c", "openssl/openssl/crypto/ocsp/ocsp_vfy.c", "openssl/openssl/crypto/pem/pem_all.c", "openssl/openssl/crypto/pem/pem_err.c", "openssl/openssl/crypto/pem/pem_info.c", "openssl/openssl/crypto/pem/pem_lib.c", "openssl/openssl/crypto/pem/pem_oth.c", "openssl/openssl/crypto/pem/pem_pk8.c", "openssl/openssl/crypto/pem/pem_pkey.c", "openssl/openssl/crypto/pem/pem_seal.c", "openssl/openssl/crypto/pem/pem_sign.c", "openssl/openssl/crypto/pem/pem_x509.c", "openssl/openssl/crypto/pem/pem_xaux.c", "openssl/openssl/crypto/pem/pvkfmt.c", "openssl/openssl/crypto/pkcs12/p12_add.c", "openssl/openssl/crypto/pkcs12/p12_asn.c", "openssl/openssl/crypto/pkcs12/p12_attr.c", "openssl/openssl/crypto/pkcs12/p12_crpt.c", "openssl/openssl/crypto/pkcs12/p12_crt.c", "openssl/openssl/crypto/pkcs12/p12_decr.c", "openssl/openssl/crypto/pkcs12/p12_init.c", "openssl/openssl/crypto/pkcs12/p12_key.c", "openssl/openssl/crypto/pkcs12/p12_kiss.c", "openssl/openssl/crypto/pkcs12/p12_mutl.c", "openssl/openssl/crypto/pkcs12/p12_npas.c", "openssl/openssl/crypto/pkcs12/p12_p8d.c", "openssl/openssl/crypto/pkcs12/p12_p8e.c", "openssl/openssl/crypto/pkcs12/p12_utl.c", "openssl/openssl/crypto/pkcs12/pk12err.c", "openssl/openssl/crypto/pkcs7/bio_pk7.c", "openssl/openssl/crypto/pkcs7/pk7_asn1.c", "openssl/openssl/crypto/pkcs7/pk7_attr.c", "openssl/openssl/crypto/pkcs7/pk7_doit.c", "openssl/openssl/crypto/pkcs7/pk7_lib.c", "openssl/openssl/crypto/pkcs7/pk7_mime.c", "openssl/openssl/crypto/pkcs7/pk7_smime.c", "openssl/openssl/crypto/pkcs7/pkcs7err.c", "openssl/openssl/crypto/pqueue/pqueue.c", "openssl/openssl/crypto/rand/md_rand.c", "openssl/openssl/crypto/rand/rand_egd.c", "openssl/openssl/crypto/rand/rand_err.c", "openssl/openssl/crypto/rand/rand_lib.c", "openssl/openssl/crypto/rand/rand_nw.c", "openssl/openssl/crypto/rand/rand_os2.c", "openssl/openssl/crypto/rand/rand_unix.c", "openssl/openssl/crypto/rand/rand_win.c", "openssl/openssl/crypto/rand/randfile.c", "openssl/openssl/crypto/rc2/rc2_cbc.c", "openssl/openssl/crypto/rc2/rc2_ecb.c", "openssl/openssl/crypto/rc2/rc2_skey.c", "openssl/openssl/crypto/rc2/rc2cfb64.c", "openssl/openssl/crypto/rc2/rc2ofb64.c", "openssl/openssl/crypto/rc4/rc4_utl.c", "openssl/openssl/crypto/ripemd/rmd_dgst.c", "openssl/openssl/crypto/ripemd/rmd_one.c", "openssl/openssl/crypto/rsa/rsa_ameth.c", "openssl/openssl/crypto/rsa/rsa_asn1.c", "openssl/openssl/crypto/rsa/rsa_chk.c", "openssl/openssl/crypto/rsa/rsa_crpt.c", "openssl/openssl/crypto/rsa/rsa_depr.c", "openssl/openssl/crypto/rsa/rsa_eay.c", "openssl/openssl/crypto/rsa/rsa_err.c", "openssl/openssl/crypto/rsa/rsa_gen.c", "openssl/openssl/crypto/rsa/rsa_lib.c", "openssl/openssl/crypto/rsa/rsa_none.c", "openssl/openssl/crypto/rsa/rsa_null.c", "openssl/openssl/crypto/rsa/rsa_oaep.c", "openssl/openssl/crypto/rsa/rsa_pk1.c", "openssl/openssl/crypto/rsa/rsa_pmeth.c", "openssl/openssl/crypto/rsa/rsa_prn.c", "openssl/openssl/crypto/rsa/rsa_pss.c", "openssl/openssl/crypto/rsa/rsa_saos.c", "openssl/openssl/crypto/rsa/rsa_sign.c", "openssl/openssl/crypto/rsa/rsa_ssl.c", "openssl/openssl/crypto/rsa/rsa_x931.c", "openssl/openssl/crypto/seed/seed.c", "openssl/openssl/crypto/seed/seed_cbc.c", "openssl/openssl/crypto/seed/seed_cfb.c", "openssl/openssl/crypto/seed/seed_ecb.c", "openssl/openssl/crypto/seed/seed_ofb.c", "openssl/openssl/crypto/sha/sha1_one.c", "openssl/openssl/crypto/sha/sha1dgst.c", "openssl/openssl/crypto/sha/sha256.c", "openssl/openssl/crypto/sha/sha512.c", "openssl/openssl/crypto/sha/sha_dgst.c", "openssl/openssl/crypto/sha/sha_one.c", "openssl/openssl/crypto/srp/srp_lib.c", "openssl/openssl/crypto/srp/srp_vfy.c", "openssl/openssl/crypto/stack/stack.c", "openssl/openssl/crypto/store/str_err.c", "openssl/openssl/crypto/store/str_lib.c", "openssl/openssl/crypto/store/str_mem.c", "openssl/openssl/crypto/store/str_meth.c", "openssl/openssl/crypto/ts/ts_asn1.c", "openssl/openssl/crypto/ts/ts_conf.c", "openssl/openssl/crypto/ts/ts_err.c", "openssl/openssl/crypto/ts/ts_lib.c", "openssl/openssl/crypto/ts/ts_req_print.c", "openssl/openssl/crypto/ts/ts_req_utils.c", "openssl/openssl/crypto/ts/ts_rsp_print.c", "openssl/openssl/crypto/ts/ts_rsp_sign.c", "openssl/openssl/crypto/ts/ts_rsp_utils.c", "openssl/openssl/crypto/ts/ts_rsp_verify.c", "openssl/openssl/crypto/ts/ts_verify_ctx.c", "openssl/openssl/crypto/txt_db/txt_db.c", "openssl/openssl/crypto/ui/ui_compat.c", "openssl/openssl/crypto/ui/ui_err.c", "openssl/openssl/crypto/ui/ui_lib.c", "openssl/openssl/crypto/ui/ui_openssl.c", "openssl/openssl/crypto/ui/ui_util.c", "openssl/openssl/crypto/uid.c", "openssl/openssl/crypto/whrlpool/wp_dgst.c", "openssl/openssl/crypto/x509/by_dir.c", "openssl/openssl/crypto/x509/by_file.c", "openssl/openssl/crypto/x509/x509_att.c", "openssl/openssl/crypto/x509/x509_cmp.c", "openssl/openssl/crypto/x509/x509_d2.c", "openssl/openssl/crypto/x509/x509_def.c", "openssl/openssl/crypto/x509/x509_err.c", "openssl/openssl/crypto/x509/x509_ext.c", "openssl/openssl/crypto/x509/x509_lu.c", "openssl/openssl/crypto/x509/x509_obj.c", "openssl/openssl/crypto/x509/x509_r2x.c", "openssl/openssl/crypto/x509/x509_req.c", "openssl/openssl/crypto/x509/x509_set.c", "openssl/openssl/crypto/x509/x509_trs.c", "openssl/openssl/crypto/x509/x509_txt.c", "openssl/openssl/crypto/x509/x509_v3.c", "openssl/openssl/crypto/x509/x509_vfy.c", "openssl/openssl/crypto/x509/x509_vpm.c", "openssl/openssl/crypto/x509/x509cset.c", "openssl/openssl/crypto/x509/x509name.c", "openssl/openssl/crypto/x509/x509rset.c", "openssl/openssl/crypto/x509/x509spki.c", "openssl/openssl/crypto/x509/x509type.c", "openssl/openssl/crypto/x509/x_all.c", "openssl/openssl/crypto/x509v3/pcy_cache.c", "openssl/openssl/crypto/x509v3/pcy_data.c", "openssl/openssl/crypto/x509v3/pcy_lib.c", "openssl/openssl/crypto/x509v3/pcy_map.c", "openssl/openssl/crypto/x509v3/pcy_node.c", "openssl/openssl/crypto/x509v3/pcy_tree.c", "openssl/openssl/crypto/x509v3/v3_addr.c", "openssl/openssl/crypto/x509v3/v3_akey.c", "openssl/openssl/crypto/x509v3/v3_akeya.c", "openssl/openssl/crypto/x509v3/v3_alt.c", "openssl/openssl/crypto/x509v3/v3_asid.c", "openssl/openssl/crypto/x509v3/v3_bcons.c", "openssl/openssl/crypto/x509v3/v3_bitst.c", "openssl/openssl/crypto/x509v3/v3_conf.c", "openssl/openssl/crypto/x509v3/v3_cpols.c", "openssl/openssl/crypto/x509v3/v3_crld.c", "openssl/openssl/crypto/x509v3/v3_enum.c", "openssl/openssl/crypto/x509v3/v3_extku.c", "openssl/openssl/crypto/x509v3/v3_genn.c", "openssl/openssl/crypto/x509v3/v3_ia5.c", "openssl/openssl/crypto/x509v3/v3_info.c", "openssl/openssl/crypto/x509v3/v3_int.c", "openssl/openssl/crypto/x509v3/v3_lib.c", "openssl/openssl/crypto/x509v3/v3_ncons.c", "openssl/openssl/crypto/x509v3/v3_ocsp.c", "openssl/openssl/crypto/x509v3/v3_pci.c", "openssl/openssl/crypto/x509v3/v3_pcia.c", "openssl/openssl/crypto/x509v3/v3_pcons.c", "openssl/openssl/crypto/x509v3/v3_pku.c", "openssl/openssl/crypto/x509v3/v3_pmaps.c", "openssl/openssl/crypto/x509v3/v3_prn.c", "openssl/openssl/crypto/x509v3/v3_purp.c", "openssl/openssl/crypto/x509v3/v3_skey.c", "openssl/openssl/crypto/x509v3/v3_sxnet.c", "openssl/openssl/crypto/x509v3/v3_utl.c", "openssl/openssl/crypto/x509v3/v3err.c", "openssl/openssl/engines/e_4758cca.c", "openssl/openssl/engines/e_aep.c", "openssl/openssl/engines/e_atalla.c", "openssl/openssl/engines/e_capi.c", "openssl/openssl/engines/e_chil.c", "openssl/openssl/engines/e_cswift.c", "openssl/openssl/engines/e_gmp.c", "openssl/openssl/engines/e_nuron.c", "openssl/openssl/engines/e_sureware.c", "openssl/openssl/engines/e_ubsec.c" ], "sources/": [ ["exclude", "md2/.*$"], ["exclude", "store/.*$"] ], "conditions": [ ["openssl_enable_asm!=1", { "defines": [ "OPENSSL_NO_ASM" ], "sources": [ "openssl/openssl/crypto/aes/aes_cbc.c", "openssl/openssl/crypto/aes/aes_core.c", "openssl/openssl/crypto/bf/bf_enc.c", "openssl/openssl/crypto/bn/bn_asm.c", "openssl/openssl/crypto/cast/c_enc.c", "openssl/openssl/crypto/camellia/camellia.c", "openssl/openssl/crypto/camellia/cmll_cbc.c", "openssl/openssl/crypto/camellia/cmll_misc.c", "openssl/openssl/crypto/des/des_enc.c", "openssl/openssl/crypto/des/fcrypt_b.c", "openssl/openssl/crypto/mem_clr.c", "openssl/openssl/crypto/rc4/rc4_enc.c", "openssl/openssl/crypto/rc4/rc4_skey.c", "openssl/openssl/crypto/whrlpool/wp_block.c" ] }, { "defines": [ "AES_ASM", "BF_ASM", "BNCO_ASM", "BN_ASM", "CPUID_ASM", "DES_ASM", "LIB_BN_ASM", "OPENSSL_BN_ASM", "OPENSSL_CPUID_OBJ", "RIP_ASM", "WHIRLPOOL_ASM", "WP_ASM" ], "conditions": [ ["OS!='win' and OS!='mac' and target_arch=='ia32'", { "sources": [ "asm/x86-elf-gas/aes/aes-586.s", "asm/x86-elf-gas/aes/aesni-x86.s", "asm/x86-elf-gas/bf/bf-686.s", "asm/x86-elf-gas/bn/x86-mont.s", "asm/x86-elf-gas/bn/x86.s", "asm/x86-elf-gas/camellia/cmll-x86.s", "asm/x86-elf-gas/cast/cast-586.s", "asm/x86-elf-gas/des/crypt586.s", "asm/x86-elf-gas/des/des-586.s", "asm/x86-elf-gas/md5/md5-586.s", "asm/x86-elf-gas/rc4/rc4-586.s", "asm/x86-elf-gas/rc5/rc5-586.s", "asm/x86-elf-gas/ripemd/rmd-586.s", "asm/x86-elf-gas/sha/sha1-586.s", "asm/x86-elf-gas/sha/sha256-586.s", "asm/x86-elf-gas/sha/sha512-586.s", "asm/x86-elf-gas/whrlpool/wp-mmx.s", "asm/x86-elf-gas/x86cpuid.s", "openssl/openssl/crypto/whrlpool/wp_block.c" ] }], ["OS!='win' and OS!='mac' and target_arch=='x64'", { "sources": [ "asm/x64-elf-gas/aes/aes-x86_64.s", "asm/x64-elf-gas/aes/aesni-x86_64.s", "asm/x64-elf-gas/aes/aesni-sha1-x86_64.s", "asm/x64-elf-gas/bn/modexp512-x86_64.s", "asm/x64-elf-gas/bn/x86_64-mont.s", "asm/x64-elf-gas/camellia/cmll-x86_64.s", "asm/x64-elf-gas/md5/md5-x86_64.s", "asm/x64-elf-gas/rc4/rc4-x86_64.s", "asm/x64-elf-gas/rc4/rc4-md5-x86_64.s", "asm/x64-elf-gas/sha/sha1-x86_64.s", "asm/x64-elf-gas/sha/sha512-x86_64.s", "asm/x64-elf-gas/whrlpool/wp-x86_64.s", "asm/x64-elf-gas/x86_64cpuid.s", #Non - generated asm "openssl/openssl/crypto/bn/asm/x86_64-gcc.c", #No asm available "openssl/openssl/crypto/bf/bf_enc.c", "openssl/openssl/crypto/cast/c_enc.c", "openssl/openssl/crypto/camellia/cmll_misc.c", "openssl/openssl/crypto/des/des_enc.c", "openssl/openssl/crypto/des/fcrypt_b.c" ] }], ["OS=='mac' and target_arch=='ia32'", { "sources": [ "asm/x86-macosx-gas/aes/aes-586.s", "asm/x86-macosx-gas/aes/aesni-x86.s", "asm/x86-macosx-gas/bf/bf-686.s", "asm/x86-macosx-gas/bn/x86-mont.s", "asm/x86-macosx-gas/bn/x86.s", "asm/x86-macosx-gas/camellia/cmll-x86.s", "asm/x86-macosx-gas/cast/cast-586.s", "asm/x86-macosx-gas/des/crypt586.s", "asm/x86-macosx-gas/des/des-586.s", "asm/x86-macosx-gas/md5/md5-586.s", "asm/x86-macosx-gas/rc4/rc4-586.s", "asm/x86-macosx-gas/rc5/rc5-586.s", "asm/x86-macosx-gas/ripemd/rmd-586.s", "asm/x86-macosx-gas/sha/sha1-586.s", "asm/x86-macosx-gas/sha/sha256-586.s", "asm/x86-macosx-gas/sha/sha512-586.s", "asm/x86-macosx-gas/whrlpool/wp-mmx.s", "asm/x86-macosx-gas/x86cpuid.s", "openssl/openssl/crypto/whrlpool/wp_block.c" ] }], ["OS=='mac' and target_arch=='x64'", { "sources": [ "asm/x64-macosx-gas/aes/aes-x86_64.s", "asm/x64-macosx-gas/aes/aesni-x86_64.s", "asm/x64-macosx-gas/aes/aesni-sha1-x86_64.s", "asm/x64-macosx-gas/bn/modexp512-x86_64.s", "asm/x64-macosx-gas/bn/x86_64-mont.s", "asm/x64-macosx-gas/camellia/cmll-x86_64.s", "asm/x64-macosx-gas/md5/md5-x86_64.s", "asm/x64-macosx-gas/rc4/rc4-x86_64.s", "asm/x64-macosx-gas/rc4/rc4-md5-x86_64.s", "asm/x64-macosx-gas/sha/sha1-x86_64.s", "asm/x64-macosx-gas/sha/sha512-x86_64.s", "asm/x64-macosx-gas/whrlpool/wp-x86_64.s", "asm/x64-macosx-gas/x86_64cpuid.s", #Non - generated asm "openssl/openssl/crypto/bn/asm/x86_64-gcc.c", #No asm available "openssl/openssl/crypto/bf/bf_enc.c", "openssl/openssl/crypto/cast/c_enc.c", "openssl/openssl/crypto/camellia/cmll_misc.c", "openssl/openssl/crypto/des/des_enc.c", "openssl/openssl/crypto/des/fcrypt_b.c" ] }], ["OS=='win' and target_arch=='ia32'", { "sources": [ "asm/x86-win32-masm/aes/aes-586.asm", "asm/x86-win32-masm/aes/aesni-x86.asm", "asm/x86-win32-masm/bf/bf-686.asm", "asm/x86-win32-masm/bn/x86-mont.asm", "asm/x86-win32-masm/bn/x86.asm", "asm/x86-win32-masm/camellia/cmll-x86.asm", "asm/x86-win32-masm/cast/cast-586.asm", "asm/x86-win32-masm/des/crypt586.asm", "asm/x86-win32-masm/des/des-586.asm", "asm/x86-win32-masm/md5/md5-586.asm", "asm/x86-win32-masm/rc4/rc4-586.asm", "asm/x86-win32-masm/rc5/rc5-586.asm", "asm/x86-win32-masm/ripemd/rmd-586.asm", "asm/x86-win32-masm/sha/sha1-586.asm", "asm/x86-win32-masm/sha/sha256-586.asm", "asm/x86-win32-masm/sha/sha512-586.asm", "asm/x86-win32-masm/whrlpool/wp-mmx.asm", "asm/x86-win32-masm/x86cpuid.asm", "openssl/openssl/crypto/whrlpool/wp_block.c" ], "rules": [ { "rule_name": "Assemble", "extension": "asm", "inputs": [], "outputs": [ "<(INTERMEDIATE_DIR)/<(RULE_INPUT_ROOT).obj", ], "action": [ "ml.exe", "/Zi", "/safeseh", "/Fo", "<(INTERMEDIATE_DIR)/<(RULE_INPUT_ROOT).obj", "/c", "<(RULE_INPUT_PATH)", ], "process_outputs_as_sources": 0, "message": "Assembling <(RULE_INPUT_PATH) to <(INTERMEDIATE_DIR)/<(RULE_INPUT_ROOT).obj.", } ] }], ["OS=='win' and target_arch=='x64'", { "sources": [ "asm/x64-win32-masm/aes/aes-x86_64.asm", "asm/x64-win32-masm/aes/aesni-x86_64.asm", "asm/x64-win32-masm/aes/aesni-sha1-x86_64.asm", "asm/x64-win32-masm/bn/modexp512-x86_64.asm", "asm/x64-win32-masm/bn/x86_64-mont.asm", "asm/x64-win32-masm/camellia/cmll-x86_64.asm", "asm/x64-win32-masm/md5/md5-x86_64.asm", "asm/x64-win32-masm/rc4/rc4-x86_64.asm", "asm/x64-win32-masm/rc4/rc4-md5-x86_64.asm", "asm/x64-win32-masm/sha/sha1-x86_64.asm", "asm/x64-win32-masm/sha/sha512-x86_64.asm", "asm/x64-win32-masm/whrlpool/wp-x86_64.asm", "asm/x64-win32-masm/x86_64cpuid.asm", #Non - generated asm "openssl/openssl/crypto/bn/asm/x86_64-win32-masm.asm", #No asm available "openssl/openssl/crypto/bf/bf_enc.c", "openssl/openssl/crypto/cast/c_enc.c", "openssl/openssl/crypto/camellia/cmll_misc.c", "openssl/openssl/crypto/des/des_enc.c", "openssl/openssl/crypto/des/fcrypt_b.c" ], "rules": [ { "rule_name": "Assemble", "extension": "asm", "inputs": [], "outputs": [ "<(INTERMEDIATE_DIR)/<(RULE_INPUT_ROOT).obj", ], "action": [ "ml64.exe", "/Zi", "/Fo", "<(INTERMEDIATE_DIR)/<(RULE_INPUT_ROOT).obj", "/c", "<(RULE_INPUT_PATH)", ], "process_outputs_as_sources": 0, "message": "Assembling <(RULE_INPUT_PATH) to <(INTERMEDIATE_DIR)/<(RULE_INPUT_ROOT).obj.", } ] }] ] }], ["OS=='win'", { "defines": [ "MK1MF_BUILD", "WIN32_LEAN_AND_MEAN" ], "link_settings": { "libraries": [ "-lgdi32.lib", "-luser32.lib", "-lwsock32.lib", ], "conditions": [ ["_type=='shared_library'", { "libraries": [ "-ladvapi32.lib" ] }] ] } }, { "defines": [ "TERMIOS", ], "cflags": [ "-Wno-missing-field-initializers" ], }], ["is_clang==1 or gcc_version>=43", { "cflags": [ "-Wno-old-style-declaration" ], }], ["OS=='solaris'", { "defines": [ "__EXTENSIONS__" ], }], ["target_arch=='arm'", { "sources": [ "openssl/openssl/crypto/armcap.c" ], }], ], }, ] }
40.753758
112
0.572216
{ "variables": { "target_arch%": "x86", "library%": "static_library", "openssl_enable_asm%": 0, "gcc_version%": 0, "is_clang%": 0, }, "targets": [ { "target_name": "libgit2", "type": "static_library", "defines": [ "GIT_THREADS", "GIT_SSH", # against compilation error. "SRC_UTIL_H_", ], "dependencies": [ "zlib", "<(module_root_dir)/vendor/http_parser/http_parser.gyp:http_parser", "libssh2", "openssl" ], "sources": [ "libgit2/src/array.h", "libgit2/src/attr.c", "libgit2/src/attr.h", "libgit2/src/attr_file.c", "libgit2/src/attr_file.h", "libgit2/src/attrcache.c", "libgit2/src/attrcache.h", "libgit2/src/bitvec.h", "libgit2/src/blame.c", "libgit2/src/blame.h", "libgit2/src/blame_git.c", "libgit2/src/blame_git.h", "libgit2/src/blob.c", "libgit2/src/blob.h", "libgit2/src/branch.c", "libgit2/src/branch.h", "libgit2/src/bswap.h", "libgit2/src/buf_text.c", "libgit2/src/buf_text.h", "libgit2/src/buffer.c", "libgit2/src/buffer.h", "libgit2/src/cache.c", "libgit2/src/cache.h", "libgit2/src/cc-compat.h", "libgit2/src/checkout.c", "libgit2/src/checkout.h", "libgit2/src/cherrypick.c", "libgit2/src/clone.c", "libgit2/src/clone.h", "libgit2/src/commit.c", "libgit2/src/commit.h", "libgit2/src/commit_list.c", "libgit2/src/commit_list.h", "libgit2/src/common.h", "libgit2/src/config.c", "libgit2/src/config.h", "libgit2/src/config_cache.c", "libgit2/src/config_file.c", "libgit2/src/config_file.h", "libgit2/src/crlf.c", "libgit2/src/date.c", "libgit2/src/delta-apply.c", "libgit2/src/delta-apply.h", "libgit2/src/delta.c", "libgit2/src/delta.h", "libgit2/src/diff.c", "libgit2/src/diff.h", "libgit2/src/diff_driver.c", "libgit2/src/diff_driver.h", "libgit2/src/diff_file.c", "libgit2/src/diff_file.h", "libgit2/src/diff_patch.c", "libgit2/src/diff_patch.h", "libgit2/src/diff_print.c", "libgit2/src/diff_stats.c", "libgit2/src/diff_tform.c", "libgit2/src/diff_xdiff.c", "libgit2/src/diff_xdiff.h", "libgit2/src/errors.c", "libgit2/src/fetch.c", "libgit2/src/fetch.h", "libgit2/src/fetchhead.c", "libgit2/src/fetchhead.h", "libgit2/src/filebuf.c", "libgit2/src/filebuf.h", "libgit2/src/fileops.c", "libgit2/src/fileops.h", "libgit2/src/filter.c", "libgit2/src/filter.h", "libgit2/src/fnmatch.c", "libgit2/src/fnmatch.h", "libgit2/src/global.c", "libgit2/src/global.h", "libgit2/src/graph.c", "libgit2/src/hash.c", "libgit2/src/hash.h", "libgit2/src/hashsig.c", "libgit2/src/hashsig.h", "libgit2/src/ident.c", "libgit2/src/ignore.c", "libgit2/src/ignore.h", "libgit2/src/index.c", "libgit2/src/index.h", "libgit2/src/indexer.c", "libgit2/src/iterator.c", "libgit2/src/iterator.h", "libgit2/src/khash.h", "libgit2/src/map.h", "libgit2/src/merge.c", "libgit2/src/merge.h", "libgit2/src/merge_file.c", "libgit2/src/merge_file.h", "libgit2/src/message.c", "libgit2/src/message.h", "libgit2/src/mwindow.c", "libgit2/src/mwindow.h", "libgit2/src/netops.c", "libgit2/src/netops.h", "libgit2/src/notes.c", "libgit2/src/notes.h", "libgit2/src/object.c", "libgit2/src/object.h", "libgit2/src/object_api.c", "libgit2/src/odb.c", "libgit2/src/odb.h", "libgit2/src/odb_loose.c", "libgit2/src/odb_mempack.c", "libgit2/src/odb_pack.c", "libgit2/src/offmap.h", "libgit2/src/oid.c", "libgit2/src/oid.h", "libgit2/src/oidmap.h", "libgit2/src/pack-objects.c", "libgit2/src/pack-objects.h", "libgit2/src/pack.c", "libgit2/src/pack.h", "libgit2/src/path.c", "libgit2/src/path.h", "libgit2/src/pathspec.c", "libgit2/src/pathspec.h", "libgit2/src/pool.c", "libgit2/src/pool.h", "libgit2/src/posix.c", "libgit2/src/posix.h", "libgit2/src/pqueue.c", "libgit2/src/pqueue.h", "libgit2/src/push.c", "libgit2/src/push.h", "libgit2/src/refdb.c", "libgit2/src/refdb.h", "libgit2/src/refdb_fs.c", "libgit2/src/refdb_fs.h", "libgit2/src/reflog.c", "libgit2/src/reflog.h", "libgit2/src/refs.c", "libgit2/src/refs.h", "libgit2/src/refspec.c", "libgit2/src/refspec.h", "libgit2/src/remote.c", "libgit2/src/remote.h", "libgit2/src/repo_template.h", "libgit2/src/repository.c", "libgit2/src/repository.h", "libgit2/src/reset.c", "libgit2/src/revert.c", "libgit2/src/revparse.c", "libgit2/src/revwalk.c", "libgit2/src/revwalk.h", "libgit2/src/settings.c", "libgit2/src/sha1_lookup.c", "libgit2/src/sha1_lookup.h", "libgit2/src/signature.c", "libgit2/src/signature.h", "libgit2/src/sortedcache.c", "libgit2/src/sortedcache.h", "libgit2/src/stash.c", "libgit2/src/status.c", "libgit2/src/status.h", "libgit2/src/strmap.c", "libgit2/src/strmap.h", "libgit2/src/strnlen.h", "libgit2/src/submodule.c", "libgit2/src/submodule.h", "libgit2/src/sysdir.c", "libgit2/src/sysdir.h", "libgit2/src/tag.c", "libgit2/src/tag.h", "libgit2/src/thread-utils.c", "libgit2/src/thread-utils.h", "libgit2/src/trace.c", "libgit2/src/trace.h", "libgit2/src/transport.c", "libgit2/src/tree-cache.c", "libgit2/src/tree-cache.h", "libgit2/src/tree.c", "libgit2/src/tree.h", "libgit2/src/tsort.c", "libgit2/src/userdiff.h", "libgit2/src/util.c", "libgit2/src/util.h", "libgit2/src/vector.c", "libgit2/src/vector.h", "libgit2/src/zstream.c", "libgit2/src/zstream.h", "libgit2/src/hash/hash_generic.c", "libgit2/src/hash/hash_generic.h", "libgit2/src/hash/hash_openssl.h", "libgit2/src/transports/cred.c", "libgit2/src/transports/cred_helpers.c", "libgit2/src/transports/git.c", "libgit2/src/transports/http.c", "libgit2/src/transports/local.c", "libgit2/src/transports/smart.c", "libgit2/src/transports/smart.h", "libgit2/src/transports/smart_pkt.c", "libgit2/src/transports/smart_protocol.c", "libgit2/src/transports/ssh.c", "libgit2/src/xdiff/xdiff.h", "libgit2/src/xdiff/xdiffi.c", "libgit2/src/xdiff/xdiffi.h", "libgit2/src/xdiff/xemit.c", "libgit2/src/xdiff/xemit.h", "libgit2/src/xdiff/xhistogram.c", "libgit2/src/xdiff/xinclude.h", "libgit2/src/xdiff/xmacros.h", "libgit2/src/xdiff/xmerge.c", "libgit2/src/xdiff/xpatience.c", "libgit2/src/xdiff/xprepare.c", "libgit2/src/xdiff/xprepare.h", "libgit2/src/xdiff/xtypes.h", "libgit2/src/xdiff/xutils.c", "libgit2/src/xdiff/xutils.h", ], "conditions": [ ["OS!='win'", { "defines": [ "GIT_SSL" ], }], ["OS=='win'", {}, { "sources": [ "libgit2/src/unix/map.c", "libgit2/src/unix/posix.h", "libgit2/src/unix/realpath.c", ] }], ["OS=='linux'", { "cflags": [ "-DGIT_SSH", "-DGIT_SSL", "-w", ], }], ["OS=='win'", { "defines": [ "GIT_WINHTTP", ], "msvs_settings": { "VCLinkerTool": { "AdditionalDependencies": [ "ws2_32.lib", ], }, # Workaround of a strange bug: # TargetMachine + static_library + x64 = nothing. "conditions": [ ["target_arch=='x64'", { "VCLibrarianTool": { "AdditionalOptions": [ "/MACHINE:X64", ], }, }, { "VCLibrarianTool": { "AdditionalOptions": [ "/MACHINE:x86", ], }, }], ], }, "msvs_disabled_warnings": [ # Conversion from 'ssize_t' to 'int32_t', possible loss of data. 4244, # Conversion from 'size_t' to 'int', possible loss of data. 4267, # Different 'volatile' qualifiers. 4090, # 'volatile void *' differs in levels of indirection from 'int'. 4047, # 'InterlockedDecrement' undefined; assuming extern returning int. 4013, ], "sources": [ "libgit2/src/win32/dir.c", "libgit2/src/win32/dir.h", "libgit2/src/win32/error.c", "libgit2/src/win32/error.h", "libgit2/src/win32/findfile.c", "libgit2/src/win32/findfile.h", "libgit2/src/win32/git2.rc", "libgit2/src/win32/map.c", "libgit2/src/win32/mingw-compat.h", "libgit2/src/win32/msvc-compat.h", "libgit2/src/win32/posix.h", "libgit2/src/win32/posix_w32.c", "libgit2/src/win32/precompiled.c", "libgit2/src/win32/precompiled.h", "libgit2/src/win32/pthread.c", "libgit2/src/win32/pthread.h", "libgit2/src/win32/reparse.h", "libgit2/src/win32/utf-conv.c", "libgit2/src/win32/utf-conv.h", "libgit2/src/win32/version.h", "libgit2/src/win32/w32_util.c", "libgit2/src/win32/w32_util.h", "libgit2/src/win32/path_w32.c", "libgit2/src/win32/path_w32.h", "libgit2/src/transports/winhttp.c", "libgit2/deps/regex/regex.c", ], }, { "libraries": [ "-lpthread", ], "sources": [ "libgit2/src/unix/map.c", "libgit2/src/unix/posix.h", "libgit2/src/unix/realpath.c", ], "cflags": [ "-Wno-missing-field-initializers", "-Wno-unused-variable", "-Wno-deprecated-declarations", ], "xcode_settings": { "WARNING_CFLAGS": [ "-Wno-missing-field-initializers", "-Wno-unused-variable", "-Wno-deprecated-declarations", "-Wno-uninitialized", ], }, }, ] ], "include_dirs": [ "libgit2/include", "libgit2/src", "libgit2/deps/regex" ], "direct_dependent_settings": { "include_dirs": [ "libgit2/include", ], }, }, { "target_name": "zlib", "type": "static_library", "sources": [ "libgit2/deps/zlib/adler32.c", "libgit2/deps/zlib/crc32.c", "libgit2/deps/zlib/crc32.h", "libgit2/deps/zlib/deflate.c", "libgit2/deps/zlib/deflate.h", "libgit2/deps/zlib/inffast.c", "libgit2/deps/zlib/inffast.h", "libgit2/deps/zlib/inffixed.h", "libgit2/deps/zlib/inflate.c", "libgit2/deps/zlib/inflate.h", "libgit2/deps/zlib/inftrees.c", "libgit2/deps/zlib/inftrees.h", "libgit2/deps/zlib/trees.c", "libgit2/deps/zlib/trees.h", "libgit2/deps/zlib/zconf.h", "libgit2/deps/zlib/zlib.h", "libgit2/deps/zlib/zutil.c", "libgit2/deps/zlib/zutil.h", ], "defines": [ "NO_VIZ", "STDC", "NO_GZIP", ], "include_dirs": [ "libgit2/include", "libgit2/deps/regex", ], "direct_dependent_settings": { "include_dirs": [ "libgit2/deps/zlib", ], }, }, { "target_name": "libssh2", "type": "static_library", "defines": [ "NETSNMP_ENABLE_IPV6" ], "sources": [ "libssh2/src/agent.c", "libssh2/src/crypt.c", "libssh2/src/keepalive.c", "libssh2/src/libgcrypt.c", "libssh2/src/openssl.c", "libssh2/src/publickey.c", "libssh2/src/sftp.c", "libssh2/src/version.c", "libssh2/src/channel.c", "libssh2/src/global.c", "libssh2/src/kex.c", "libssh2/src/mac.c", "libssh2/src/packet.c", "libssh2/src/scp.c", "libssh2/src/transport.c", "libssh2/src/comp.c", "libssh2/src/hostkey.c", "libssh2/src/knownhost.c", "libssh2/src/misc.c", "libssh2/src/pem.c", "libssh2/src/session.c", "libssh2/src/userauth.c", ], "include_dirs": [ ".", "libssh2/include", ], "dependencies": [ "openssl" ], "direct_dependent_settings": { "include_dirs": [ "libssh2/include" ] }, "conditions": [ ["OS=='win'", { "include_dirs": [ "libssh2/src", "libssh2/win32", "libssh2/include" ], "direct_dependent_settings": { "include_dirs": [ "libssh2/src", "libssh2/win32", "libssh2/include" ] } }], ] }, { "target_name": "openssl", "type": "static_library", "defines": [ #No clue what these are for. "L_ENDIAN", "PURIFY", "_REENTRANT", "NO_WINDOWS_BRAINDEATH", ], "include_dirs": [ ".", "openssl/openssl", "openssl/openssl/crypto", "openssl/openssl/crypto/asn1", "openssl/openssl/crypto/evp", "openssl/openssl/crypto/md2", "openssl/openssl/crypto/modes", "openssl/openssl/crypto/store", "openssl/openssl/include", ], "direct_dependent_settings": { "include_dirs": [ "openssl/openssl/include", "openssl/openssl/include/openssl", ] }, "sources": [ "openssl/openssl/ssl/bio_ssl.c", "openssl/openssl/ssl/d1_both.c", "openssl/openssl/ssl/d1_clnt.c", "openssl/openssl/ssl/d1_enc.c", "openssl/openssl/ssl/d1_lib.c", "openssl/openssl/ssl/d1_meth.c", "openssl/openssl/ssl/d1_pkt.c", "openssl/openssl/ssl/d1_srtp.c", "openssl/openssl/ssl/d1_srvr.c", "openssl/openssl/ssl/kssl.c", "openssl/openssl/ssl/s23_clnt.c", "openssl/openssl/ssl/s23_lib.c", "openssl/openssl/ssl/s23_meth.c", "openssl/openssl/ssl/s23_pkt.c", "openssl/openssl/ssl/s23_srvr.c", "openssl/openssl/ssl/s2_clnt.c", "openssl/openssl/ssl/s2_enc.c", "openssl/openssl/ssl/s2_lib.c", "openssl/openssl/ssl/s2_meth.c", "openssl/openssl/ssl/s2_pkt.c", "openssl/openssl/ssl/s2_srvr.c", "openssl/openssl/ssl/s3_both.c", "openssl/openssl/ssl/s3_clnt.c", "openssl/openssl/ssl/s3_enc.c", "openssl/openssl/ssl/s3_lib.c", "openssl/openssl/ssl/s3_meth.c", "openssl/openssl/ssl/s3_pkt.c", "openssl/openssl/ssl/s3_srvr.c", "openssl/openssl/ssl/s3_cbc.c", "openssl/openssl/ssl/ssl_algs.c", "openssl/openssl/ssl/ssl_asn1.c", "openssl/openssl/ssl/ssl_cert.c", "openssl/openssl/ssl/ssl_ciph.c", "openssl/openssl/ssl/ssl_err.c", "openssl/openssl/ssl/ssl_err2.c", "openssl/openssl/ssl/ssl_lib.c", "openssl/openssl/ssl/ssl_rsa.c", "openssl/openssl/ssl/ssl_sess.c", "openssl/openssl/ssl/ssl_stat.c", "openssl/openssl/ssl/ssl_txt.c", "openssl/openssl/ssl/t1_clnt.c", "openssl/openssl/ssl/t1_enc.c", "openssl/openssl/ssl/t1_lib.c", "openssl/openssl/ssl/t1_meth.c", "openssl/openssl/ssl/t1_reneg.c", "openssl/openssl/ssl/t1_srvr.c", "openssl/openssl/ssl/tls_srp.c", "openssl/openssl/crypto/aes/aes_cfb.c", "openssl/openssl/crypto/aes/aes_ctr.c", "openssl/openssl/crypto/aes/aes_ecb.c", "openssl/openssl/crypto/aes/aes_ige.c", "openssl/openssl/crypto/aes/aes_misc.c", "openssl/openssl/crypto/aes/aes_ofb.c", "openssl/openssl/crypto/aes/aes_wrap.c", "openssl/openssl/crypto/asn1/a_bitstr.c", "openssl/openssl/crypto/asn1/a_bool.c", "openssl/openssl/crypto/asn1/a_bytes.c", "openssl/openssl/crypto/asn1/a_d2i_fp.c", "openssl/openssl/crypto/asn1/a_digest.c", "openssl/openssl/crypto/asn1/a_dup.c", "openssl/openssl/crypto/asn1/a_enum.c", "openssl/openssl/crypto/asn1/a_gentm.c", "openssl/openssl/crypto/asn1/a_i2d_fp.c", "openssl/openssl/crypto/asn1/a_int.c", "openssl/openssl/crypto/asn1/a_mbstr.c", "openssl/openssl/crypto/asn1/a_object.c", "openssl/openssl/crypto/asn1/a_octet.c", "openssl/openssl/crypto/asn1/a_print.c", "openssl/openssl/crypto/asn1/a_set.c", "openssl/openssl/crypto/asn1/a_sign.c", "openssl/openssl/crypto/asn1/a_strex.c", "openssl/openssl/crypto/asn1/a_strnid.c", "openssl/openssl/crypto/asn1/a_time.c", "openssl/openssl/crypto/asn1/a_type.c", "openssl/openssl/crypto/asn1/a_utctm.c", "openssl/openssl/crypto/asn1/a_utf8.c", "openssl/openssl/crypto/asn1/a_verify.c", "openssl/openssl/crypto/asn1/ameth_lib.c", "openssl/openssl/crypto/asn1/asn1_err.c", "openssl/openssl/crypto/asn1/asn1_gen.c", "openssl/openssl/crypto/asn1/asn1_lib.c", "openssl/openssl/crypto/asn1/asn1_par.c", "openssl/openssl/crypto/asn1/asn_mime.c", "openssl/openssl/crypto/asn1/asn_moid.c", "openssl/openssl/crypto/asn1/asn_pack.c", "openssl/openssl/crypto/asn1/bio_asn1.c", "openssl/openssl/crypto/asn1/bio_ndef.c", "openssl/openssl/crypto/asn1/d2i_pr.c", "openssl/openssl/crypto/asn1/d2i_pu.c", "openssl/openssl/crypto/asn1/evp_asn1.c", "openssl/openssl/crypto/asn1/f_enum.c", "openssl/openssl/crypto/asn1/f_int.c", "openssl/openssl/crypto/asn1/f_string.c", "openssl/openssl/crypto/asn1/i2d_pr.c", "openssl/openssl/crypto/asn1/i2d_pu.c", "openssl/openssl/crypto/asn1/n_pkey.c", "openssl/openssl/crypto/asn1/nsseq.c", "openssl/openssl/crypto/asn1/p5_pbe.c", "openssl/openssl/crypto/asn1/p5_pbev2.c", "openssl/openssl/crypto/asn1/p8_pkey.c", "openssl/openssl/crypto/asn1/t_bitst.c", "openssl/openssl/crypto/asn1/t_crl.c", "openssl/openssl/crypto/asn1/t_pkey.c", "openssl/openssl/crypto/asn1/t_req.c", "openssl/openssl/crypto/asn1/t_spki.c", "openssl/openssl/crypto/asn1/t_x509.c", "openssl/openssl/crypto/asn1/t_x509a.c", "openssl/openssl/crypto/asn1/tasn_dec.c", "openssl/openssl/crypto/asn1/tasn_enc.c", "openssl/openssl/crypto/asn1/tasn_fre.c", "openssl/openssl/crypto/asn1/tasn_new.c", "openssl/openssl/crypto/asn1/tasn_prn.c", "openssl/openssl/crypto/asn1/tasn_typ.c", "openssl/openssl/crypto/asn1/tasn_utl.c", "openssl/openssl/crypto/asn1/x_algor.c", "openssl/openssl/crypto/asn1/x_attrib.c", "openssl/openssl/crypto/asn1/x_bignum.c", "openssl/openssl/crypto/asn1/x_crl.c", "openssl/openssl/crypto/asn1/x_exten.c", "openssl/openssl/crypto/asn1/x_info.c", "openssl/openssl/crypto/asn1/x_long.c", "openssl/openssl/crypto/asn1/x_name.c", "openssl/openssl/crypto/asn1/x_nx509.c", "openssl/openssl/crypto/asn1/x_pkey.c", "openssl/openssl/crypto/asn1/x_pubkey.c", "openssl/openssl/crypto/asn1/x_req.c", "openssl/openssl/crypto/asn1/x_sig.c", "openssl/openssl/crypto/asn1/x_spki.c", "openssl/openssl/crypto/asn1/x_val.c", "openssl/openssl/crypto/asn1/x_x509.c", "openssl/openssl/crypto/asn1/x_x509a.c", "openssl/openssl/crypto/bf/bf_cfb64.c", "openssl/openssl/crypto/bf/bf_ecb.c", "openssl/openssl/crypto/bf/bf_ofb64.c", "openssl/openssl/crypto/bf/bf_skey.c", "openssl/openssl/crypto/bio/b_dump.c", "openssl/openssl/crypto/bio/b_print.c", "openssl/openssl/crypto/bio/b_sock.c", "openssl/openssl/crypto/bio/bf_buff.c", "openssl/openssl/crypto/bio/bf_nbio.c", "openssl/openssl/crypto/bio/bf_null.c", "openssl/openssl/crypto/bio/bio_cb.c", "openssl/openssl/crypto/bio/bio_err.c", "openssl/openssl/crypto/bio/bio_lib.c", "openssl/openssl/crypto/bio/bss_acpt.c", "openssl/openssl/crypto/bio/bss_bio.c", "openssl/openssl/crypto/bio/bss_conn.c", "openssl/openssl/crypto/bio/bss_dgram.c", "openssl/openssl/crypto/bio/bss_fd.c", "openssl/openssl/crypto/bio/bss_file.c", "openssl/openssl/crypto/bio/bss_log.c", "openssl/openssl/crypto/bio/bss_mem.c", "openssl/openssl/crypto/bio/bss_null.c", "openssl/openssl/crypto/bio/bss_sock.c", "openssl/openssl/crypto/bn/bn_add.c", "openssl/openssl/crypto/bn/bn_blind.c", "openssl/openssl/crypto/bn/bn_const.c", "openssl/openssl/crypto/bn/bn_ctx.c", "openssl/openssl/crypto/bn/bn_depr.c", "openssl/openssl/crypto/bn/bn_div.c", "openssl/openssl/crypto/bn/bn_err.c", "openssl/openssl/crypto/bn/bn_exp.c", "openssl/openssl/crypto/bn/bn_exp2.c", "openssl/openssl/crypto/bn/bn_gcd.c", "openssl/openssl/crypto/bn/bn_gf2m.c", "openssl/openssl/crypto/bn/bn_kron.c", "openssl/openssl/crypto/bn/bn_lib.c", "openssl/openssl/crypto/bn/bn_mod.c", "openssl/openssl/crypto/bn/bn_mont.c", "openssl/openssl/crypto/bn/bn_mpi.c", "openssl/openssl/crypto/bn/bn_mul.c", "openssl/openssl/crypto/bn/bn_nist.c", "openssl/openssl/crypto/bn/bn_prime.c", "openssl/openssl/crypto/bn/bn_print.c", "openssl/openssl/crypto/bn/bn_rand.c", "openssl/openssl/crypto/bn/bn_recp.c", "openssl/openssl/crypto/bn/bn_shift.c", "openssl/openssl/crypto/bn/bn_sqr.c", "openssl/openssl/crypto/bn/bn_sqrt.c", "openssl/openssl/crypto/bn/bn_word.c", "openssl/openssl/crypto/bn/bn_x931p.c", "openssl/openssl/crypto/buffer/buf_err.c", "openssl/openssl/crypto/buffer/buf_str.c", "openssl/openssl/crypto/buffer/buffer.c", "openssl/openssl/crypto/camellia/cmll_cfb.c", "openssl/openssl/crypto/camellia/cmll_ctr.c", "openssl/openssl/crypto/camellia/cmll_ecb.c", "openssl/openssl/crypto/camellia/cmll_ofb.c", "openssl/openssl/crypto/camellia/cmll_utl.c", "openssl/openssl/crypto/cast/c_cfb64.c", "openssl/openssl/crypto/cast/c_ecb.c", "openssl/openssl/crypto/cast/c_ofb64.c", "openssl/openssl/crypto/cast/c_skey.c", "openssl/openssl/crypto/cmac/cm_ameth.c", "openssl/openssl/crypto/cmac/cm_pmeth.c", "openssl/openssl/crypto/cmac/cmac.c", "openssl/openssl/crypto/cms/cms_asn1.c", "openssl/openssl/crypto/cms/cms_att.c", "openssl/openssl/crypto/cms/cms_cd.c", "openssl/openssl/crypto/cms/cms_dd.c", "openssl/openssl/crypto/cms/cms_enc.c", "openssl/openssl/crypto/cms/cms_env.c", "openssl/openssl/crypto/cms/cms_err.c", "openssl/openssl/crypto/cms/cms_ess.c", "openssl/openssl/crypto/cms/cms_io.c", "openssl/openssl/crypto/cms/cms_lib.c", "openssl/openssl/crypto/cms/cms_pwri.c", "openssl/openssl/crypto/cms/cms_sd.c", "openssl/openssl/crypto/cms/cms_smime.c", "openssl/openssl/crypto/comp/c_rle.c", "openssl/openssl/crypto/comp/c_zlib.c", "openssl/openssl/crypto/comp/comp_err.c", "openssl/openssl/crypto/comp/comp_lib.c", "openssl/openssl/crypto/conf/conf_api.c", "openssl/openssl/crypto/conf/conf_def.c", "openssl/openssl/crypto/conf/conf_err.c", "openssl/openssl/crypto/conf/conf_lib.c", "openssl/openssl/crypto/conf/conf_mall.c", "openssl/openssl/crypto/conf/conf_mod.c", "openssl/openssl/crypto/conf/conf_sap.c", "openssl/openssl/crypto/cpt_err.c", "openssl/openssl/crypto/cryptlib.c", "openssl/openssl/crypto/cversion.c", "openssl/openssl/crypto/des/cbc_cksm.c", "openssl/openssl/crypto/des/cbc_enc.c", "openssl/openssl/crypto/des/cfb64ede.c", "openssl/openssl/crypto/des/cfb64enc.c", "openssl/openssl/crypto/des/cfb_enc.c", "openssl/openssl/crypto/des/des_old.c", "openssl/openssl/crypto/des/des_old2.c", "openssl/openssl/crypto/des/ecb3_enc.c", "openssl/openssl/crypto/des/ecb_enc.c", "openssl/openssl/crypto/des/ede_cbcm_enc.c", "openssl/openssl/crypto/des/enc_read.c", "openssl/openssl/crypto/des/enc_writ.c", "openssl/openssl/crypto/des/fcrypt.c", "openssl/openssl/crypto/des/ofb64ede.c", "openssl/openssl/crypto/des/ofb64enc.c", "openssl/openssl/crypto/des/ofb_enc.c", "openssl/openssl/crypto/des/pcbc_enc.c", "openssl/openssl/crypto/des/qud_cksm.c", "openssl/openssl/crypto/des/rand_key.c", "openssl/openssl/crypto/des/read2pwd.c", "openssl/openssl/crypto/des/rpc_enc.c", "openssl/openssl/crypto/des/set_key.c", "openssl/openssl/crypto/des/str2key.c", "openssl/openssl/crypto/des/xcbc_enc.c", "openssl/openssl/crypto/dh/dh_ameth.c", "openssl/openssl/crypto/dh/dh_asn1.c", "openssl/openssl/crypto/dh/dh_check.c", "openssl/openssl/crypto/dh/dh_depr.c", "openssl/openssl/crypto/dh/dh_err.c", "openssl/openssl/crypto/dh/dh_gen.c", "openssl/openssl/crypto/dh/dh_key.c", "openssl/openssl/crypto/dh/dh_lib.c", "openssl/openssl/crypto/dh/dh_pmeth.c", "openssl/openssl/crypto/dh/dh_prn.c", "openssl/openssl/crypto/dsa/dsa_ameth.c", "openssl/openssl/crypto/dsa/dsa_asn1.c", "openssl/openssl/crypto/dsa/dsa_depr.c", "openssl/openssl/crypto/dsa/dsa_err.c", "openssl/openssl/crypto/dsa/dsa_gen.c", "openssl/openssl/crypto/dsa/dsa_key.c", "openssl/openssl/crypto/dsa/dsa_lib.c", "openssl/openssl/crypto/dsa/dsa_ossl.c", "openssl/openssl/crypto/dsa/dsa_pmeth.c", "openssl/openssl/crypto/dsa/dsa_prn.c", "openssl/openssl/crypto/dsa/dsa_sign.c", "openssl/openssl/crypto/dsa/dsa_vrf.c", "openssl/openssl/crypto/dso/dso_beos.c", "openssl/openssl/crypto/dso/dso_dl.c", "openssl/openssl/crypto/dso/dso_dlfcn.c", "openssl/openssl/crypto/dso/dso_err.c", "openssl/openssl/crypto/dso/dso_lib.c", "openssl/openssl/crypto/dso/dso_null.c", "openssl/openssl/crypto/dso/dso_openssl.c", "openssl/openssl/crypto/dso/dso_vms.c", "openssl/openssl/crypto/dso/dso_win32.c", "openssl/openssl/crypto/ebcdic.c", "openssl/openssl/crypto/ec/ec2_mult.c", "openssl/openssl/crypto/ec/ec2_oct.c", "openssl/openssl/crypto/ec/ec2_smpl.c", "openssl/openssl/crypto/ec/ec_ameth.c", "openssl/openssl/crypto/ec/ec_asn1.c", "openssl/openssl/crypto/ec/ec_check.c", "openssl/openssl/crypto/ec/ec_curve.c", "openssl/openssl/crypto/ec/ec_cvt.c", "openssl/openssl/crypto/ec/ec_err.c", "openssl/openssl/crypto/ec/ec_key.c", "openssl/openssl/crypto/ec/ec_lib.c", "openssl/openssl/crypto/ec/ec_mult.c", "openssl/openssl/crypto/ec/ec_oct.c", "openssl/openssl/crypto/ec/ec_pmeth.c", "openssl/openssl/crypto/ec/ec_print.c", "openssl/openssl/crypto/ec/eck_prn.c", "openssl/openssl/crypto/ec/ecp_mont.c", "openssl/openssl/crypto/ec/ecp_nist.c", "openssl/openssl/crypto/ec/ecp_nistp224.c", "openssl/openssl/crypto/ec/ecp_nistp256.c", "openssl/openssl/crypto/ec/ecp_nistp521.c", "openssl/openssl/crypto/ec/ecp_nistputil.c", "openssl/openssl/crypto/ec/ecp_oct.c", "openssl/openssl/crypto/ec/ecp_smpl.c", "openssl/openssl/crypto/ecdh/ech_err.c", "openssl/openssl/crypto/ecdh/ech_key.c", "openssl/openssl/crypto/ecdh/ech_lib.c", "openssl/openssl/crypto/ecdh/ech_ossl.c", "openssl/openssl/crypto/ecdsa/ecs_asn1.c", "openssl/openssl/crypto/ecdsa/ecs_err.c", "openssl/openssl/crypto/ecdsa/ecs_lib.c", "openssl/openssl/crypto/ecdsa/ecs_ossl.c", "openssl/openssl/crypto/ecdsa/ecs_sign.c", "openssl/openssl/crypto/ecdsa/ecs_vrf.c", "openssl/openssl/crypto/engine/eng_all.c", "openssl/openssl/crypto/engine/eng_cnf.c", "openssl/openssl/crypto/engine/eng_cryptodev.c", "openssl/openssl/crypto/engine/eng_ctrl.c", "openssl/openssl/crypto/engine/eng_dyn.c", "openssl/openssl/crypto/engine/eng_err.c", "openssl/openssl/crypto/engine/eng_fat.c", "openssl/openssl/crypto/engine/eng_init.c", "openssl/openssl/crypto/engine/eng_lib.c", "openssl/openssl/crypto/engine/eng_list.c", "openssl/openssl/crypto/engine/eng_openssl.c", "openssl/openssl/crypto/engine/eng_pkey.c", "openssl/openssl/crypto/engine/eng_rdrand.c", "openssl/openssl/crypto/engine/eng_rsax.c", "openssl/openssl/crypto/engine/eng_table.c", "openssl/openssl/crypto/engine/tb_asnmth.c", "openssl/openssl/crypto/engine/tb_cipher.c", "openssl/openssl/crypto/engine/tb_dh.c", "openssl/openssl/crypto/engine/tb_digest.c", "openssl/openssl/crypto/engine/tb_dsa.c", "openssl/openssl/crypto/engine/tb_ecdh.c", "openssl/openssl/crypto/engine/tb_ecdsa.c", "openssl/openssl/crypto/engine/tb_pkmeth.c", "openssl/openssl/crypto/engine/tb_rand.c", "openssl/openssl/crypto/engine/tb_rsa.c", "openssl/openssl/crypto/engine/tb_store.c", "openssl/openssl/crypto/err/err.c", "openssl/openssl/crypto/err/err_all.c", "openssl/openssl/crypto/err/err_prn.c", "openssl/openssl/crypto/evp/bio_b64.c", "openssl/openssl/crypto/evp/bio_enc.c", "openssl/openssl/crypto/evp/bio_md.c", "openssl/openssl/crypto/evp/bio_ok.c", "openssl/openssl/crypto/evp/c_all.c", "openssl/openssl/crypto/evp/c_allc.c", "openssl/openssl/crypto/evp/c_alld.c", "openssl/openssl/crypto/evp/digest.c", "openssl/openssl/crypto/evp/e_aes.c", "openssl/openssl/crypto/evp/e_aes_cbc_hmac_sha1.c", "openssl/openssl/crypto/evp/e_bf.c", "openssl/openssl/crypto/evp/e_camellia.c", "openssl/openssl/crypto/evp/e_cast.c", "openssl/openssl/crypto/evp/e_des.c", "openssl/openssl/crypto/evp/e_des3.c", "openssl/openssl/crypto/evp/e_idea.c", "openssl/openssl/crypto/evp/e_null.c", "openssl/openssl/crypto/evp/e_old.c", "openssl/openssl/crypto/evp/e_rc2.c", "openssl/openssl/crypto/evp/e_rc4.c", "openssl/openssl/crypto/evp/e_rc4_hmac_md5.c", "openssl/openssl/crypto/evp/e_rc5.c", "openssl/openssl/crypto/evp/e_seed.c", "openssl/openssl/crypto/evp/e_xcbc_d.c", "openssl/openssl/crypto/evp/encode.c", "openssl/openssl/crypto/evp/evp_acnf.c", "openssl/openssl/crypto/evp/evp_cnf.c", "openssl/openssl/crypto/evp/evp_enc.c", "openssl/openssl/crypto/evp/evp_err.c", "openssl/openssl/crypto/evp/evp_fips.c", "openssl/openssl/crypto/evp/evp_key.c", "openssl/openssl/crypto/evp/evp_lib.c", "openssl/openssl/crypto/evp/evp_pbe.c", "openssl/openssl/crypto/evp/evp_pkey.c", "openssl/openssl/crypto/evp/m_dss.c", "openssl/openssl/crypto/evp/m_dss1.c", "openssl/openssl/crypto/evp/m_ecdsa.c", "openssl/openssl/crypto/evp/m_md2.c", "openssl/openssl/crypto/evp/m_md4.c", "openssl/openssl/crypto/evp/m_md5.c", "openssl/openssl/crypto/evp/m_mdc2.c", "openssl/openssl/crypto/evp/m_null.c", "openssl/openssl/crypto/evp/m_ripemd.c", "openssl/openssl/crypto/evp/m_sha.c", "openssl/openssl/crypto/evp/m_sha1.c", "openssl/openssl/crypto/evp/m_sigver.c", "openssl/openssl/crypto/evp/m_wp.c", "openssl/openssl/crypto/evp/names.c", "openssl/openssl/crypto/evp/p5_crpt.c", "openssl/openssl/crypto/evp/p5_crpt2.c", "openssl/openssl/crypto/evp/p_dec.c", "openssl/openssl/crypto/evp/p_enc.c", "openssl/openssl/crypto/evp/p_lib.c", "openssl/openssl/crypto/evp/p_open.c", "openssl/openssl/crypto/evp/p_seal.c", "openssl/openssl/crypto/evp/p_sign.c", "openssl/openssl/crypto/evp/p_verify.c", "openssl/openssl/crypto/evp/pmeth_fn.c", "openssl/openssl/crypto/evp/pmeth_gn.c", "openssl/openssl/crypto/evp/pmeth_lib.c", "openssl/openssl/crypto/ex_data.c", "openssl/openssl/crypto/fips_ers.c", "openssl/openssl/crypto/hmac/hm_ameth.c", "openssl/openssl/crypto/hmac/hm_pmeth.c", "openssl/openssl/crypto/hmac/hmac.c", "openssl/openssl/crypto/idea/i_cbc.c", "openssl/openssl/crypto/idea/i_cfb64.c", "openssl/openssl/crypto/idea/i_ecb.c", "openssl/openssl/crypto/idea/i_ofb64.c", "openssl/openssl/crypto/idea/i_skey.c", "openssl/openssl/crypto/krb5/krb5_asn.c", "openssl/openssl/crypto/lhash/lh_stats.c", "openssl/openssl/crypto/lhash/lhash.c", "openssl/openssl/crypto/md2/md2_dgst.c", "openssl/openssl/crypto/md2/md2_one.c", "openssl/openssl/crypto/md4/md4_dgst.c", "openssl/openssl/crypto/md4/md4_one.c", "openssl/openssl/crypto/md5/md5_dgst.c", "openssl/openssl/crypto/md5/md5_one.c", "openssl/openssl/crypto/mdc2/mdc2_one.c", "openssl/openssl/crypto/mdc2/mdc2dgst.c", "openssl/openssl/crypto/mem.c", "openssl/openssl/crypto/mem_dbg.c", "openssl/openssl/crypto/modes/cbc128.c", "openssl/openssl/crypto/modes/ccm128.c", "openssl/openssl/crypto/modes/cfb128.c", "openssl/openssl/crypto/modes/ctr128.c", "openssl/openssl/crypto/modes/cts128.c", "openssl/openssl/crypto/modes/gcm128.c", "openssl/openssl/crypto/modes/ofb128.c", "openssl/openssl/crypto/modes/xts128.c", "openssl/openssl/crypto/o_dir.c", "openssl/openssl/crypto/o_fips.c", "openssl/openssl/crypto/o_init.c", "openssl/openssl/crypto/o_str.c", "openssl/openssl/crypto/o_time.c", "openssl/openssl/crypto/objects/o_names.c", "openssl/openssl/crypto/objects/obj_dat.c", "openssl/openssl/crypto/objects/obj_err.c", "openssl/openssl/crypto/objects/obj_lib.c", "openssl/openssl/crypto/objects/obj_xref.c", "openssl/openssl/crypto/ocsp/ocsp_asn.c", "openssl/openssl/crypto/ocsp/ocsp_cl.c", "openssl/openssl/crypto/ocsp/ocsp_err.c", "openssl/openssl/crypto/ocsp/ocsp_ext.c", "openssl/openssl/crypto/ocsp/ocsp_ht.c", "openssl/openssl/crypto/ocsp/ocsp_lib.c", "openssl/openssl/crypto/ocsp/ocsp_prn.c", "openssl/openssl/crypto/ocsp/ocsp_srv.c", "openssl/openssl/crypto/ocsp/ocsp_vfy.c", "openssl/openssl/crypto/pem/pem_all.c", "openssl/openssl/crypto/pem/pem_err.c", "openssl/openssl/crypto/pem/pem_info.c", "openssl/openssl/crypto/pem/pem_lib.c", "openssl/openssl/crypto/pem/pem_oth.c", "openssl/openssl/crypto/pem/pem_pk8.c", "openssl/openssl/crypto/pem/pem_pkey.c", "openssl/openssl/crypto/pem/pem_seal.c", "openssl/openssl/crypto/pem/pem_sign.c", "openssl/openssl/crypto/pem/pem_x509.c", "openssl/openssl/crypto/pem/pem_xaux.c", "openssl/openssl/crypto/pem/pvkfmt.c", "openssl/openssl/crypto/pkcs12/p12_add.c", "openssl/openssl/crypto/pkcs12/p12_asn.c", "openssl/openssl/crypto/pkcs12/p12_attr.c", "openssl/openssl/crypto/pkcs12/p12_crpt.c", "openssl/openssl/crypto/pkcs12/p12_crt.c", "openssl/openssl/crypto/pkcs12/p12_decr.c", "openssl/openssl/crypto/pkcs12/p12_init.c", "openssl/openssl/crypto/pkcs12/p12_key.c", "openssl/openssl/crypto/pkcs12/p12_kiss.c", "openssl/openssl/crypto/pkcs12/p12_mutl.c", "openssl/openssl/crypto/pkcs12/p12_npas.c", "openssl/openssl/crypto/pkcs12/p12_p8d.c", "openssl/openssl/crypto/pkcs12/p12_p8e.c", "openssl/openssl/crypto/pkcs12/p12_utl.c", "openssl/openssl/crypto/pkcs12/pk12err.c", "openssl/openssl/crypto/pkcs7/bio_pk7.c", "openssl/openssl/crypto/pkcs7/pk7_asn1.c", "openssl/openssl/crypto/pkcs7/pk7_attr.c", "openssl/openssl/crypto/pkcs7/pk7_doit.c", "openssl/openssl/crypto/pkcs7/pk7_lib.c", "openssl/openssl/crypto/pkcs7/pk7_mime.c", "openssl/openssl/crypto/pkcs7/pk7_smime.c", "openssl/openssl/crypto/pkcs7/pkcs7err.c", "openssl/openssl/crypto/pqueue/pqueue.c", "openssl/openssl/crypto/rand/md_rand.c", "openssl/openssl/crypto/rand/rand_egd.c", "openssl/openssl/crypto/rand/rand_err.c", "openssl/openssl/crypto/rand/rand_lib.c", "openssl/openssl/crypto/rand/rand_nw.c", "openssl/openssl/crypto/rand/rand_os2.c", "openssl/openssl/crypto/rand/rand_unix.c", "openssl/openssl/crypto/rand/rand_win.c", "openssl/openssl/crypto/rand/randfile.c", "openssl/openssl/crypto/rc2/rc2_cbc.c", "openssl/openssl/crypto/rc2/rc2_ecb.c", "openssl/openssl/crypto/rc2/rc2_skey.c", "openssl/openssl/crypto/rc2/rc2cfb64.c", "openssl/openssl/crypto/rc2/rc2ofb64.c", "openssl/openssl/crypto/rc4/rc4_utl.c", "openssl/openssl/crypto/ripemd/rmd_dgst.c", "openssl/openssl/crypto/ripemd/rmd_one.c", "openssl/openssl/crypto/rsa/rsa_ameth.c", "openssl/openssl/crypto/rsa/rsa_asn1.c", "openssl/openssl/crypto/rsa/rsa_chk.c", "openssl/openssl/crypto/rsa/rsa_crpt.c", "openssl/openssl/crypto/rsa/rsa_depr.c", "openssl/openssl/crypto/rsa/rsa_eay.c", "openssl/openssl/crypto/rsa/rsa_err.c", "openssl/openssl/crypto/rsa/rsa_gen.c", "openssl/openssl/crypto/rsa/rsa_lib.c", "openssl/openssl/crypto/rsa/rsa_none.c", "openssl/openssl/crypto/rsa/rsa_null.c", "openssl/openssl/crypto/rsa/rsa_oaep.c", "openssl/openssl/crypto/rsa/rsa_pk1.c", "openssl/openssl/crypto/rsa/rsa_pmeth.c", "openssl/openssl/crypto/rsa/rsa_prn.c", "openssl/openssl/crypto/rsa/rsa_pss.c", "openssl/openssl/crypto/rsa/rsa_saos.c", "openssl/openssl/crypto/rsa/rsa_sign.c", "openssl/openssl/crypto/rsa/rsa_ssl.c", "openssl/openssl/crypto/rsa/rsa_x931.c", "openssl/openssl/crypto/seed/seed.c", "openssl/openssl/crypto/seed/seed_cbc.c", "openssl/openssl/crypto/seed/seed_cfb.c", "openssl/openssl/crypto/seed/seed_ecb.c", "openssl/openssl/crypto/seed/seed_ofb.c", "openssl/openssl/crypto/sha/sha1_one.c", "openssl/openssl/crypto/sha/sha1dgst.c", "openssl/openssl/crypto/sha/sha256.c", "openssl/openssl/crypto/sha/sha512.c", "openssl/openssl/crypto/sha/sha_dgst.c", "openssl/openssl/crypto/sha/sha_one.c", "openssl/openssl/crypto/srp/srp_lib.c", "openssl/openssl/crypto/srp/srp_vfy.c", "openssl/openssl/crypto/stack/stack.c", "openssl/openssl/crypto/store/str_err.c", "openssl/openssl/crypto/store/str_lib.c", "openssl/openssl/crypto/store/str_mem.c", "openssl/openssl/crypto/store/str_meth.c", "openssl/openssl/crypto/ts/ts_asn1.c", "openssl/openssl/crypto/ts/ts_conf.c", "openssl/openssl/crypto/ts/ts_err.c", "openssl/openssl/crypto/ts/ts_lib.c", "openssl/openssl/crypto/ts/ts_req_print.c", "openssl/openssl/crypto/ts/ts_req_utils.c", "openssl/openssl/crypto/ts/ts_rsp_print.c", "openssl/openssl/crypto/ts/ts_rsp_sign.c", "openssl/openssl/crypto/ts/ts_rsp_utils.c", "openssl/openssl/crypto/ts/ts_rsp_verify.c", "openssl/openssl/crypto/ts/ts_verify_ctx.c", "openssl/openssl/crypto/txt_db/txt_db.c", "openssl/openssl/crypto/ui/ui_compat.c", "openssl/openssl/crypto/ui/ui_err.c", "openssl/openssl/crypto/ui/ui_lib.c", "openssl/openssl/crypto/ui/ui_openssl.c", "openssl/openssl/crypto/ui/ui_util.c", "openssl/openssl/crypto/uid.c", "openssl/openssl/crypto/whrlpool/wp_dgst.c", "openssl/openssl/crypto/x509/by_dir.c", "openssl/openssl/crypto/x509/by_file.c", "openssl/openssl/crypto/x509/x509_att.c", "openssl/openssl/crypto/x509/x509_cmp.c", "openssl/openssl/crypto/x509/x509_d2.c", "openssl/openssl/crypto/x509/x509_def.c", "openssl/openssl/crypto/x509/x509_err.c", "openssl/openssl/crypto/x509/x509_ext.c", "openssl/openssl/crypto/x509/x509_lu.c", "openssl/openssl/crypto/x509/x509_obj.c", "openssl/openssl/crypto/x509/x509_r2x.c", "openssl/openssl/crypto/x509/x509_req.c", "openssl/openssl/crypto/x509/x509_set.c", "openssl/openssl/crypto/x509/x509_trs.c", "openssl/openssl/crypto/x509/x509_txt.c", "openssl/openssl/crypto/x509/x509_v3.c", "openssl/openssl/crypto/x509/x509_vfy.c", "openssl/openssl/crypto/x509/x509_vpm.c", "openssl/openssl/crypto/x509/x509cset.c", "openssl/openssl/crypto/x509/x509name.c", "openssl/openssl/crypto/x509/x509rset.c", "openssl/openssl/crypto/x509/x509spki.c", "openssl/openssl/crypto/x509/x509type.c", "openssl/openssl/crypto/x509/x_all.c", "openssl/openssl/crypto/x509v3/pcy_cache.c", "openssl/openssl/crypto/x509v3/pcy_data.c", "openssl/openssl/crypto/x509v3/pcy_lib.c", "openssl/openssl/crypto/x509v3/pcy_map.c", "openssl/openssl/crypto/x509v3/pcy_node.c", "openssl/openssl/crypto/x509v3/pcy_tree.c", "openssl/openssl/crypto/x509v3/v3_addr.c", "openssl/openssl/crypto/x509v3/v3_akey.c", "openssl/openssl/crypto/x509v3/v3_akeya.c", "openssl/openssl/crypto/x509v3/v3_alt.c", "openssl/openssl/crypto/x509v3/v3_asid.c", "openssl/openssl/crypto/x509v3/v3_bcons.c", "openssl/openssl/crypto/x509v3/v3_bitst.c", "openssl/openssl/crypto/x509v3/v3_conf.c", "openssl/openssl/crypto/x509v3/v3_cpols.c", "openssl/openssl/crypto/x509v3/v3_crld.c", "openssl/openssl/crypto/x509v3/v3_enum.c", "openssl/openssl/crypto/x509v3/v3_extku.c", "openssl/openssl/crypto/x509v3/v3_genn.c", "openssl/openssl/crypto/x509v3/v3_ia5.c", "openssl/openssl/crypto/x509v3/v3_info.c", "openssl/openssl/crypto/x509v3/v3_int.c", "openssl/openssl/crypto/x509v3/v3_lib.c", "openssl/openssl/crypto/x509v3/v3_ncons.c", "openssl/openssl/crypto/x509v3/v3_ocsp.c", "openssl/openssl/crypto/x509v3/v3_pci.c", "openssl/openssl/crypto/x509v3/v3_pcia.c", "openssl/openssl/crypto/x509v3/v3_pcons.c", "openssl/openssl/crypto/x509v3/v3_pku.c", "openssl/openssl/crypto/x509v3/v3_pmaps.c", "openssl/openssl/crypto/x509v3/v3_prn.c", "openssl/openssl/crypto/x509v3/v3_purp.c", "openssl/openssl/crypto/x509v3/v3_skey.c", "openssl/openssl/crypto/x509v3/v3_sxnet.c", "openssl/openssl/crypto/x509v3/v3_utl.c", "openssl/openssl/crypto/x509v3/v3err.c", "openssl/openssl/engines/e_4758cca.c", "openssl/openssl/engines/e_aep.c", "openssl/openssl/engines/e_atalla.c", "openssl/openssl/engines/e_capi.c", "openssl/openssl/engines/e_chil.c", "openssl/openssl/engines/e_cswift.c", "openssl/openssl/engines/e_gmp.c", "openssl/openssl/engines/e_nuron.c", "openssl/openssl/engines/e_sureware.c", "openssl/openssl/engines/e_ubsec.c" ], "sources/": [ ["exclude", "md2/.*$"], ["exclude", "store/.*$"] ], "conditions": [ ["openssl_enable_asm!=1", { "defines": [ "OPENSSL_NO_ASM" ], "sources": [ "openssl/openssl/crypto/aes/aes_cbc.c", "openssl/openssl/crypto/aes/aes_core.c", "openssl/openssl/crypto/bf/bf_enc.c", "openssl/openssl/crypto/bn/bn_asm.c", "openssl/openssl/crypto/cast/c_enc.c", "openssl/openssl/crypto/camellia/camellia.c", "openssl/openssl/crypto/camellia/cmll_cbc.c", "openssl/openssl/crypto/camellia/cmll_misc.c", "openssl/openssl/crypto/des/des_enc.c", "openssl/openssl/crypto/des/fcrypt_b.c", "openssl/openssl/crypto/mem_clr.c", "openssl/openssl/crypto/rc4/rc4_enc.c", "openssl/openssl/crypto/rc4/rc4_skey.c", "openssl/openssl/crypto/whrlpool/wp_block.c" ] }, { "defines": [ "AES_ASM", "BF_ASM", "BNCO_ASM", "BN_ASM", "CPUID_ASM", "DES_ASM", "LIB_BN_ASM", "OPENSSL_BN_ASM", "OPENSSL_CPUID_OBJ", "RIP_ASM", "WHIRLPOOL_ASM", "WP_ASM" ], "conditions": [ ["OS!='win' and OS!='mac' and target_arch=='ia32'", { "sources": [ "asm/x86-elf-gas/aes/aes-586.s", "asm/x86-elf-gas/aes/aesni-x86.s", "asm/x86-elf-gas/bf/bf-686.s", "asm/x86-elf-gas/bn/x86-mont.s", "asm/x86-elf-gas/bn/x86.s", "asm/x86-elf-gas/camellia/cmll-x86.s", "asm/x86-elf-gas/cast/cast-586.s", "asm/x86-elf-gas/des/crypt586.s", "asm/x86-elf-gas/des/des-586.s", "asm/x86-elf-gas/md5/md5-586.s", "asm/x86-elf-gas/rc4/rc4-586.s", "asm/x86-elf-gas/rc5/rc5-586.s", "asm/x86-elf-gas/ripemd/rmd-586.s", "asm/x86-elf-gas/sha/sha1-586.s", "asm/x86-elf-gas/sha/sha256-586.s", "asm/x86-elf-gas/sha/sha512-586.s", "asm/x86-elf-gas/whrlpool/wp-mmx.s", "asm/x86-elf-gas/x86cpuid.s", "openssl/openssl/crypto/whrlpool/wp_block.c" ] }], ["OS!='win' and OS!='mac' and target_arch=='x64'", { "sources": [ "asm/x64-elf-gas/aes/aes-x86_64.s", "asm/x64-elf-gas/aes/aesni-x86_64.s", "asm/x64-elf-gas/aes/aesni-sha1-x86_64.s", "asm/x64-elf-gas/bn/modexp512-x86_64.s", "asm/x64-elf-gas/bn/x86_64-mont.s", "asm/x64-elf-gas/camellia/cmll-x86_64.s", "asm/x64-elf-gas/md5/md5-x86_64.s", "asm/x64-elf-gas/rc4/rc4-x86_64.s", "asm/x64-elf-gas/rc4/rc4-md5-x86_64.s", "asm/x64-elf-gas/sha/sha1-x86_64.s", "asm/x64-elf-gas/sha/sha512-x86_64.s", "asm/x64-elf-gas/whrlpool/wp-x86_64.s", "asm/x64-elf-gas/x86_64cpuid.s", #Non - generated asm "openssl/openssl/crypto/bn/asm/x86_64-gcc.c", #No asm available "openssl/openssl/crypto/bf/bf_enc.c", "openssl/openssl/crypto/cast/c_enc.c", "openssl/openssl/crypto/camellia/cmll_misc.c", "openssl/openssl/crypto/des/des_enc.c", "openssl/openssl/crypto/des/fcrypt_b.c" ] }], ["OS=='mac' and target_arch=='ia32'", { "sources": [ "asm/x86-macosx-gas/aes/aes-586.s", "asm/x86-macosx-gas/aes/aesni-x86.s", "asm/x86-macosx-gas/bf/bf-686.s", "asm/x86-macosx-gas/bn/x86-mont.s", "asm/x86-macosx-gas/bn/x86.s", "asm/x86-macosx-gas/camellia/cmll-x86.s", "asm/x86-macosx-gas/cast/cast-586.s", "asm/x86-macosx-gas/des/crypt586.s", "asm/x86-macosx-gas/des/des-586.s", "asm/x86-macosx-gas/md5/md5-586.s", "asm/x86-macosx-gas/rc4/rc4-586.s", "asm/x86-macosx-gas/rc5/rc5-586.s", "asm/x86-macosx-gas/ripemd/rmd-586.s", "asm/x86-macosx-gas/sha/sha1-586.s", "asm/x86-macosx-gas/sha/sha256-586.s", "asm/x86-macosx-gas/sha/sha512-586.s", "asm/x86-macosx-gas/whrlpool/wp-mmx.s", "asm/x86-macosx-gas/x86cpuid.s", "openssl/openssl/crypto/whrlpool/wp_block.c" ] }], ["OS=='mac' and target_arch=='x64'", { "sources": [ "asm/x64-macosx-gas/aes/aes-x86_64.s", "asm/x64-macosx-gas/aes/aesni-x86_64.s", "asm/x64-macosx-gas/aes/aesni-sha1-x86_64.s", "asm/x64-macosx-gas/bn/modexp512-x86_64.s", "asm/x64-macosx-gas/bn/x86_64-mont.s", "asm/x64-macosx-gas/camellia/cmll-x86_64.s", "asm/x64-macosx-gas/md5/md5-x86_64.s", "asm/x64-macosx-gas/rc4/rc4-x86_64.s", "asm/x64-macosx-gas/rc4/rc4-md5-x86_64.s", "asm/x64-macosx-gas/sha/sha1-x86_64.s", "asm/x64-macosx-gas/sha/sha512-x86_64.s", "asm/x64-macosx-gas/whrlpool/wp-x86_64.s", "asm/x64-macosx-gas/x86_64cpuid.s", #Non - generated asm "openssl/openssl/crypto/bn/asm/x86_64-gcc.c", #No asm available "openssl/openssl/crypto/bf/bf_enc.c", "openssl/openssl/crypto/cast/c_enc.c", "openssl/openssl/crypto/camellia/cmll_misc.c", "openssl/openssl/crypto/des/des_enc.c", "openssl/openssl/crypto/des/fcrypt_b.c" ] }], ["OS=='win' and target_arch=='ia32'", { "sources": [ "asm/x86-win32-masm/aes/aes-586.asm", "asm/x86-win32-masm/aes/aesni-x86.asm", "asm/x86-win32-masm/bf/bf-686.asm", "asm/x86-win32-masm/bn/x86-mont.asm", "asm/x86-win32-masm/bn/x86.asm", "asm/x86-win32-masm/camellia/cmll-x86.asm", "asm/x86-win32-masm/cast/cast-586.asm", "asm/x86-win32-masm/des/crypt586.asm", "asm/x86-win32-masm/des/des-586.asm", "asm/x86-win32-masm/md5/md5-586.asm", "asm/x86-win32-masm/rc4/rc4-586.asm", "asm/x86-win32-masm/rc5/rc5-586.asm", "asm/x86-win32-masm/ripemd/rmd-586.asm", "asm/x86-win32-masm/sha/sha1-586.asm", "asm/x86-win32-masm/sha/sha256-586.asm", "asm/x86-win32-masm/sha/sha512-586.asm", "asm/x86-win32-masm/whrlpool/wp-mmx.asm", "asm/x86-win32-masm/x86cpuid.asm", "openssl/openssl/crypto/whrlpool/wp_block.c" ], "rules": [ { "rule_name": "Assemble", "extension": "asm", "inputs": [], "outputs": [ "<(INTERMEDIATE_DIR)/<(RULE_INPUT_ROOT).obj", ], "action": [ "ml.exe", "/Zi", "/safeseh", "/Fo", "<(INTERMEDIATE_DIR)/<(RULE_INPUT_ROOT).obj", "/c", "<(RULE_INPUT_PATH)", ], "process_outputs_as_sources": 0, "message": "Assembling <(RULE_INPUT_PATH) to <(INTERMEDIATE_DIR)/<(RULE_INPUT_ROOT).obj.", } ] }], ["OS=='win' and target_arch=='x64'", { "sources": [ "asm/x64-win32-masm/aes/aes-x86_64.asm", "asm/x64-win32-masm/aes/aesni-x86_64.asm", "asm/x64-win32-masm/aes/aesni-sha1-x86_64.asm", "asm/x64-win32-masm/bn/modexp512-x86_64.asm", "asm/x64-win32-masm/bn/x86_64-mont.asm", "asm/x64-win32-masm/camellia/cmll-x86_64.asm", "asm/x64-win32-masm/md5/md5-x86_64.asm", "asm/x64-win32-masm/rc4/rc4-x86_64.asm", "asm/x64-win32-masm/rc4/rc4-md5-x86_64.asm", "asm/x64-win32-masm/sha/sha1-x86_64.asm", "asm/x64-win32-masm/sha/sha512-x86_64.asm", "asm/x64-win32-masm/whrlpool/wp-x86_64.asm", "asm/x64-win32-masm/x86_64cpuid.asm", #Non - generated asm "openssl/openssl/crypto/bn/asm/x86_64-win32-masm.asm", #No asm available "openssl/openssl/crypto/bf/bf_enc.c", "openssl/openssl/crypto/cast/c_enc.c", "openssl/openssl/crypto/camellia/cmll_misc.c", "openssl/openssl/crypto/des/des_enc.c", "openssl/openssl/crypto/des/fcrypt_b.c" ], "rules": [ { "rule_name": "Assemble", "extension": "asm", "inputs": [], "outputs": [ "<(INTERMEDIATE_DIR)/<(RULE_INPUT_ROOT).obj", ], "action": [ "ml64.exe", "/Zi", "/Fo", "<(INTERMEDIATE_DIR)/<(RULE_INPUT_ROOT).obj", "/c", "<(RULE_INPUT_PATH)", ], "process_outputs_as_sources": 0, "message": "Assembling <(RULE_INPUT_PATH) to <(INTERMEDIATE_DIR)/<(RULE_INPUT_ROOT).obj.", } ] }] ] }], ["OS=='win'", { "defines": [ "MK1MF_BUILD", "WIN32_LEAN_AND_MEAN" ], "link_settings": { "libraries": [ "-lgdi32.lib", "-luser32.lib", "-lwsock32.lib", ], "conditions": [ ["_type=='shared_library'", { "libraries": [ "-ladvapi32.lib" ] }] ] } }, { "defines": [ "TERMIOS", ], "cflags": [ "-Wno-missing-field-initializers" ], }], ["is_clang==1 or gcc_version>=43", { "cflags": [ "-Wno-old-style-declaration" ], }], ["OS=='solaris'", { "defines": [ "__EXTENSIONS__" ], }], ["target_arch=='arm'", { "sources": [ "openssl/openssl/crypto/armcap.c" ], }], ], }, ] }
true
true
f72a63ada453874531a4aa783d0ef1b05af45aff
21,710
py
Python
tests/engine/cloud/test_cloud_flows.py
tedmiston/prefect
a2cb40c28c942b1d170db42a55bab99598a4dcd6
[ "ECL-2.0", "Apache-2.0" ]
1
2020-05-10T14:32:32.000Z
2020-05-10T14:32:32.000Z
tests/engine/cloud/test_cloud_flows.py
tedmiston/prefect
a2cb40c28c942b1d170db42a55bab99598a4dcd6
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
tests/engine/cloud/test_cloud_flows.py
tedmiston/prefect
a2cb40c28c942b1d170db42a55bab99598a4dcd6
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
import datetime import sys import uuid from collections import Counter, namedtuple from unittest.mock import MagicMock import pendulum import pytest import prefect from prefect.client.client import Client, FlowRunInfoResult, TaskRunInfoResult from prefect.engine.cloud import CloudFlowRunner, CloudTaskRunner from prefect.engine.executors import LocalExecutor from prefect.engine.result_handlers import JSONResultHandler, ResultHandler from prefect.engine.state import ( Failed, Finished, Pending, Retrying, Running, Skipped, Success, TimedOut, TriggerFailed, ) from prefect.utilities.configuration import set_temporary_config pytestmark = pytest.mark.filterwarnings("ignore::UserWarning") class FlowRun: flow_id = str(uuid.uuid4()) def __init__(self, id, state=None, version=None): self.id = id self.name = "flow run name" self.state = state or Pending() self.version = version or 0 class TaskRun: def __init__( self, id, flow_run_id, task_slug, state=None, version=None, map_index=None ): self.id = id self.flow_run_id = flow_run_id self.task_id = task_slug self.task_slug = task_slug self.state = state or Pending() self.version = version or 0 self.map_index = map_index if map_index is not None else -1 @prefect.task def whats_the_time(): return prefect.context.get("scheduled_start_time") @prefect.task def plus_one(x): return x + 1 @prefect.task def invert_fail_once(x): try: return 1 / x except: if prefect.context.get("task_run_count", 0) < 2: raise else: return 100 @pytest.fixture(autouse=True) def cloud_settings(): with set_temporary_config( { "cloud.graphql": "http://my-cloud.foo", "cloud.auth_token": "token", "engine.flow_runner.default_class": "prefect.engine.cloud.CloudFlowRunner", "engine.task_runner.default_class": "prefect.engine.cloud.CloudTaskRunner", "logging.level": "DEBUG", } ): yield class MockedCloudClient(MagicMock): def __init__(self, flow_runs, task_runs, monkeypatch): super().__init__() self.flow_runs = {fr.id: fr for fr in flow_runs} self.task_runs = {tr.id: tr for tr in task_runs} self.call_count = Counter() monkeypatch.setattr( "prefect.engine.cloud.task_runner.Client", MagicMock(return_value=self) ) monkeypatch.setattr( "prefect.engine.cloud.flow_runner.Client", MagicMock(return_value=self) ) def get_flow_run_info(self, flow_run_id, *args, **kwargs): self.call_count["get_flow_run_info"] += 1 flow_run = self.flow_runs[flow_run_id] task_runs = [t for t in self.task_runs.values() if t.flow_run_id == flow_run_id] return FlowRunInfoResult( id=flow_run.id, flow_id=flow_run.flow_id, name=flow_run.name, parameters={}, context=None, version=flow_run.version, scheduled_start_time=pendulum.parse("2019-01-25T19:15:58.632412+00:00"), state=flow_run.state, task_runs=[ TaskRunInfoResult( id=tr.id, task_id=tr.task_slug, task_slug=tr.task_slug, version=tr.version, state=tr.state, ) for tr in task_runs ], ) def get_task_run_info(self, flow_run_id, task_id, map_index, *args, **kwargs): """ Return task run if found, otherwise create it """ self.call_count["get_task_run_info"] += 1 task_run = next( ( t for t in self.task_runs.values() if t.flow_run_id == flow_run_id and t.task_id == task_id and t.map_index == map_index ), None, ) if not task_run: task_run = TaskRun( id=str(uuid.uuid4()), task_slug=task_id, flow_run_id=flow_run_id, map_index=map_index, ) self.task_runs[task_run.id] = task_run return TaskRunInfoResult( id=task_run.id, task_id=task_id, task_slug=task_id, version=task_run.version, state=task_run.state, ) def set_flow_run_state(self, flow_run_id, version, state, **kwargs): self.call_count["set_flow_run_state"] += 1 self.call_count[flow_run_id] += 1 fr = self.flow_runs[flow_run_id] if fr.version == version: fr.state = state fr.version += 1 else: raise ValueError("Invalid flow run update") def set_task_run_state(self, task_run_id, version, state, **kwargs): self.call_count["set_task_run_state"] += 1 self.call_count[task_run_id] += 1 tr = self.task_runs[task_run_id] if tr.version == version: tr.state = state tr.version += 1 else: raise ValueError("Invalid task run update") return state @pytest.mark.parametrize("executor", ["local", "sync"], indirect=True) def test_simple_two_task_flow(monkeypatch, executor): flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) task_run_id_2 = str(uuid.uuid4()) with prefect.Flow(name="test") as flow: t1 = prefect.Task() t2 = prefect.Task() t2.set_upstream(t1) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun(id=task_run_id_1, task_slug=t1.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_2, task_slug=t2.slug, flow_run_id=flow_run_id), ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): state = CloudFlowRunner(flow=flow).run( return_tasks=flow.tasks, executor=executor ) assert state.is_successful() assert client.flow_runs[flow_run_id].state.is_successful() assert client.task_runs[task_run_id_1].state.is_successful() assert client.task_runs[task_run_id_1].version == 2 assert client.task_runs[task_run_id_2].state.is_successful() @pytest.mark.parametrize("executor", ["local", "sync"], indirect=True) def test_scheduled_start_time_is_in_context(monkeypatch, executor): flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) flow = prefect.Flow( name="test", tasks=[whats_the_time], result_handler=ResultHandler() ) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun( id=task_run_id_1, task_slug=whats_the_time.slug, flow_run_id=flow_run_id ) ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): state = CloudFlowRunner(flow=flow).run( return_tasks=flow.tasks, executor=executor ) assert state.is_successful() assert client.flow_runs[flow_run_id].state.is_successful() assert client.task_runs[task_run_id_1].state.is_successful() assert isinstance(state.result[whats_the_time].result, datetime.datetime) @pytest.mark.parametrize("executor", ["local", "sync"], indirect=True) def test_simple_two_task_flow_with_final_task_set_to_fail(monkeypatch, executor): flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) task_run_id_2 = str(uuid.uuid4()) with prefect.Flow(name="test") as flow: t1 = prefect.Task() t2 = prefect.Task() t2.set_upstream(t1) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun(id=task_run_id_1, task_slug=t1.slug, flow_run_id=flow_run_id), TaskRun( id=task_run_id_2, task_slug=t2.slug, flow_run_id=flow_run_id, state=Failed(), ), ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): state = CloudFlowRunner(flow=flow).run( return_tasks=flow.tasks, executor=executor ) assert state.is_failed() assert client.flow_runs[flow_run_id].state.is_failed() assert client.task_runs[task_run_id_1].state.is_successful() assert client.task_runs[task_run_id_1].version == 2 assert client.task_runs[task_run_id_2].state.is_failed() assert client.task_runs[task_run_id_2].version == 0 @pytest.mark.parametrize("executor", ["local", "sync"], indirect=True) def test_simple_two_task_flow_with_final_task_already_running(monkeypatch, executor): flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) task_run_id_2 = str(uuid.uuid4()) with prefect.Flow(name="test") as flow: t1 = prefect.Task() t2 = prefect.Task() t2.set_upstream(t1) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun(id=task_run_id_1, task_slug=t1.slug, flow_run_id=flow_run_id), TaskRun( id=task_run_id_2, task_slug=t2.slug, version=1, flow_run_id=flow_run_id, state=Running(), ), ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): state = CloudFlowRunner(flow=flow).run( return_tasks=flow.tasks, executor=executor ) assert state.is_running() assert client.flow_runs[flow_run_id].state.is_running() assert client.task_runs[task_run_id_1].state.is_successful() assert client.task_runs[task_run_id_1].version == 2 assert client.task_runs[task_run_id_2].state.is_running() assert client.task_runs[task_run_id_2].version == 1 @pytest.mark.parametrize("executor", ["local", "sync"], indirect=True) def test_simple_three_task_flow_with_one_failing_task(monkeypatch, executor): @prefect.task def error(): 1 / 0 flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) task_run_id_2 = str(uuid.uuid4()) task_run_id_3 = str(uuid.uuid4()) with prefect.Flow(name="test") as flow: t1 = prefect.Task() t2 = prefect.Task() t3 = error() t2.set_upstream(t1) t3.set_upstream(t2) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun(id=task_run_id_1, task_slug=t1.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_2, task_slug=t2.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_3, task_slug=t3.slug, flow_run_id=flow_run_id), ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): state = CloudFlowRunner(flow=flow).run( return_tasks=flow.tasks, executor=executor ) assert state.is_failed() assert client.flow_runs[flow_run_id].state.is_failed() assert client.task_runs[task_run_id_1].state.is_successful() assert client.task_runs[task_run_id_1].version == 2 assert client.task_runs[task_run_id_2].state.is_successful() assert client.task_runs[task_run_id_2].version == 2 assert client.task_runs[task_run_id_3].state.is_failed() assert client.task_runs[task_run_id_2].version == 2 @pytest.mark.parametrize("executor", ["local", "sync"], indirect=True) def test_simple_three_task_flow_with_first_task_retrying(monkeypatch, executor): """ If the first task retries, then the next two tasks shouldn't even make calls to Cloud because they won't pass their upstream checks """ @prefect.task(max_retries=1, retry_delay=datetime.timedelta(minutes=2)) def error(): 1 / 0 flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) task_run_id_2 = str(uuid.uuid4()) task_run_id_3 = str(uuid.uuid4()) with prefect.Flow(name="test") as flow: t1 = error() t2 = prefect.Task() t3 = prefect.Task() t2.set_upstream(t1) t3.set_upstream(t2) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun(id=task_run_id_1, task_slug=t1.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_2, task_slug=t2.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_3, task_slug=t3.slug, flow_run_id=flow_run_id), ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): state = CloudFlowRunner(flow=flow).run( return_tasks=flow.tasks, executor=executor ) assert state.is_running() assert client.flow_runs[flow_run_id].state.is_running() assert isinstance(client.task_runs[task_run_id_1].state, Retrying) assert client.task_runs[task_run_id_1].version == 3 assert client.task_runs[task_run_id_2].state.is_pending() assert client.task_runs[task_run_id_2].version == 0 assert client.task_runs[task_run_id_3].state.is_pending() assert client.task_runs[task_run_id_2].version == 0 assert client.call_count["set_task_run_state"] == 3 @pytest.mark.parametrize("executor", ["local", "sync"], indirect=True) def test_simple_map(monkeypatch, executor): flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) with prefect.Flow(name="test", result_handler=JSONResultHandler()) as flow: t1 = plus_one.map([0, 1, 2]) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun(id=task_run_id_1, task_slug=t1.slug, flow_run_id=flow_run_id) ] + [ TaskRun(id=str(uuid.uuid4()), task_slug=t.slug, flow_run_id=flow_run_id) for t in flow.tasks if t is not t1 ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): state = CloudFlowRunner(flow=flow).run( return_tasks=flow.tasks, executor=executor ) assert state.is_successful() assert client.flow_runs[flow_run_id].state.is_successful() assert client.task_runs[task_run_id_1].state.is_mapped() # there should be a total of 4 task runs corresponding to the mapped task assert len([tr for tr in client.task_runs.values() if tr.task_slug == t1.slug]) == 4 @pytest.mark.parametrize("executor", ["local", "sync"], indirect=True) def test_deep_map(monkeypatch, executor): flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) task_run_id_2 = str(uuid.uuid4()) task_run_id_3 = str(uuid.uuid4()) with prefect.Flow(name="test", result_handler=JSONResultHandler()) as flow: t1 = plus_one.map([0, 1, 2]) t2 = plus_one.map(t1) t3 = plus_one.map(t2) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun(id=task_run_id_1, task_slug=t1.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_2, task_slug=t2.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_3, task_slug=t3.slug, flow_run_id=flow_run_id), ] + [ TaskRun(id=str(uuid.uuid4()), task_slug=t.slug, flow_run_id=flow_run_id) for t in flow.tasks if t not in [t1, t2, t3] ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): state = CloudFlowRunner(flow=flow).run( return_tasks=flow.tasks, executor=executor ) assert state.is_successful() assert client.flow_runs[flow_run_id].state.is_successful() assert client.task_runs[task_run_id_1].state.is_mapped() assert client.task_runs[task_run_id_2].state.is_mapped() assert client.task_runs[task_run_id_3].state.is_mapped() # there should be a total of 4 task runs corresponding to each mapped task for t in [t1, t2, t3]: assert ( len([tr for tr in client.task_runs.values() if tr.task_slug == t.slug]) == 4 ) @pytest.mark.parametrize("executor", ["local", "sync"], indirect=True) def test_deep_map_with_a_failure(monkeypatch, executor): flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) task_run_id_2 = str(uuid.uuid4()) task_run_id_3 = str(uuid.uuid4()) with prefect.Flow(name="test", result_handler=JSONResultHandler()) as flow: t1 = plus_one.map([-1, 0, 1]) t2 = invert_fail_once.map(t1) t3 = plus_one.map(t2) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun(id=task_run_id_1, task_slug=t1.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_2, task_slug=t2.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_3, task_slug=t3.slug, flow_run_id=flow_run_id), ] + [ TaskRun(id=str(uuid.uuid4()), task_slug=t.slug, flow_run_id=flow_run_id) for t in flow.tasks if t not in [t1, t2, t3] ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): state = CloudFlowRunner(flow=flow).run(return_tasks=flow.tasks) assert state.is_failed() assert client.flow_runs[flow_run_id].state.is_failed() assert client.task_runs[task_run_id_1].state.is_mapped() assert client.task_runs[task_run_id_2].state.is_mapped() assert client.task_runs[task_run_id_3].state.is_mapped() # there should be a total of 4 task runs corresponding to each mapped task for t in [t1, t2, t3]: assert ( len([tr for tr in client.task_runs.values() if tr.task_slug == t.slug]) == 4 ) # t2's first child task should have failed t2_0 = next( tr for tr in client.task_runs.values() if tr.task_slug == t2.slug and tr.map_index == 0 ) assert t2_0.state.is_failed() # t3's first child task should have failed t3_0 = next( tr for tr in client.task_runs.values() if tr.task_slug == t3.slug and tr.map_index == 0 ) assert t3_0.state.is_failed() def test_deep_map_with_a_retry(monkeypatch): """ Creates a situation in which a deeply-mapped Flow encounters a one-time error in one of the middle layers. Running the flow a second time should resolve the error. DOES NOT WORK WITH DASK EXECUTORS because of the need for shared state on second run """ flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) task_run_id_2 = str(uuid.uuid4()) task_run_id_3 = str(uuid.uuid4()) with prefect.Flow(name="test", result_handler=JSONResultHandler()) as flow: t1 = plus_one.map([-1, 0, 1]) t2 = invert_fail_once.map(t1) t3 = plus_one.map(t2) t2.max_retries = 1 t2.retry_delay = datetime.timedelta(seconds=100) monkeypatch.setattr("requests.Session", MagicMock()) monkeypatch.setattr("requests.post", MagicMock()) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun(id=task_run_id_1, task_slug=t1.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_2, task_slug=t2.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_3, task_slug=t3.slug, flow_run_id=flow_run_id), ] + [ TaskRun(id=str(uuid.uuid4()), task_slug=t.slug, flow_run_id=flow_run_id) for t in flow.tasks if t not in [t1, t2, t3] ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): CloudFlowRunner(flow=flow).run(executor=LocalExecutor()) assert client.flow_runs[flow_run_id].state.is_running() assert client.task_runs[task_run_id_1].state.is_mapped() assert client.task_runs[task_run_id_2].state.is_mapped() assert client.task_runs[task_run_id_3].state.is_mapped() # there should be a total of 4 task runs corresponding to each mapped task for t in [t1, t2, t3]: assert ( len([tr for tr in client.task_runs.values() if tr.task_slug == t.slug]) == 4 ) # t2's first child task should be retrying t2_0 = next( tr for tr in client.task_runs.values() if tr.task_slug == t2.slug and tr.map_index == 0 ) assert isinstance(t2_0.state, Retrying) # t3's first child task should be pending t3_0 = next( tr for tr in client.task_runs.values() if tr.task_slug == t3.slug and tr.map_index == 0 ) assert t3_0.state.is_pending() # RUN A SECOND TIME with an artificially updated start time failed_id = [ t_id for t_id, tr in client.task_runs.items() if tr.task_slug == t2.slug and tr.map_index == 0 ].pop() client.task_runs[failed_id].state.start_time = pendulum.now("UTC") with prefect.context(flow_run_id=flow_run_id): CloudFlowRunner(flow=flow).run(executor=LocalExecutor()) # t2's first child task should be successful t2_0 = next( tr for tr in client.task_runs.values() if tr.task_slug == t2.slug and tr.map_index == 0 ) assert t2_0.state.is_successful() # t3's first child task should be successful t3_0 = next( tr for tr in client.task_runs.values() if tr.task_slug == t3.slug and tr.map_index == 0 ) assert t3_0.state.is_successful()
33.094512
89
0.643574
import datetime import sys import uuid from collections import Counter, namedtuple from unittest.mock import MagicMock import pendulum import pytest import prefect from prefect.client.client import Client, FlowRunInfoResult, TaskRunInfoResult from prefect.engine.cloud import CloudFlowRunner, CloudTaskRunner from prefect.engine.executors import LocalExecutor from prefect.engine.result_handlers import JSONResultHandler, ResultHandler from prefect.engine.state import ( Failed, Finished, Pending, Retrying, Running, Skipped, Success, TimedOut, TriggerFailed, ) from prefect.utilities.configuration import set_temporary_config pytestmark = pytest.mark.filterwarnings("ignore::UserWarning") class FlowRun: flow_id = str(uuid.uuid4()) def __init__(self, id, state=None, version=None): self.id = id self.name = "flow run name" self.state = state or Pending() self.version = version or 0 class TaskRun: def __init__( self, id, flow_run_id, task_slug, state=None, version=None, map_index=None ): self.id = id self.flow_run_id = flow_run_id self.task_id = task_slug self.task_slug = task_slug self.state = state or Pending() self.version = version or 0 self.map_index = map_index if map_index is not None else -1 @prefect.task def whats_the_time(): return prefect.context.get("scheduled_start_time") @prefect.task def plus_one(x): return x + 1 @prefect.task def invert_fail_once(x): try: return 1 / x except: if prefect.context.get("task_run_count", 0) < 2: raise else: return 100 @pytest.fixture(autouse=True) def cloud_settings(): with set_temporary_config( { "cloud.graphql": "http://my-cloud.foo", "cloud.auth_token": "token", "engine.flow_runner.default_class": "prefect.engine.cloud.CloudFlowRunner", "engine.task_runner.default_class": "prefect.engine.cloud.CloudTaskRunner", "logging.level": "DEBUG", } ): yield class MockedCloudClient(MagicMock): def __init__(self, flow_runs, task_runs, monkeypatch): super().__init__() self.flow_runs = {fr.id: fr for fr in flow_runs} self.task_runs = {tr.id: tr for tr in task_runs} self.call_count = Counter() monkeypatch.setattr( "prefect.engine.cloud.task_runner.Client", MagicMock(return_value=self) ) monkeypatch.setattr( "prefect.engine.cloud.flow_runner.Client", MagicMock(return_value=self) ) def get_flow_run_info(self, flow_run_id, *args, **kwargs): self.call_count["get_flow_run_info"] += 1 flow_run = self.flow_runs[flow_run_id] task_runs = [t for t in self.task_runs.values() if t.flow_run_id == flow_run_id] return FlowRunInfoResult( id=flow_run.id, flow_id=flow_run.flow_id, name=flow_run.name, parameters={}, context=None, version=flow_run.version, scheduled_start_time=pendulum.parse("2019-01-25T19:15:58.632412+00:00"), state=flow_run.state, task_runs=[ TaskRunInfoResult( id=tr.id, task_id=tr.task_slug, task_slug=tr.task_slug, version=tr.version, state=tr.state, ) for tr in task_runs ], ) def get_task_run_info(self, flow_run_id, task_id, map_index, *args, **kwargs): self.call_count["get_task_run_info"] += 1 task_run = next( ( t for t in self.task_runs.values() if t.flow_run_id == flow_run_id and t.task_id == task_id and t.map_index == map_index ), None, ) if not task_run: task_run = TaskRun( id=str(uuid.uuid4()), task_slug=task_id, flow_run_id=flow_run_id, map_index=map_index, ) self.task_runs[task_run.id] = task_run return TaskRunInfoResult( id=task_run.id, task_id=task_id, task_slug=task_id, version=task_run.version, state=task_run.state, ) def set_flow_run_state(self, flow_run_id, version, state, **kwargs): self.call_count["set_flow_run_state"] += 1 self.call_count[flow_run_id] += 1 fr = self.flow_runs[flow_run_id] if fr.version == version: fr.state = state fr.version += 1 else: raise ValueError("Invalid flow run update") def set_task_run_state(self, task_run_id, version, state, **kwargs): self.call_count["set_task_run_state"] += 1 self.call_count[task_run_id] += 1 tr = self.task_runs[task_run_id] if tr.version == version: tr.state = state tr.version += 1 else: raise ValueError("Invalid task run update") return state @pytest.mark.parametrize("executor", ["local", "sync"], indirect=True) def test_simple_two_task_flow(monkeypatch, executor): flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) task_run_id_2 = str(uuid.uuid4()) with prefect.Flow(name="test") as flow: t1 = prefect.Task() t2 = prefect.Task() t2.set_upstream(t1) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun(id=task_run_id_1, task_slug=t1.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_2, task_slug=t2.slug, flow_run_id=flow_run_id), ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): state = CloudFlowRunner(flow=flow).run( return_tasks=flow.tasks, executor=executor ) assert state.is_successful() assert client.flow_runs[flow_run_id].state.is_successful() assert client.task_runs[task_run_id_1].state.is_successful() assert client.task_runs[task_run_id_1].version == 2 assert client.task_runs[task_run_id_2].state.is_successful() @pytest.mark.parametrize("executor", ["local", "sync"], indirect=True) def test_scheduled_start_time_is_in_context(monkeypatch, executor): flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) flow = prefect.Flow( name="test", tasks=[whats_the_time], result_handler=ResultHandler() ) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun( id=task_run_id_1, task_slug=whats_the_time.slug, flow_run_id=flow_run_id ) ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): state = CloudFlowRunner(flow=flow).run( return_tasks=flow.tasks, executor=executor ) assert state.is_successful() assert client.flow_runs[flow_run_id].state.is_successful() assert client.task_runs[task_run_id_1].state.is_successful() assert isinstance(state.result[whats_the_time].result, datetime.datetime) @pytest.mark.parametrize("executor", ["local", "sync"], indirect=True) def test_simple_two_task_flow_with_final_task_set_to_fail(monkeypatch, executor): flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) task_run_id_2 = str(uuid.uuid4()) with prefect.Flow(name="test") as flow: t1 = prefect.Task() t2 = prefect.Task() t2.set_upstream(t1) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun(id=task_run_id_1, task_slug=t1.slug, flow_run_id=flow_run_id), TaskRun( id=task_run_id_2, task_slug=t2.slug, flow_run_id=flow_run_id, state=Failed(), ), ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): state = CloudFlowRunner(flow=flow).run( return_tasks=flow.tasks, executor=executor ) assert state.is_failed() assert client.flow_runs[flow_run_id].state.is_failed() assert client.task_runs[task_run_id_1].state.is_successful() assert client.task_runs[task_run_id_1].version == 2 assert client.task_runs[task_run_id_2].state.is_failed() assert client.task_runs[task_run_id_2].version == 0 @pytest.mark.parametrize("executor", ["local", "sync"], indirect=True) def test_simple_two_task_flow_with_final_task_already_running(monkeypatch, executor): flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) task_run_id_2 = str(uuid.uuid4()) with prefect.Flow(name="test") as flow: t1 = prefect.Task() t2 = prefect.Task() t2.set_upstream(t1) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun(id=task_run_id_1, task_slug=t1.slug, flow_run_id=flow_run_id), TaskRun( id=task_run_id_2, task_slug=t2.slug, version=1, flow_run_id=flow_run_id, state=Running(), ), ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): state = CloudFlowRunner(flow=flow).run( return_tasks=flow.tasks, executor=executor ) assert state.is_running() assert client.flow_runs[flow_run_id].state.is_running() assert client.task_runs[task_run_id_1].state.is_successful() assert client.task_runs[task_run_id_1].version == 2 assert client.task_runs[task_run_id_2].state.is_running() assert client.task_runs[task_run_id_2].version == 1 @pytest.mark.parametrize("executor", ["local", "sync"], indirect=True) def test_simple_three_task_flow_with_one_failing_task(monkeypatch, executor): @prefect.task def error(): 1 / 0 flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) task_run_id_2 = str(uuid.uuid4()) task_run_id_3 = str(uuid.uuid4()) with prefect.Flow(name="test") as flow: t1 = prefect.Task() t2 = prefect.Task() t3 = error() t2.set_upstream(t1) t3.set_upstream(t2) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun(id=task_run_id_1, task_slug=t1.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_2, task_slug=t2.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_3, task_slug=t3.slug, flow_run_id=flow_run_id), ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): state = CloudFlowRunner(flow=flow).run( return_tasks=flow.tasks, executor=executor ) assert state.is_failed() assert client.flow_runs[flow_run_id].state.is_failed() assert client.task_runs[task_run_id_1].state.is_successful() assert client.task_runs[task_run_id_1].version == 2 assert client.task_runs[task_run_id_2].state.is_successful() assert client.task_runs[task_run_id_2].version == 2 assert client.task_runs[task_run_id_3].state.is_failed() assert client.task_runs[task_run_id_2].version == 2 @pytest.mark.parametrize("executor", ["local", "sync"], indirect=True) def test_simple_three_task_flow_with_first_task_retrying(monkeypatch, executor): @prefect.task(max_retries=1, retry_delay=datetime.timedelta(minutes=2)) def error(): 1 / 0 flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) task_run_id_2 = str(uuid.uuid4()) task_run_id_3 = str(uuid.uuid4()) with prefect.Flow(name="test") as flow: t1 = error() t2 = prefect.Task() t3 = prefect.Task() t2.set_upstream(t1) t3.set_upstream(t2) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun(id=task_run_id_1, task_slug=t1.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_2, task_slug=t2.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_3, task_slug=t3.slug, flow_run_id=flow_run_id), ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): state = CloudFlowRunner(flow=flow).run( return_tasks=flow.tasks, executor=executor ) assert state.is_running() assert client.flow_runs[flow_run_id].state.is_running() assert isinstance(client.task_runs[task_run_id_1].state, Retrying) assert client.task_runs[task_run_id_1].version == 3 assert client.task_runs[task_run_id_2].state.is_pending() assert client.task_runs[task_run_id_2].version == 0 assert client.task_runs[task_run_id_3].state.is_pending() assert client.task_runs[task_run_id_2].version == 0 assert client.call_count["set_task_run_state"] == 3 @pytest.mark.parametrize("executor", ["local", "sync"], indirect=True) def test_simple_map(monkeypatch, executor): flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) with prefect.Flow(name="test", result_handler=JSONResultHandler()) as flow: t1 = plus_one.map([0, 1, 2]) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun(id=task_run_id_1, task_slug=t1.slug, flow_run_id=flow_run_id) ] + [ TaskRun(id=str(uuid.uuid4()), task_slug=t.slug, flow_run_id=flow_run_id) for t in flow.tasks if t is not t1 ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): state = CloudFlowRunner(flow=flow).run( return_tasks=flow.tasks, executor=executor ) assert state.is_successful() assert client.flow_runs[flow_run_id].state.is_successful() assert client.task_runs[task_run_id_1].state.is_mapped() assert len([tr for tr in client.task_runs.values() if tr.task_slug == t1.slug]) == 4 @pytest.mark.parametrize("executor", ["local", "sync"], indirect=True) def test_deep_map(monkeypatch, executor): flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) task_run_id_2 = str(uuid.uuid4()) task_run_id_3 = str(uuid.uuid4()) with prefect.Flow(name="test", result_handler=JSONResultHandler()) as flow: t1 = plus_one.map([0, 1, 2]) t2 = plus_one.map(t1) t3 = plus_one.map(t2) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun(id=task_run_id_1, task_slug=t1.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_2, task_slug=t2.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_3, task_slug=t3.slug, flow_run_id=flow_run_id), ] + [ TaskRun(id=str(uuid.uuid4()), task_slug=t.slug, flow_run_id=flow_run_id) for t in flow.tasks if t not in [t1, t2, t3] ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): state = CloudFlowRunner(flow=flow).run( return_tasks=flow.tasks, executor=executor ) assert state.is_successful() assert client.flow_runs[flow_run_id].state.is_successful() assert client.task_runs[task_run_id_1].state.is_mapped() assert client.task_runs[task_run_id_2].state.is_mapped() assert client.task_runs[task_run_id_3].state.is_mapped() for t in [t1, t2, t3]: assert ( len([tr for tr in client.task_runs.values() if tr.task_slug == t.slug]) == 4 ) @pytest.mark.parametrize("executor", ["local", "sync"], indirect=True) def test_deep_map_with_a_failure(monkeypatch, executor): flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) task_run_id_2 = str(uuid.uuid4()) task_run_id_3 = str(uuid.uuid4()) with prefect.Flow(name="test", result_handler=JSONResultHandler()) as flow: t1 = plus_one.map([-1, 0, 1]) t2 = invert_fail_once.map(t1) t3 = plus_one.map(t2) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun(id=task_run_id_1, task_slug=t1.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_2, task_slug=t2.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_3, task_slug=t3.slug, flow_run_id=flow_run_id), ] + [ TaskRun(id=str(uuid.uuid4()), task_slug=t.slug, flow_run_id=flow_run_id) for t in flow.tasks if t not in [t1, t2, t3] ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): state = CloudFlowRunner(flow=flow).run(return_tasks=flow.tasks) assert state.is_failed() assert client.flow_runs[flow_run_id].state.is_failed() assert client.task_runs[task_run_id_1].state.is_mapped() assert client.task_runs[task_run_id_2].state.is_mapped() assert client.task_runs[task_run_id_3].state.is_mapped() for t in [t1, t2, t3]: assert ( len([tr for tr in client.task_runs.values() if tr.task_slug == t.slug]) == 4 ) t2_0 = next( tr for tr in client.task_runs.values() if tr.task_slug == t2.slug and tr.map_index == 0 ) assert t2_0.state.is_failed() # t3's first child task should have failed t3_0 = next( tr for tr in client.task_runs.values() if tr.task_slug == t3.slug and tr.map_index == 0 ) assert t3_0.state.is_failed() def test_deep_map_with_a_retry(monkeypatch): flow_run_id = str(uuid.uuid4()) task_run_id_1 = str(uuid.uuid4()) task_run_id_2 = str(uuid.uuid4()) task_run_id_3 = str(uuid.uuid4()) with prefect.Flow(name="test", result_handler=JSONResultHandler()) as flow: t1 = plus_one.map([-1, 0, 1]) t2 = invert_fail_once.map(t1) t3 = plus_one.map(t2) t2.max_retries = 1 t2.retry_delay = datetime.timedelta(seconds=100) monkeypatch.setattr("requests.Session", MagicMock()) monkeypatch.setattr("requests.post", MagicMock()) client = MockedCloudClient( flow_runs=[FlowRun(id=flow_run_id)], task_runs=[ TaskRun(id=task_run_id_1, task_slug=t1.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_2, task_slug=t2.slug, flow_run_id=flow_run_id), TaskRun(id=task_run_id_3, task_slug=t3.slug, flow_run_id=flow_run_id), ] + [ TaskRun(id=str(uuid.uuid4()), task_slug=t.slug, flow_run_id=flow_run_id) for t in flow.tasks if t not in [t1, t2, t3] ], monkeypatch=monkeypatch, ) with prefect.context(flow_run_id=flow_run_id): CloudFlowRunner(flow=flow).run(executor=LocalExecutor()) assert client.flow_runs[flow_run_id].state.is_running() assert client.task_runs[task_run_id_1].state.is_mapped() assert client.task_runs[task_run_id_2].state.is_mapped() assert client.task_runs[task_run_id_3].state.is_mapped() for t in [t1, t2, t3]: assert ( len([tr for tr in client.task_runs.values() if tr.task_slug == t.slug]) == 4 ) t2_0 = next( tr for tr in client.task_runs.values() if tr.task_slug == t2.slug and tr.map_index == 0 ) assert isinstance(t2_0.state, Retrying) # t3's first child task should be pending t3_0 = next( tr for tr in client.task_runs.values() if tr.task_slug == t3.slug and tr.map_index == 0 ) assert t3_0.state.is_pending() failed_id = [ t_id for t_id, tr in client.task_runs.items() if tr.task_slug == t2.slug and tr.map_index == 0 ].pop() client.task_runs[failed_id].state.start_time = pendulum.now("UTC") with prefect.context(flow_run_id=flow_run_id): CloudFlowRunner(flow=flow).run(executor=LocalExecutor()) t2_0 = next( tr for tr in client.task_runs.values() if tr.task_slug == t2.slug and tr.map_index == 0 ) assert t2_0.state.is_successful() # t3's first child task should be successful t3_0 = next( tr for tr in client.task_runs.values() if tr.task_slug == t3.slug and tr.map_index == 0 ) assert t3_0.state.is_successful()
true
true
f72a6472f11d4bd876bdf957708a3a20931e06da
10,074
py
Python
scripts/fishnet_generator.py
dgketchum/gsflow-arcpy
966e8f48e0fee1ba534fc6a64987f67594b144f2
[ "Apache-2.0" ]
13
2018-09-12T17:42:48.000Z
2022-03-18T20:14:45.000Z
scripts/fishnet_generator.py
dgketchum/gsflow-arcpy
966e8f48e0fee1ba534fc6a64987f67594b144f2
[ "Apache-2.0" ]
35
2018-03-08T16:20:07.000Z
2020-11-05T11:59:05.000Z
scripts/fishnet_generator.py
dgketchum/gsflow-arcpy
966e8f48e0fee1ba534fc6a64987f67594b144f2
[ "Apache-2.0" ]
12
2018-08-18T20:54:56.000Z
2022-03-26T00:04:45.000Z
#-------------------------------- # Name: fishnet_generator.py # Purpose: GSFLOW fishnet generator # Notes: ArcGIS 10.2+ Version # Python: 2.7 #-------------------------------- import argparse import ConfigParser import datetime as dt from decimal import Decimal import logging import os import sys import arcpy from arcpy import env import support_functions as support def fishnet_func(config_path, overwrite_flag=False): """GSFLOW Fishnet Generator Args: config_file (str): Project config file path ovewrite_flag (bool): if True, overwrite existing files debug_flag (bool): if True, enable debug level logging Parameters ---------- config_path : str Project configuration file (.ini) path. ovewrite_flag : bool If True, overwrite existing files (the default is False). Returns ------- None """ # Initialize hru parameters class hru = support.HRUParameters(config_path) # Open input parameter config file inputs_cfg = ConfigParser.ConfigParser() try: inputs_cfg.readfp(open(config_path)) except Exception as e: logging.error( '\nERROR: Config file could not be read, ' 'is not an input file, or does not exist\n' ' config_file = {}\n' ' Exception: {}\n'.format(config_path, e)) sys.exit() # Log DEBUG to file log_file_name = 'fishnet_generator_log.txt' log_console = logging.FileHandler( filename=os.path.join(hru.log_ws, log_file_name), mode='w') log_console.setLevel(logging.DEBUG) log_console.setFormatter(logging.Formatter('%(message)s')) logging.getLogger('').addHandler(log_console) logging.info('\nGSFLOW Fishnet Generator') # Warn the user if the fishnet already exists # It might be better to not allow the user to do this at all and force them # to manually remove the file. if arcpy.Exists(hru.polygon_path) and not overwrite_flag: logging.warning('\nWARNING: The existing fishnet/grid will be ' 'over written\n {}'.format(hru.polygon_path)) raw_input('Press ENTER to continue') # Check input paths study_area_path = inputs_cfg.get('INPUTS', 'study_area_path') if not arcpy.Exists(study_area_path): logging.error( '\nERROR: Study area ({}) does not exist'.format( study_area_path)) sys.exit() # For now, study area has to be a polygon if arcpy.Describe(study_area_path).datasetType != 'FeatureClass': logging.error( '\nERROR: For now, study area must be a polygon shapefile') sys.exit() # Read Fishnet specific parameters from INI # If ref_x and ref_y are not specified, get from the study area extent try: hru.ref_x = inputs_cfg.getfloat('INPUTS', 'hru_ref_x') except: hru.ref_x = arcpy.Describe(study_area_path).extent.XMin logging.info( ' {0} parameter not set in INI, setting {0} = {1}'.format( 'ref_x', hru.ref_x)) try: hru.ref_y = inputs_cfg.getfloat('INPUTS', 'hru_ref_y') except: hru.ref_y = arcpy.Describe(study_area_path).extent.YMin logging.info( ' {0} parameter not set in INI, setting {0} = {1}'.format( 'ref_y', hru.ref_y)) try: buffer_cells = inputs_cfg.getint('INPUTS', 'hru_buffer_cells') except: buffer_cells = 2 logging.info( ' Missing INI parameter, setting {} = {}'.format( 'buffer_cells', buffer_cells)) try: snap_method = inputs_cfg.get('INPUTS', 'hru_param_snap_method') except: snap_method = 'EXPAND' logging.info( ' Missing INI parameter, setting {} = {}'.format( 'snap_method', snap_method)) snap_method_list = ['EXPAND', 'ROUND', 'SHRINK'] if snap_method not in snap_method_list: logging.error('\nERROR: {} must be: {}'.format( 'snap_method', ', '.join(snap_method_list))) sys.exit() # Log input hru parameters logging.info('\nFishnet Parameters') logging.info(' Cellsize: {}'.format(hru.cs)) logging.info(' Snap point: {} {}'.format(hru.ref_x, hru.ref_y)) logging.debug(' Buffer cells: {}'.format(buffer_cells)) # Read reference point as string for determining number of digits try: digits = abs(min( Decimal(inputs_cfg.get('INPUTS', 'hru_ref_x')).as_tuple().exponent, Decimal(inputs_cfg.get('INPUTS', 'hru_ref_y')).as_tuple().exponent)) except ConfigParser.NoOptionError: digits = 10 logging.debug(' Extent digits: {}'.format(digits)) # Check inputs if buffer_cells < 0: logging.error('\nERROR: Buffer cells must be greater than 0') sys.exit() # Build output folder if necessary fishnet_temp_ws = os.path.join(hru.param_ws, 'fishnet_temp') if not os.path.isdir(fishnet_temp_ws): os.mkdir(fishnet_temp_ws) # Output paths study_area_proj_path = os.path.join( fishnet_temp_ws, 'projected_study_area.shp') # Set ArcGIS environment variables arcpy.CheckOutExtension('Spatial') env.overwriteOutput = True env.pyramid = 'PYRAMIDS -1' # env.pyramid = 'PYRAMIDS 0' env.workspace = hru.param_ws env.scratchWorkspace = hru.scratch_ws # Get spatial reference of study_area hru.sr = arcpy.Describe(study_area_path).spatialReference # If study area spat_ref doesn't match hru_param spat_ref # Project study are to hru_param and get projected extent # Otherwise, read study_area extent directly study_area_extent = arcpy.Describe(study_area_path).extent logging.debug('\n Study area: {}'.format(study_area_path)) logging.debug(' Study area spat. ref.: {}'.format(hru.sr.name)) logging.debug(' Study area GCS: {}'.format(hru.sr.GCS.name)) logging.info(' Study Area extent: {}'.format( support.extent_string(study_area_extent))) # Check if the study area shapefile is projeted if (hru.sr.name in ['GCS_North_American_1983', 'GCS_WGS_1984'] or hru.sr.GCS.name == hru.sr.name): logging.warning( '\nWARNING: The study area shapefile does not appear to be projected.' '\n This will likely cause problems or not work at all.' '\n Projection: {}'.format(hru.sr.name)) raw_input('Press ENTER to continue\n') # Buffer extent buffer_extent = support.buffer_extent_func( study_area_extent, buffer_cells * hru.cs) logging.info(' Buffered Extent: {}'.format( support.extent_string(buffer_extent))) # Adjust study area extent to reference points # Set the number of digits of rounding based on the number digits # int the reference points hru.ref_pnt = arcpy.Point(hru.ref_x, hru.ref_y) hru.extent = support.adjust_extent_to_snap( buffer_extent, hru.ref_pnt, hru.cs, method=snap_method, digits=digits) logging.info(' Snapped Extent: {}'.format( support.extent_string(hru.extent))) # Build hru_param logging.info('\nBuilding HRU parameter fishnet') build_fishnet_func( hru.polygon_path, hru.point_path, hru.extent, hru.cs, hru.sr) # Write initial parameters to hru_param (X/Y, ROW/COL, Unique ID) # set_hru_id_func(hru.polygon_path, hru.extent, hru.cs) def build_fishnet_func(hru_polygon_path, hru_point_path, extent, cs, sr): """""" # Remove existing if arcpy.Exists(hru_polygon_path): arcpy.Delete_management(hru_polygon_path) if arcpy.Exists(hru_point_path): arcpy.Delete_management(hru_point_path) # Calculate LL/UR corner points origin_pnt = (extent.XMin, extent.YMin) yaxis_pnt = (extent.XMin, extent.YMin + cs) corner_pnt = (extent.XMax, extent.YMax) origin_str = ' '.join(map(str, origin_pnt)) yaxis_str = ' '.join(map(str, yaxis_pnt)) corner_str = ' '.join(map(str, corner_pnt)) logging.debug(' Origin: {}'.format(origin_str)) logging.debug(' Y-Axis: {}'.format(yaxis_str)) logging.debug(' Corner: {}'.format(corner_str)) # Build fishnet & labels arcpy.CreateFishnet_management( hru_polygon_path, origin_str, yaxis_str, cs, cs, '0', '0', corner_str, 'LABELS', '#', 'POLYGON') arcpy.DefineProjection_management(hru_polygon_path, sr) arcpy.DefineProjection_management(hru_point_path, sr) def arg_parse(): """""" parser = argparse.ArgumentParser( description='Fishnet Generator', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( '-i', '--ini', required=True, help='Project input file', metavar='PATH') parser.add_argument( '-o', '--overwrite', default=False, action="store_true", help='Force overwrite of existing files') parser.add_argument( '-d', '--debug', default=logging.INFO, const=logging.DEBUG, help='Debug level logging', action="store_const", dest="loglevel") args = parser.parse_args() # Convert input file to an absolute path if os.path.isfile(os.path.abspath(args.ini)): args.ini = os.path.abspath(args.ini) return args if __name__ == '__main__': args = arg_parse() logging.basicConfig(level=args.loglevel, format='%(message)s') logging.info('\n{}'.format('#' * 80)) log_f = '{:<20s} {}' logging.info(log_f.format( 'Run Time Stamp:', dt.datetime.now().isoformat(' '))) logging.info(log_f.format('Current Directory:', os.getcwd())) logging.info(log_f.format('Script:', os.path.basename(sys.argv[0]))) fishnet_func(config_path=args.ini, overwrite_flag=args.overwrite)
37.730337
83
0.629839
import argparse import ConfigParser import datetime as dt from decimal import Decimal import logging import os import sys import arcpy from arcpy import env import support_functions as support def fishnet_func(config_path, overwrite_flag=False): hru = support.HRUParameters(config_path) inputs_cfg = ConfigParser.ConfigParser() try: inputs_cfg.readfp(open(config_path)) except Exception as e: logging.error( '\nERROR: Config file could not be read, ' 'is not an input file, or does not exist\n' ' config_file = {}\n' ' Exception: {}\n'.format(config_path, e)) sys.exit() log_file_name = 'fishnet_generator_log.txt' log_console = logging.FileHandler( filename=os.path.join(hru.log_ws, log_file_name), mode='w') log_console.setLevel(logging.DEBUG) log_console.setFormatter(logging.Formatter('%(message)s')) logging.getLogger('').addHandler(log_console) logging.info('\nGSFLOW Fishnet Generator') if arcpy.Exists(hru.polygon_path) and not overwrite_flag: logging.warning('\nWARNING: The existing fishnet/grid will be ' 'over written\n {}'.format(hru.polygon_path)) raw_input('Press ENTER to continue') study_area_path = inputs_cfg.get('INPUTS', 'study_area_path') if not arcpy.Exists(study_area_path): logging.error( '\nERROR: Study area ({}) does not exist'.format( study_area_path)) sys.exit() if arcpy.Describe(study_area_path).datasetType != 'FeatureClass': logging.error( '\nERROR: For now, study area must be a polygon shapefile') sys.exit() try: hru.ref_x = inputs_cfg.getfloat('INPUTS', 'hru_ref_x') except: hru.ref_x = arcpy.Describe(study_area_path).extent.XMin logging.info( ' {0} parameter not set in INI, setting {0} = {1}'.format( 'ref_x', hru.ref_x)) try: hru.ref_y = inputs_cfg.getfloat('INPUTS', 'hru_ref_y') except: hru.ref_y = arcpy.Describe(study_area_path).extent.YMin logging.info( ' {0} parameter not set in INI, setting {0} = {1}'.format( 'ref_y', hru.ref_y)) try: buffer_cells = inputs_cfg.getint('INPUTS', 'hru_buffer_cells') except: buffer_cells = 2 logging.info( ' Missing INI parameter, setting {} = {}'.format( 'buffer_cells', buffer_cells)) try: snap_method = inputs_cfg.get('INPUTS', 'hru_param_snap_method') except: snap_method = 'EXPAND' logging.info( ' Missing INI parameter, setting {} = {}'.format( 'snap_method', snap_method)) snap_method_list = ['EXPAND', 'ROUND', 'SHRINK'] if snap_method not in snap_method_list: logging.error('\nERROR: {} must be: {}'.format( 'snap_method', ', '.join(snap_method_list))) sys.exit() logging.info('\nFishnet Parameters') logging.info(' Cellsize: {}'.format(hru.cs)) logging.info(' Snap point: {} {}'.format(hru.ref_x, hru.ref_y)) logging.debug(' Buffer cells: {}'.format(buffer_cells)) try: digits = abs(min( Decimal(inputs_cfg.get('INPUTS', 'hru_ref_x')).as_tuple().exponent, Decimal(inputs_cfg.get('INPUTS', 'hru_ref_y')).as_tuple().exponent)) except ConfigParser.NoOptionError: digits = 10 logging.debug(' Extent digits: {}'.format(digits)) if buffer_cells < 0: logging.error('\nERROR: Buffer cells must be greater than 0') sys.exit() fishnet_temp_ws = os.path.join(hru.param_ws, 'fishnet_temp') if not os.path.isdir(fishnet_temp_ws): os.mkdir(fishnet_temp_ws) study_area_proj_path = os.path.join( fishnet_temp_ws, 'projected_study_area.shp') arcpy.CheckOutExtension('Spatial') env.overwriteOutput = True env.pyramid = 'PYRAMIDS -1' env.workspace = hru.param_ws env.scratchWorkspace = hru.scratch_ws hru.sr = arcpy.Describe(study_area_path).spatialReference # Project study are to hru_param and get projected extent # Otherwise, read study_area extent directly study_area_extent = arcpy.Describe(study_area_path).extent logging.debug('\n Study area: {}'.format(study_area_path)) logging.debug(' Study area spat. ref.: {}'.format(hru.sr.name)) logging.debug(' Study area GCS: {}'.format(hru.sr.GCS.name)) logging.info(' Study Area extent: {}'.format( support.extent_string(study_area_extent))) # Check if the study area shapefile is projeted if (hru.sr.name in ['GCS_North_American_1983', 'GCS_WGS_1984'] or hru.sr.GCS.name == hru.sr.name): logging.warning( '\nWARNING: The study area shapefile does not appear to be projected.' '\n This will likely cause problems or not work at all.' '\n Projection: {}'.format(hru.sr.name)) raw_input('Press ENTER to continue\n') # Buffer extent buffer_extent = support.buffer_extent_func( study_area_extent, buffer_cells * hru.cs) logging.info(' Buffered Extent: {}'.format( support.extent_string(buffer_extent))) # Adjust study area extent to reference points # Set the number of digits of rounding based on the number digits # int the reference points hru.ref_pnt = arcpy.Point(hru.ref_x, hru.ref_y) hru.extent = support.adjust_extent_to_snap( buffer_extent, hru.ref_pnt, hru.cs, method=snap_method, digits=digits) logging.info(' Snapped Extent: {}'.format( support.extent_string(hru.extent))) # Build hru_param logging.info('\nBuilding HRU parameter fishnet') build_fishnet_func( hru.polygon_path, hru.point_path, hru.extent, hru.cs, hru.sr) # Write initial parameters to hru_param (X/Y, ROW/COL, Unique ID) # set_hru_id_func(hru.polygon_path, hru.extent, hru.cs) def build_fishnet_func(hru_polygon_path, hru_point_path, extent, cs, sr): # Remove existing if arcpy.Exists(hru_polygon_path): arcpy.Delete_management(hru_polygon_path) if arcpy.Exists(hru_point_path): arcpy.Delete_management(hru_point_path) # Calculate LL/UR corner points origin_pnt = (extent.XMin, extent.YMin) yaxis_pnt = (extent.XMin, extent.YMin + cs) corner_pnt = (extent.XMax, extent.YMax) origin_str = ' '.join(map(str, origin_pnt)) yaxis_str = ' '.join(map(str, yaxis_pnt)) corner_str = ' '.join(map(str, corner_pnt)) logging.debug(' Origin: {}'.format(origin_str)) logging.debug(' Y-Axis: {}'.format(yaxis_str)) logging.debug(' Corner: {}'.format(corner_str)) # Build fishnet & labels arcpy.CreateFishnet_management( hru_polygon_path, origin_str, yaxis_str, cs, cs, '0', '0', corner_str, 'LABELS', ' arcpy.DefineProjection_management(hru_polygon_path, sr) arcpy.DefineProjection_management(hru_point_path, sr) def arg_parse(): parser = argparse.ArgumentParser( description='Fishnet Generator', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( '-i', '--ini', required=True, help='Project input file', metavar='PATH') parser.add_argument( '-o', '--overwrite', default=False, action="store_true", help='Force overwrite of existing files') parser.add_argument( '-d', '--debug', default=logging.INFO, const=logging.DEBUG, help='Debug level logging', action="store_const", dest="loglevel") args = parser.parse_args() # Convert input file to an absolute path if os.path.isfile(os.path.abspath(args.ini)): args.ini = os.path.abspath(args.ini) return args if __name__ == '__main__': args = arg_parse() logging.basicConfig(level=args.loglevel, format='%(message)s') logging.info('\n{}'.format(' log_f = '{:<20s} {}' logging.info(log_f.format( 'Run Time Stamp:', dt.datetime.now().isoformat(' '))) logging.info(log_f.format('Current Directory:', os.getcwd())) logging.info(log_f.format('Script:', os.path.basename(sys.argv[0]))) fishnet_func(config_path=args.ini, overwrite_flag=args.overwrite)
true
true
f72a6574f160f049bb1e251b53b255e19fcb01c4
2,448
py
Python
test/functional/p2p_addrv2_relay.py
PivxLiteDev/PivxLite
648d4a193b61b1996b41e9f6c6c468875c757cdd
[ "MIT" ]
null
null
null
test/functional/p2p_addrv2_relay.py
PivxLiteDev/PivxLite
648d4a193b61b1996b41e9f6c6c468875c757cdd
[ "MIT" ]
3
2020-02-06T10:15:07.000Z
2022-01-13T00:08:49.000Z
test/functional/p2p_addrv2_relay.py
PivxLiteDev/PivxLite
648d4a193b61b1996b41e9f6c6c468875c757cdd
[ "MIT" ]
9
2020-03-10T14:14:25.000Z
2022-03-05T13:43:35.000Z
#!/usr/bin/env python3 # Copyright (c) 2020 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """ Test addrv2 relay """ import time from test_framework.messages import ( CAddress, msg_addrv2, NODE_NETWORK ) from test_framework.mininode import P2PInterface from test_framework.test_framework import PivxlTestFramework from test_framework.util import assert_equal ADDRS = [] for i in range(10): addr = CAddress() addr.time = int(time.time()) + i addr.nServices = NODE_NETWORK addr.ip = "123.123.123.{}".format(i % 256) addr.port = 8333 + i ADDRS.append(addr) class AddrReceiver(P2PInterface): addrv2_received_and_checked = False def __init__(self): super().__init__(support_addrv2 = True) def on_addrv2(self, message): for addr in message.addrs: assert_equal(addr.nServices, 1) # NODE_NETWORK assert addr.ip.startswith('123.123.123.') assert (8333 <= addr.port < 8343) self.addrv2_received_and_checked = True def wait_for_addrv2(self): self.wait_until(lambda: "addrv2" in self.last_message) class AddrTest(PivxlTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 def run_test(self): self.log.info('Create connection that sends addrv2 messages') addr_source = self.nodes[0].add_p2p_connection(P2PInterface()) msg = msg_addrv2() self.log.info('Send too-large addrv2 message') msg.addrs = ADDRS * 101 with self.nodes[0].assert_debug_log(['addrv2 message size = 1010']): addr_source.send_and_ping(msg) self.log.info('Check that addrv2 message content is relayed and added to addrman') addr_receiver = self.nodes[0].add_p2p_connection(AddrReceiver()) msg.addrs = ADDRS with self.nodes[0].assert_debug_log([ 'Added 10 addresses from 127.0.0.1: 0 tried', 'received: addrv2 (131 bytes) peer=1', 'sending addrv2 (131 bytes) peer=2', ]): addr_source.send_and_ping(msg) self.nodes[0].setmocktime(int(time.time()) + 30 * 60) addr_receiver.wait_for_addrv2() assert addr_receiver.addrv2_received_and_checked if __name__ == '__main__': AddrTest().main()
30.987342
90
0.664216
import time from test_framework.messages import ( CAddress, msg_addrv2, NODE_NETWORK ) from test_framework.mininode import P2PInterface from test_framework.test_framework import PivxlTestFramework from test_framework.util import assert_equal ADDRS = [] for i in range(10): addr = CAddress() addr.time = int(time.time()) + i addr.nServices = NODE_NETWORK addr.ip = "123.123.123.{}".format(i % 256) addr.port = 8333 + i ADDRS.append(addr) class AddrReceiver(P2PInterface): addrv2_received_and_checked = False def __init__(self): super().__init__(support_addrv2 = True) def on_addrv2(self, message): for addr in message.addrs: assert_equal(addr.nServices, 1) assert addr.ip.startswith('123.123.123.') assert (8333 <= addr.port < 8343) self.addrv2_received_and_checked = True def wait_for_addrv2(self): self.wait_until(lambda: "addrv2" in self.last_message) class AddrTest(PivxlTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 def run_test(self): self.log.info('Create connection that sends addrv2 messages') addr_source = self.nodes[0].add_p2p_connection(P2PInterface()) msg = msg_addrv2() self.log.info('Send too-large addrv2 message') msg.addrs = ADDRS * 101 with self.nodes[0].assert_debug_log(['addrv2 message size = 1010']): addr_source.send_and_ping(msg) self.log.info('Check that addrv2 message content is relayed and added to addrman') addr_receiver = self.nodes[0].add_p2p_connection(AddrReceiver()) msg.addrs = ADDRS with self.nodes[0].assert_debug_log([ 'Added 10 addresses from 127.0.0.1: 0 tried', 'received: addrv2 (131 bytes) peer=1', 'sending addrv2 (131 bytes) peer=2', ]): addr_source.send_and_ping(msg) self.nodes[0].setmocktime(int(time.time()) + 30 * 60) addr_receiver.wait_for_addrv2() assert addr_receiver.addrv2_received_and_checked if __name__ == '__main__': AddrTest().main()
true
true
f72a65ddec02cb6954334890b87a93ad0a175bef
257
py
Python
Akeso/Exploits/ExploitFrame.py
tamuctf/Akeso
05e6c284b45e1d1ec2d744a8508c9b03e3b5718e
[ "MIT" ]
19
2018-02-26T00:19:17.000Z
2019-12-18T04:26:45.000Z
Akeso/Exploits/ExploitFrame.py
tamuctf/Akeso
05e6c284b45e1d1ec2d744a8508c9b03e3b5718e
[ "MIT" ]
11
2018-05-07T15:11:30.000Z
2018-11-13T16:40:41.000Z
DefenseLab/Exploits/ExploitFrame.py
ameserole/Defense-Lab
05d89eecd52e76c00f6aa3ab0eaaff85fad88dbb
[ "MIT" ]
2
2019-12-11T07:28:48.000Z
2021-05-30T07:41:57.000Z
class ExploitFrame(object): """Exploit object""" def __init__(self, serviceInfo): self.serviceInfo = serviceInfo def exploit(self): raise NotImplementedError() def exploitSuccess(self): raise NotImplementedError()
21.416667
38
0.66537
class ExploitFrame(object): def __init__(self, serviceInfo): self.serviceInfo = serviceInfo def exploit(self): raise NotImplementedError() def exploitSuccess(self): raise NotImplementedError()
true
true
f72a66542ace53e924c25a5a10a82214486982d6
3,365
py
Python
SQSConnection.py
jmartipu/CrearSolicitudDispatcher
3b9c46f5f4a07fe96c98846c7f48d802203e8cee
[ "Apache-2.0" ]
null
null
null
SQSConnection.py
jmartipu/CrearSolicitudDispatcher
3b9c46f5f4a07fe96c98846c7f48d802203e8cee
[ "Apache-2.0" ]
null
null
null
SQSConnection.py
jmartipu/CrearSolicitudDispatcher
3b9c46f5f4a07fe96c98846c7f48d802203e8cee
[ "Apache-2.0" ]
null
null
null
import boto3 import botocore import Settings class SQSConnection: session = boto3.Session( aws_access_key_id=Settings.AWS_ACCESS_KEY_ID_SQS, aws_secret_access_key=Settings.AWS_SECRET_ACCESS_KEY_SQS, ) sqs = session.client('sqs', region_name=Settings.AWS_REGION_SQS) queue_url = Settings.AWS_QUEUE_URL_IN exists = True message = '' receipt_handle = '' def __init__(self, queue_url): self.queue_url = queue_url def __enter__(self): try: self.session = boto3.Session( aws_access_key_id=Settings.AWS_ACCESS_KEY_ID_SQS, aws_secret_access_key=Settings.AWS_SECRET_ACCESS_KEY_SQS, ) self.sqs = self.session.client('sqs', region_name=Settings.AWS_REGION_SQS) except ConnectionError: print("No se puede conectar a SQS") except Exception as e: print(e) def receive(self): try: response = self.sqs.receive_message( QueueUrl=self.queue_url, AttributeNames=[ 'ALL' ], MaxNumberOfMessages=1, MessageAttributeNames=[ 'All' ], VisibilityTimeout=20, WaitTimeSeconds=2 ) if response is not None: self.message = response['Messages'][0] self.receipt_handle = self.message['ReceiptHandle'] except botocore.exceptions.ClientError as e: # If a client error is thrown, then check that it was a 404 error. # If it was a 404 error, then the bucket does not exist. error_code = e.response['Error']['Code'] if error_code == '404': self.exists = False except Exception as e: print(e) def delete(self): try: print(self.receipt_handle) self.sqs.delete_message( QueueUrl=self.queue_url, ReceiptHandle=self.receipt_handle ) self.message = '' self.receipt_handle = '' except botocore.exceptions.ClientError as e: # If a client error is thrown, then check that it was a 404 error. # If it was a 404 error, then the bucket does not exist. error_code = e.response['Error']['Code'] if error_code == '404': self.exists = False except Exception as e: print('Error Cargando SQS') def __exit__(self, exc_type, exc_val, exc_tb): print("SQS Terminada exit") def send(self, data): try: print("inicia enviado") response = self.sqs.send_message( QueueUrl=self.queue_url, MessageAttributes=data.get('MessageAttributes'), MessageBody=data.get('Body'), ) print("termina enviado") except botocore.exceptions.ClientError as e: # If a client error is thrown, then check that it was a 404 error. # If it was a 404 error, then the bucket does not exist. error_code = e.response['Error']['Code'] if error_code == '404': self.exists = False except Exception as e: print(e)
31.157407
86
0.556612
import boto3 import botocore import Settings class SQSConnection: session = boto3.Session( aws_access_key_id=Settings.AWS_ACCESS_KEY_ID_SQS, aws_secret_access_key=Settings.AWS_SECRET_ACCESS_KEY_SQS, ) sqs = session.client('sqs', region_name=Settings.AWS_REGION_SQS) queue_url = Settings.AWS_QUEUE_URL_IN exists = True message = '' receipt_handle = '' def __init__(self, queue_url): self.queue_url = queue_url def __enter__(self): try: self.session = boto3.Session( aws_access_key_id=Settings.AWS_ACCESS_KEY_ID_SQS, aws_secret_access_key=Settings.AWS_SECRET_ACCESS_KEY_SQS, ) self.sqs = self.session.client('sqs', region_name=Settings.AWS_REGION_SQS) except ConnectionError: print("No se puede conectar a SQS") except Exception as e: print(e) def receive(self): try: response = self.sqs.receive_message( QueueUrl=self.queue_url, AttributeNames=[ 'ALL' ], MaxNumberOfMessages=1, MessageAttributeNames=[ 'All' ], VisibilityTimeout=20, WaitTimeSeconds=2 ) if response is not None: self.message = response['Messages'][0] self.receipt_handle = self.message['ReceiptHandle'] except botocore.exceptions.ClientError as e: error_code = e.response['Error']['Code'] if error_code == '404': self.exists = False except Exception as e: print(e) def delete(self): try: print(self.receipt_handle) self.sqs.delete_message( QueueUrl=self.queue_url, ReceiptHandle=self.receipt_handle ) self.message = '' self.receipt_handle = '' except botocore.exceptions.ClientError as e: error_code = e.response['Error']['Code'] if error_code == '404': self.exists = False except Exception as e: print('Error Cargando SQS') def __exit__(self, exc_type, exc_val, exc_tb): print("SQS Terminada exit") def send(self, data): try: print("inicia enviado") response = self.sqs.send_message( QueueUrl=self.queue_url, MessageAttributes=data.get('MessageAttributes'), MessageBody=data.get('Body'), ) print("termina enviado") except botocore.exceptions.ClientError as e: error_code = e.response['Error']['Code'] if error_code == '404': self.exists = False except Exception as e: print(e)
true
true
f72a674b8b8017122951cbd31901aa9c70d1de59
10,984
py
Python
insights/parsers/systemd/unitfiles.py
haithcockce/insights-core
b2e197c6bfc25bcbe2926f07c35a80f2cf8232f5
[ "Apache-2.0" ]
121
2017-05-30T20:23:25.000Z
2022-03-23T12:52:15.000Z
insights/parsers/systemd/unitfiles.py
haithcockce/insights-core
b2e197c6bfc25bcbe2926f07c35a80f2cf8232f5
[ "Apache-2.0" ]
1,977
2017-05-26T14:36:03.000Z
2022-03-31T10:38:53.000Z
insights/parsers/systemd/unitfiles.py
haithcockce/insights-core
b2e197c6bfc25bcbe2926f07c35a80f2cf8232f5
[ "Apache-2.0" ]
244
2017-05-30T20:22:57.000Z
2022-03-26T10:09:39.000Z
""" Units Manged By Systemctl (services) ==================================== Parsers included in this module are: ListUnits - command ``/bin/systemctl list-units`` ------------------------------------------------- UnitFiles - command ``/bin/systemctl list-unit-files`` ------------------------------------------------------ """ from .. import get_active_lines from ... import Parser, parser from insights.specs import Specs from insights.parsers import SkipException @parser(Specs.systemctl_list_unit_files) class UnitFiles(Parser): """ The UnitFiles class parses the output of ``/bin/systemctl list-unit-files`` and provides information about enabled services. Output of Command:: UNIT FILE STATE mariadb.service enabled neutron-openvswitch-agent.service enabled neutron-ovs-cleanup.service enabled neutron-server.service enabled runlevel0.target disabled runlevel1.target disabled runlevel2.target enabled Raises: SkipException: When nothing is parsed. Example: >>> conf.is_on('mariadb.service') True >>> conf.is_on('runlevel0.target') False >>> conf.exists('neutron-server.service') True >>> conf.exists('runlevel1.target') True >>> 'mariadb.service' in conf.services True >>> 'runlevel0.target' in conf.services True >>> 'nonexistent-service.service' in conf.services False >>> conf.services['mariadb.service'] True >>> conf.services['runlevel1.target'] False >>> conf.services['nonexistent-service.service'] Traceback (most recent call last): File "<doctest insights.parsers.systemd.unitfiles.UnitFiles[11]>", line 1, in <module> conf.services['nonexistent-service.service'] KeyError: 'nonexistent-service.service' """ def __init__(self, *args, **kwargs): self.services = {} """dict: Dictionary of bool indicating if service is enabled, access by service name .""" self.service_list = [] """list: List of service names in order of appearance.""" self.parsed_lines = {} """dict: Dictionary of content lines access by service name.""" super(UnitFiles, self).__init__(*args, **kwargs) def parse_content(self, content): """ Main parsing class method which stores all interesting data from the content. Args: content (context.content): Parser context content """ # 'static' means 'on' to fulfill dependency of something else that is on # man systemctl - "is-enabled" knows these states valid_states = set(['enabled', 'enabled-runtime', 'linked', 'linked-runtime', 'masked', 'masked-runtime', 'static', 'indirect', 'disabled', 'generated', 'transient', 'bad', 'invalid']) # man systemctl - "is-enabled" considers these to be enabled on_states = set(['enabled', 'enabled-runtime', 'static', 'indirect', 'generated', 'transient']) for line in get_active_lines(content): parts = line.split(None) # AWK like split, strips whitespaces if len(parts) == 2 and any(part in valid_states for part in parts): service, state = parts enabled = state in on_states self.services[service] = enabled self.parsed_lines[service] = line self.service_list.append(service) if not self.services: raise SkipException def is_on(self, service_name): """ Checks if the service is enabled in systemctl. Args: service_name (str): service name including '.service' Returns: Union[bool, None]: True if service is enabled, False if it is disabled. None if the service doesn't exist. """ return self.services.get(service_name, None) def exists(self, service_name): """ Checks if the service is listed in systemctl. Args: service_name (str): service name including '.service' Returns: bool: True if service exists, False otherwise. """ return service_name in self.service_list @parser(Specs.systemctl_list_units) class ListUnits(Parser): """ The ListUnits class parses the output of ``/bin/systemctl list-units`` and provides information about all the services listed under it. Output of Command:: UNIT LOAD ACTIVE SUB DESCRIPTION sockets.target loaded active active Sockets swap.target loaded active active Swap systemd-shutdownd.socket loaded active listening Delayed Shutdown Socket neutron-dhcp-agent.service loaded active running OpenStack Neutron DHCP Agent neutron-openvswitch-agent.service loaded active running OpenStack Neutron Open vSwitch Agent ... unbound-anchor.timer loaded active waiting daily update of the root trust anchor for DNSSEC LOAD = Reflects whether the unit definition was properly loaded. ACTIVE = The high-level unit activation state, i.e. generalization of SUB. SUB = The low-level unit activation state, values depend on unit type. 161 loaded units listed. Pass --all to see loaded but inactive units, too. To show all installed unit files use 'systemctl list-unit-files'. Raises: SkipException: When nothing is parsed. Example: >>> units.get_service_details('swap.target') == {'LOAD': 'loaded', 'ACTIVE': 'active', 'SUB': 'active', 'UNIT': 'swap.target', 'DESCRIPTION': 'Swap'} True >>> units.unit_list['swap.target'] == {'LOAD': 'loaded', 'ACTIVE': 'active', 'SUB': 'active', 'UNIT': 'swap.target', 'DESCRIPTION': 'Swap'} True >>> units.is_active('swap.target') True >>> units.get_service_details('random.service') == {'LOAD': None, 'ACTIVE': None, 'SUB': None, 'UNIT': None, 'DESCRIPTION': None} True """ EMPTY_DETAILS = {'LOAD': None, 'ACTIVE': None, 'SUB': None, 'UNIT': None, 'DESCRIPTION': None} def __init__(self, *args, **kwargs): self.unit_list = {} """dict: Dictionary service detail like active, running, exited, dead""" super(ListUnits, self).__init__(*args, **kwargs) def parse_service_details(self, parts): # man systemctl - "is-enabled" knows these states valid_states = set(['invalid', 'loaded', 'inactive', 'active', 'exited', 'running', 'failed', 'mounted', 'waiting', 'plugged']) valid_units = set(['service', 'socket', 'device', 'mount', 'automount', 'swap', 'target', 'path', 'timer', 'slice', 'scope']) service_details = {} if (len(parts) >= 4 and any(part in valid_states for part in parts) and any(unit in parts[0] for unit in valid_units)): service_details['UNIT'] = parts[0] service_details['LOAD'] = parts[1] service_details['ACTIVE'] = parts[2] service_details['SUB'] = parts[3] service_details['DESCRIPTION'] = ' '.join(parts[4:]) if len(parts) > 4 else None return service_details def parse_content(self, content): """ Main parsing class method which stores all interesting data from the content. Args: content (context.content): Parser context content """ BULLET_CHAR_U = u'\u25CF' BULLET_CHAR_B = b"\xe2\x97\x8f" for line in get_active_lines(content): # If this is a heading line, then ignore this line if line.startswith('UNIT '): continue parts = line.split(None) # AWK like split, strips whitespaces first_part = 0 if parts[0] == BULLET_CHAR_U or parts[0].encode('utf-8') == BULLET_CHAR_B or parts[0] == '*': first_part = 1 # If past the end of the list then quit if parts[first_part] in ['LOAD', 'ACTIVE', 'SUB']: break service_details = self.parse_service_details(parts[first_part:]) if service_details: self.unit_list[parts[first_part]] = service_details if not self.unit_list: raise SkipException def get_service_details(self, service_name): """ Return the service details collected by systemctl. Args: service_name (str): service name including its extension. Returns: dict: Dictionary containing details for the service. if service is not present dictonary values will be `None`:: {'LOAD': 'loaded', 'ACTIVE': 'active', 'SUB': 'running', 'UNIT': 'neutron-dhcp-agent.service'} """ return self.unit_list.get(service_name, ListUnits.EMPTY_DETAILS) def is_loaded(self, service_name): """ Return the LOAD state of service managed by systemd. Args: service_name (str): service name including its extension. Returns: bool: True if service is loaded False if not loaded """ return self.get_service_details(service_name)['LOAD'] == 'loaded' def is_active(self, service_name): """ Return the ACTIVE state of service managed by systemd. Args: service_name (str): service name including its extension. Returns: bool: True if service is active False if inactive """ return self.get_service_details(service_name)['ACTIVE'] == 'active' def is_running(self, service_name): """ Return the SUB state of service managed by systemd. Args: service_name (str): service name including its extension. Returns: bool: True if service is running False in all other states. """ return self.get_service_details(service_name)['SUB'] == 'running' def is_failed(self, service_name): """ Return the ACTIVE state of service managed by systemd. Args: service_name (str): service name including its extension. Returns: bool: True if service is failed, False in all other states. """ return self.get_service_details(service_name)['ACTIVE'] == 'failed' @property def service_names(self): """list: Returns a list of all UNIT names.""" return list(self.unit_list.keys())
37.745704
157
0.584578
from .. import get_active_lines from ... import Parser, parser from insights.specs import Specs from insights.parsers import SkipException @parser(Specs.systemctl_list_unit_files) class UnitFiles(Parser): def __init__(self, *args, **kwargs): self.services = {} self.service_list = [] self.parsed_lines = {} super(UnitFiles, self).__init__(*args, **kwargs) def parse_content(self, content): valid_states = set(['enabled', 'enabled-runtime', 'linked', 'linked-runtime', 'masked', 'masked-runtime', 'static', 'indirect', 'disabled', 'generated', 'transient', 'bad', 'invalid']) on_states = set(['enabled', 'enabled-runtime', 'static', 'indirect', 'generated', 'transient']) for line in get_active_lines(content): parts = line.split(None) if len(parts) == 2 and any(part in valid_states for part in parts): service, state = parts enabled = state in on_states self.services[service] = enabled self.parsed_lines[service] = line self.service_list.append(service) if not self.services: raise SkipException def is_on(self, service_name): return self.services.get(service_name, None) def exists(self, service_name): return service_name in self.service_list @parser(Specs.systemctl_list_units) class ListUnits(Parser): EMPTY_DETAILS = {'LOAD': None, 'ACTIVE': None, 'SUB': None, 'UNIT': None, 'DESCRIPTION': None} def __init__(self, *args, **kwargs): self.unit_list = {} super(ListUnits, self).__init__(*args, **kwargs) def parse_service_details(self, parts): valid_states = set(['invalid', 'loaded', 'inactive', 'active', 'exited', 'running', 'failed', 'mounted', 'waiting', 'plugged']) valid_units = set(['service', 'socket', 'device', 'mount', 'automount', 'swap', 'target', 'path', 'timer', 'slice', 'scope']) service_details = {} if (len(parts) >= 4 and any(part in valid_states for part in parts) and any(unit in parts[0] for unit in valid_units)): service_details['UNIT'] = parts[0] service_details['LOAD'] = parts[1] service_details['ACTIVE'] = parts[2] service_details['SUB'] = parts[3] service_details['DESCRIPTION'] = ' '.join(parts[4:]) if len(parts) > 4 else None return service_details def parse_content(self, content): BULLET_CHAR_U = u'\u25CF' BULLET_CHAR_B = b"\xe2\x97\x8f" for line in get_active_lines(content): if line.startswith('UNIT '): continue parts = line.split(None) first_part = 0 if parts[0] == BULLET_CHAR_U or parts[0].encode('utf-8') == BULLET_CHAR_B or parts[0] == '*': first_part = 1 if parts[first_part] in ['LOAD', 'ACTIVE', 'SUB']: break service_details = self.parse_service_details(parts[first_part:]) if service_details: self.unit_list[parts[first_part]] = service_details if not self.unit_list: raise SkipException def get_service_details(self, service_name): return self.unit_list.get(service_name, ListUnits.EMPTY_DETAILS) def is_loaded(self, service_name): return self.get_service_details(service_name)['LOAD'] == 'loaded' def is_active(self, service_name): return self.get_service_details(service_name)['ACTIVE'] == 'active' def is_running(self, service_name): return self.get_service_details(service_name)['SUB'] == 'running' def is_failed(self, service_name): return self.get_service_details(service_name)['ACTIVE'] == 'failed' @property def service_names(self): return list(self.unit_list.keys())
true
true
f72a681dedfbe58c031e09445ad13611853eefec
5,987
py
Python
tests/test_public_client.py
shanefontaine/ethfinex-python
a883eb8e72d1c87156db62adbc5f95bb82fa5371
[ "MIT" ]
7
2018-12-25T09:55:40.000Z
2021-05-14T04:23:44.000Z
tests/test_public_client.py
shanefontaine/ethfinex-python
a883eb8e72d1c87156db62adbc5f95bb82fa5371
[ "MIT" ]
4
2019-03-08T09:37:35.000Z
2021-06-01T23:12:31.000Z
tests/test_public_client.py
shanefontaine/ethfinex-python
a883eb8e72d1c87156db62adbc5f95bb82fa5371
[ "MIT" ]
1
2021-04-24T01:11:01.000Z
2021-04-24T01:11:01.000Z
import pytest import time from ethfinex.public_client import PublicClient @pytest.fixture(scope='module') def client(): return PublicClient() @pytest.mark.usefixtures('client') class TestPublicClient(object): @staticmethod def teardown_method(): time.sleep(.5) # Avoid rate limit def test_get_platform_status(self, client): r = client.get_platform_status() assert type(r) is list @pytest.mark.parametrize('pair', ['tBTCUSD', 'tETHBTC']) def test_get_ticker(self, client, pair): r = client.get_ticker(pair) assert type(r) is list assert len(r) is 10 @pytest.mark.parametrize('pair, limit, start, end, sort', [ ('tBTCUSD', 120, None, None, 0), ('tBTCUSD', 120, 1514764800000, 1514765700000, 0), ('tBTCUSD', None, None, None, None), ('tBTCUSD', 10, 1514764800000, 1514765700000, 0), ('tBTCUSD', 10, 1514764800000, 1514768400000, 0), ('tBTCUSD', 10, 1514764800000, 1514768400000, 1), pytest.param('tBTCUSD', 10, 1514765700000, 1514764800000, 1, marks=pytest.mark.xfail) ]) def test_get_trades(self, client, pair, limit, start, end, sort): r = client.get_trades(pair, limit, start, end, sort) limit = 120 if not limit else limit # Check length assert len(r) == limit # Check timestamps if start and end: for entry in r: timestamp = entry[1] assert start <= timestamp <= end # Check sort if sort == 1: assert r[0][1] <= r[1][1] else: assert r[0][1] >= r[1][1] @pytest.mark.parametrize('pair, precision, length', [ ('tBTCUSD', 'P0', None), ('tBTCUSD', 'P0', 25), ('tBTCUSD', 'P0', 100), ('tBTCUSD', 'P4', None), ('tBTCUSD', 'P1', 25), ('tBTCUSD', 'P2', 25), pytest.param('tBTCUSD', 'P2', 5, marks=pytest.mark.xfail), pytest.param('tBTCUSD', None, 5, marks=pytest.mark.xfail), ]) def test_get_books(self, client, pair, precision, length): r = client.get_books(pair, precision, length) # Default length is 50. Returns double the amount length = 50 if not length else length * 2 # Check length assert len(r) == length # Check Precision price = str(r[0][0]) if precision == 'P0': digits = len(price.split(".")) # Will return either a whole number or a single decimal assert (digits == 1 or digits == 2) elif precision == 'P1': assert len(price) == 4 elif precision == 'P2': assert len(price) == 4 assert price[-1] == '0' elif precision == 'P3': assert len(price) == 4 assert price[-1] == '0' assert price[-2] == '0' elif precision == 'P4': assert len(price) == 4 assert price[-1] == '0' assert price[-2] == '0' assert price[-3] == '0' elif precision == 'R0': assert len(price == 11) @pytest.mark.parametrize('symbol, key, side, section, sort', [ ('fUSD', 'funding.size', 'long', 'hist', 0), ('fUSD', 'credits.size', 'long', 'hist', 0), # TODO: Figure out credits.size.sym # TODO: Figure out pos.size ('fUSD', 'funding.size', 'long', 'last', 0), ('fUSD', 'funding.size', 'long', 'last', 1), ('fUSD', 'credits.size', 'long', 'last', 1), pytest.param(None, None, None, None, None, marks=pytest.mark.xfail) ]) def test_get_stats(self, client, symbol, key, side, section, sort): r = client.get_stats(symbol, key, side, section, sort) # Check length if section == 'hist': assert len(r) == 120 elif section == 'last': assert len(r) == 2 # Check sort. There is no `section == 'last'` because you cannot sort # a single entry if sort == 1 and section == 'hist': assert r[0][0] <= r[1][0] elif sort != 1 and section == 'hist': assert r[0][0] >= r[1][0] @pytest.mark.parametrize('symbol, time_frame, section, limit, start, end, sort', [ ('tBTCUSD', '1m', 'hist', None, None, None, None), ('tBTCUSD', '15m', 'hist', 1, None, None, None), ('tBTCUSD', '15m', 'hist', 1, None, None, 1), ('tBTCUSD', '15m', 'hist', 1, 1514764800000, 1514765700000, 1), ('tBTCUSD', '15m', 'hist', 1, 1514764800000, 1514768400000, 1), ('tBTCUSD', '1m', 'last', None, None, None, None), ('tBTCUSD', '15m', 'last', 1, 1514764800000, 1514768400000, 1), ('tBTCUSD', '1m', 'last', 1, 1514768400000, 1514764800000, 1), pytest.param(None, None, None, None, None, None, None, marks=pytest.mark.xfail), pytest.param('tBTCUSD', '1m', 'hist', 1, 1514768400000, 1514764800000, 1, marks=pytest.mark.xfail) ]) def test_get_candles(self, client, symbol, time_frame, section, limit, start, end, sort): r = client.get_candles(symbol, time_frame, section, limit, start, end, sort) # Check length if section == 'hist' and limit != 1: assert len(r) == 120 elif section == 'hist' and limit == 1: assert len(r) == 1 elif section == 'last' and limit == 1: assert len(r) == 6 elif section == 'last' and limit == 1: assert len(r) == 1 # Check sort. There is no `section == 'last'` because you cannot sort # a single entry if sort == 1 and section == 'hist' and limit != 1: assert r[0][0] <= r[1][0] elif sort != 1 and section == 'hist' and limit != 1: assert r[0][0] >= r[1][0]
36.730061
86
0.525639
import pytest import time from ethfinex.public_client import PublicClient @pytest.fixture(scope='module') def client(): return PublicClient() @pytest.mark.usefixtures('client') class TestPublicClient(object): @staticmethod def teardown_method(): time.sleep(.5) def test_get_platform_status(self, client): r = client.get_platform_status() assert type(r) is list @pytest.mark.parametrize('pair', ['tBTCUSD', 'tETHBTC']) def test_get_ticker(self, client, pair): r = client.get_ticker(pair) assert type(r) is list assert len(r) is 10 @pytest.mark.parametrize('pair, limit, start, end, sort', [ ('tBTCUSD', 120, None, None, 0), ('tBTCUSD', 120, 1514764800000, 1514765700000, 0), ('tBTCUSD', None, None, None, None), ('tBTCUSD', 10, 1514764800000, 1514765700000, 0), ('tBTCUSD', 10, 1514764800000, 1514768400000, 0), ('tBTCUSD', 10, 1514764800000, 1514768400000, 1), pytest.param('tBTCUSD', 10, 1514765700000, 1514764800000, 1, marks=pytest.mark.xfail) ]) def test_get_trades(self, client, pair, limit, start, end, sort): r = client.get_trades(pair, limit, start, end, sort) limit = 120 if not limit else limit assert len(r) == limit if start and end: for entry in r: timestamp = entry[1] assert start <= timestamp <= end if sort == 1: assert r[0][1] <= r[1][1] else: assert r[0][1] >= r[1][1] @pytest.mark.parametrize('pair, precision, length', [ ('tBTCUSD', 'P0', None), ('tBTCUSD', 'P0', 25), ('tBTCUSD', 'P0', 100), ('tBTCUSD', 'P4', None), ('tBTCUSD', 'P1', 25), ('tBTCUSD', 'P2', 25), pytest.param('tBTCUSD', 'P2', 5, marks=pytest.mark.xfail), pytest.param('tBTCUSD', None, 5, marks=pytest.mark.xfail), ]) def test_get_books(self, client, pair, precision, length): r = client.get_books(pair, precision, length) length = 50 if not length else length * 2 assert len(r) == length price = str(r[0][0]) if precision == 'P0': digits = len(price.split(".")) assert (digits == 1 or digits == 2) elif precision == 'P1': assert len(price) == 4 elif precision == 'P2': assert len(price) == 4 assert price[-1] == '0' elif precision == 'P3': assert len(price) == 4 assert price[-1] == '0' assert price[-2] == '0' elif precision == 'P4': assert len(price) == 4 assert price[-1] == '0' assert price[-2] == '0' assert price[-3] == '0' elif precision == 'R0': assert len(price == 11) @pytest.mark.parametrize('symbol, key, side, section, sort', [ ('fUSD', 'funding.size', 'long', 'hist', 0), ('fUSD', 'credits.size', 'long', 'hist', 0), ('fUSD', 'funding.size', 'long', 'last', 0), ('fUSD', 'funding.size', 'long', 'last', 1), ('fUSD', 'credits.size', 'long', 'last', 1), pytest.param(None, None, None, None, None, marks=pytest.mark.xfail) ]) def test_get_stats(self, client, symbol, key, side, section, sort): r = client.get_stats(symbol, key, side, section, sort) if section == 'hist': assert len(r) == 120 elif section == 'last': assert len(r) == 2 if sort == 1 and section == 'hist': assert r[0][0] <= r[1][0] elif sort != 1 and section == 'hist': assert r[0][0] >= r[1][0] @pytest.mark.parametrize('symbol, time_frame, section, limit, start, end, sort', [ ('tBTCUSD', '1m', 'hist', None, None, None, None), ('tBTCUSD', '15m', 'hist', 1, None, None, None), ('tBTCUSD', '15m', 'hist', 1, None, None, 1), ('tBTCUSD', '15m', 'hist', 1, 1514764800000, 1514765700000, 1), ('tBTCUSD', '15m', 'hist', 1, 1514764800000, 1514768400000, 1), ('tBTCUSD', '1m', 'last', None, None, None, None), ('tBTCUSD', '15m', 'last', 1, 1514764800000, 1514768400000, 1), ('tBTCUSD', '1m', 'last', 1, 1514768400000, 1514764800000, 1), pytest.param(None, None, None, None, None, None, None, marks=pytest.mark.xfail), pytest.param('tBTCUSD', '1m', 'hist', 1, 1514768400000, 1514764800000, 1, marks=pytest.mark.xfail) ]) def test_get_candles(self, client, symbol, time_frame, section, limit, start, end, sort): r = client.get_candles(symbol, time_frame, section, limit, start, end, sort) if section == 'hist' and limit != 1: assert len(r) == 120 elif section == 'hist' and limit == 1: assert len(r) == 1 elif section == 'last' and limit == 1: assert len(r) == 6 elif section == 'last' and limit == 1: assert len(r) == 1 if sort == 1 and section == 'hist' and limit != 1: assert r[0][0] <= r[1][0] elif sort != 1 and section == 'hist' and limit != 1: assert r[0][0] >= r[1][0]
true
true
f72a687a337167c96e7903a7bdd07f5ced99b8a8
3,743
py
Python
src/federatedid/federated.py
dawidkski/federated-faceid
95b1f4b7da0e8baf1cac35edf3b49528c650c491
[ "MIT" ]
1
2021-12-23T14:00:36.000Z
2021-12-23T14:00:36.000Z
src/federatedid/federated.py
dawidkski/federated-faceid
95b1f4b7da0e8baf1cac35edf3b49528c650c491
[ "MIT" ]
6
2021-01-12T13:40:31.000Z
2022-03-12T00:31:27.000Z
src/federatedid/federated.py
d-kicinski/federated-faceid
95b1f4b7da0e8baf1cac35edf3b49528c650c491
[ "MIT" ]
1
2020-05-12T03:11:07.000Z
2020-05-12T03:11:07.000Z
import copy from dataclasses import dataclass from typing import List, Optional import torch from torch.nn import CrossEntropyLoss, Module from torch.utils.data import DataLoader def federated_averaging(models: List[Module]) -> Module: global_model = copy.deepcopy(models[0]) global_weights = global_model.state_dict() local_weights = [m.state_dict() for m in models] for k in global_weights.keys(): for i in range(1, len(local_weights)): global_weights[k] += local_weights[i][k] global_weights[k] = torch.div(global_weights[k], len(local_weights)) global_model.load_state_dict(global_weights) return global_model class ModelAccumulator: def __init__(self): self.model_counter: int = 0 self.global_model = None self.global_weights = None def update(self, model): local_weights = model.state_dict() if self.global_model is None: self.global_model = model self.global_weights = local_weights self.model_counter += 1 else: for k in self.global_weights.keys(): self.global_weights[k] += local_weights[k] self.model_counter += 1 def get(self): for k in self.global_weights.keys(): self.global_weights[k] = torch.div( self.global_weights[k], self.model_counter ) self.global_model.load_state_dict(self.global_weights) return self.global_model def reset(self): self.global_model = None self.global_weights = None self.model_counter = 0 @dataclass class EdgeDeviceSettings: batch_size: int epochs: int learning_rate: float learning_rate_decay: float device: str @dataclass class TrainingResult: loss: float steps: int learning_rate: float class EdgeDevice: def __init__( self, device_id: int, settings: EdgeDeviceSettings, data_loader: DataLoader ): self.device_id = device_id self._data_loader = data_loader self.setting = copy.deepcopy(settings) self._loss_func = CrossEntropyLoss() self._model: Optional[Module] = None def download(self, model: Module): self._model = copy.deepcopy(model) def upload(self) -> Module: if self._model is not None: return copy.deepcopy(self._model) else: raise ValueError("Model not found on this device!") def train(self) -> TrainingResult: if self._data_loader is None: raise ValueError("Dataset not found on this device!") self._model.train() self.setting.learning_rate = ( self.setting.learning_rate * self.setting.learning_rate_decay ) optimizer = torch.optim.SGD( params=self._model.parameters(), lr=self.setting.learning_rate ) epoch_loss = [] local_steps: int = 0 for _ in range(self.setting.epochs): batch_loss = [] for i_batch, (images, labels) in enumerate(self._data_loader): self._model.zero_grad() images = images.to(self.setting.device) labels = labels.to(self.setting.device) logits = self._model(images) loss = self._loss_func(logits, labels) loss.backward() optimizer.step() local_steps += 1 batch_loss.append(loss.item()) epoch_loss.append(sum(batch_loss) / len(batch_loss)) mean_loss = sum(epoch_loss) / len(epoch_loss) return TrainingResult( loss=mean_loss, steps=local_steps, learning_rate=self.setting.learning_rate )
29.944
87
0.627304
import copy from dataclasses import dataclass from typing import List, Optional import torch from torch.nn import CrossEntropyLoss, Module from torch.utils.data import DataLoader def federated_averaging(models: List[Module]) -> Module: global_model = copy.deepcopy(models[0]) global_weights = global_model.state_dict() local_weights = [m.state_dict() for m in models] for k in global_weights.keys(): for i in range(1, len(local_weights)): global_weights[k] += local_weights[i][k] global_weights[k] = torch.div(global_weights[k], len(local_weights)) global_model.load_state_dict(global_weights) return global_model class ModelAccumulator: def __init__(self): self.model_counter: int = 0 self.global_model = None self.global_weights = None def update(self, model): local_weights = model.state_dict() if self.global_model is None: self.global_model = model self.global_weights = local_weights self.model_counter += 1 else: for k in self.global_weights.keys(): self.global_weights[k] += local_weights[k] self.model_counter += 1 def get(self): for k in self.global_weights.keys(): self.global_weights[k] = torch.div( self.global_weights[k], self.model_counter ) self.global_model.load_state_dict(self.global_weights) return self.global_model def reset(self): self.global_model = None self.global_weights = None self.model_counter = 0 @dataclass class EdgeDeviceSettings: batch_size: int epochs: int learning_rate: float learning_rate_decay: float device: str @dataclass class TrainingResult: loss: float steps: int learning_rate: float class EdgeDevice: def __init__( self, device_id: int, settings: EdgeDeviceSettings, data_loader: DataLoader ): self.device_id = device_id self._data_loader = data_loader self.setting = copy.deepcopy(settings) self._loss_func = CrossEntropyLoss() self._model: Optional[Module] = None def download(self, model: Module): self._model = copy.deepcopy(model) def upload(self) -> Module: if self._model is not None: return copy.deepcopy(self._model) else: raise ValueError("Model not found on this device!") def train(self) -> TrainingResult: if self._data_loader is None: raise ValueError("Dataset not found on this device!") self._model.train() self.setting.learning_rate = ( self.setting.learning_rate * self.setting.learning_rate_decay ) optimizer = torch.optim.SGD( params=self._model.parameters(), lr=self.setting.learning_rate ) epoch_loss = [] local_steps: int = 0 for _ in range(self.setting.epochs): batch_loss = [] for i_batch, (images, labels) in enumerate(self._data_loader): self._model.zero_grad() images = images.to(self.setting.device) labels = labels.to(self.setting.device) logits = self._model(images) loss = self._loss_func(logits, labels) loss.backward() optimizer.step() local_steps += 1 batch_loss.append(loss.item()) epoch_loss.append(sum(batch_loss) / len(batch_loss)) mean_loss = sum(epoch_loss) / len(epoch_loss) return TrainingResult( loss=mean_loss, steps=local_steps, learning_rate=self.setting.learning_rate )
true
true
f72a688feda53838c2dd09e2907fbb42d5bc0c1c
1,667
py
Python
tests/bugs/core_3474_test.py
reevespaul/firebird-qa
98f16f425aa9ab8ee63b86172f959d63a2d76f21
[ "MIT" ]
null
null
null
tests/bugs/core_3474_test.py
reevespaul/firebird-qa
98f16f425aa9ab8ee63b86172f959d63a2d76f21
[ "MIT" ]
null
null
null
tests/bugs/core_3474_test.py
reevespaul/firebird-qa
98f16f425aa9ab8ee63b86172f959d63a2d76f21
[ "MIT" ]
null
null
null
#coding:utf-8 # # id: bugs.core_3474 # title: Regression in joins on procedures # decription: # tracker_id: CORE-3474 # min_versions: ['2.5.0'] # versions: 3.0 # qmid: None import pytest from firebird.qa import db_factory, isql_act, Action # version: 3.0 # resources: None substitutions_1 = [('-At line.*', '')] init_script_1 = """""" db_1 = db_factory(from_backup='employee-ods12.fbk', init=init_script_1) test_script_1 = """ set list on; select e.emp_no emp_1, e.last_name name_1, p.proj_name proj_1 from employee e left join ( get_emp_proj(e.emp_no) proc join project p on p.proj_id = proc.proj_id ) on 1=1 order by 1,2,3 rows 1; select e.emp_no emp_2, e.last_name name_2, p.proj_name proj_2 from ( employee e left join get_emp_proj(e.emp_no) proc on 1=1 ) left join project p on p.proj_id = proc.proj_id order by 1,2,3 rows 1; """ act_1 = isql_act('db_1', test_script_1, substitutions=substitutions_1) expected_stdout_1 = """ EMP_2 2 NAME_2 Nelson PROJ_2 <null> """ expected_stderr_1 = """ Statement failed, SQLSTATE = 42S22 Dynamic SQL Error -SQL error code = -206 -Column unknown -E.EMP_NO """ @pytest.mark.version('>=3.0') def test_1(act_1: Action): act_1.expected_stdout = expected_stdout_1 act_1.expected_stderr = expected_stderr_1 act_1.execute() assert act_1.clean_expected_stderr == act_1.clean_stderr assert act_1.clean_expected_stdout == act_1.clean_stdout
24.514706
71
0.617277
import pytest from firebird.qa import db_factory, isql_act, Action substitutions_1 = [('-At line.*', '')] init_script_1 = """""" db_1 = db_factory(from_backup='employee-ods12.fbk', init=init_script_1) test_script_1 = """ set list on; select e.emp_no emp_1, e.last_name name_1, p.proj_name proj_1 from employee e left join ( get_emp_proj(e.emp_no) proc join project p on p.proj_id = proc.proj_id ) on 1=1 order by 1,2,3 rows 1; select e.emp_no emp_2, e.last_name name_2, p.proj_name proj_2 from ( employee e left join get_emp_proj(e.emp_no) proc on 1=1 ) left join project p on p.proj_id = proc.proj_id order by 1,2,3 rows 1; """ act_1 = isql_act('db_1', test_script_1, substitutions=substitutions_1) expected_stdout_1 = """ EMP_2 2 NAME_2 Nelson PROJ_2 <null> """ expected_stderr_1 = """ Statement failed, SQLSTATE = 42S22 Dynamic SQL Error -SQL error code = -206 -Column unknown -E.EMP_NO """ @pytest.mark.version('>=3.0') def test_1(act_1: Action): act_1.expected_stdout = expected_stdout_1 act_1.expected_stderr = expected_stderr_1 act_1.execute() assert act_1.clean_expected_stderr == act_1.clean_stderr assert act_1.clean_expected_stdout == act_1.clean_stdout
true
true
f72a6990f0aad8249f5dc016a2590edf77f57c03
4,224
py
Python
mainapp/controllers/forms.py
fabiocostapro/fiberappz
da73569fa03e0b731b5ec2c96a0ee668f8b10ef6
[ "MIT" ]
null
null
null
mainapp/controllers/forms.py
fabiocostapro/fiberappz
da73569fa03e0b731b5ec2c96a0ee668f8b10ef6
[ "MIT" ]
null
null
null
mainapp/controllers/forms.py
fabiocostapro/fiberappz
da73569fa03e0b731b5ec2c96a0ee668f8b10ef6
[ "MIT" ]
null
null
null
from wtforms import Form from wtforms import StringField, PasswordField from wtforms.fields.html5 import EmailField from wtforms import validators from mainapp.models.tables import User class UserCreateForm(Form): username = StringField("Usuário", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=4, max=25, message="Mínimo de 4 e máximo de 25 caracteres") ]) name = StringField("Nome", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=4, max=25, message="Mínimo de 4 e máximo de 25 caracteres") ]) cpf = StringField("Cpf", [ ]) company = StringField("Company", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=4, max=25, message="Mínimo de 4 e máximo de 25 caracteres") ]) cnpj = StringField("Cnpj", [ ]) email = EmailField("E-mail", [ validators.Required(message="Preenchimento obrigatório"), validators.Email(message="Preenchimento inválido") ]) password = PasswordField("Senha", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=6, max=15, message="Mínimo de 6 e máximo de 15 caracteres") ]) def validate_username(form, field): username = field.data user = User.query.filter_by(username=username).first() if user is not None: raise validators.ValidationError("Usuário já cadastrado!") class OltCreateForm(Form): name = StringField("Nome", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=4, max=25, message="Mínimo de 4 e máximo de 25 caracteres") ]) ip = StringField("Ip", [ ]) port = StringField("Porta", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=3, max=5, message="Mínimo de 3 e máximo de 5 caracteres") ]) login = StringField("Login", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=4, max=25, message="Mínimo de 4 e máximo de 25 caracteres") ]) password = StringField("Senha", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=4, max=25, message="Mínimo de 4 e máximo de 25 caracteres") ]) class UserReadForm(Form): username = StringField("Usuário", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=4, max=25, message="Mínimo de 4 e máximo de 25 caracteres") ]) class LoginForm(Form): username = StringField("Usuário", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=4, max=25, message="Mínimo de 4 e máximo de 25 caracteres") ]) password = PasswordField("Senha", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=6, max=15, message="Mínimo de 6 e máximo de 15 caracteres") ])
45.419355
114
0.482244
from wtforms import Form from wtforms import StringField, PasswordField from wtforms.fields.html5 import EmailField from wtforms import validators from mainapp.models.tables import User class UserCreateForm(Form): username = StringField("Usuário", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=4, max=25, message="Mínimo de 4 e máximo de 25 caracteres") ]) name = StringField("Nome", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=4, max=25, message="Mínimo de 4 e máximo de 25 caracteres") ]) cpf = StringField("Cpf", [ ]) company = StringField("Company", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=4, max=25, message="Mínimo de 4 e máximo de 25 caracteres") ]) cnpj = StringField("Cnpj", [ ]) email = EmailField("E-mail", [ validators.Required(message="Preenchimento obrigatório"), validators.Email(message="Preenchimento inválido") ]) password = PasswordField("Senha", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=6, max=15, message="Mínimo de 6 e máximo de 15 caracteres") ]) def validate_username(form, field): username = field.data user = User.query.filter_by(username=username).first() if user is not None: raise validators.ValidationError("Usuário já cadastrado!") class OltCreateForm(Form): name = StringField("Nome", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=4, max=25, message="Mínimo de 4 e máximo de 25 caracteres") ]) ip = StringField("Ip", [ ]) port = StringField("Porta", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=3, max=5, message="Mínimo de 3 e máximo de 5 caracteres") ]) login = StringField("Login", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=4, max=25, message="Mínimo de 4 e máximo de 25 caracteres") ]) password = StringField("Senha", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=4, max=25, message="Mínimo de 4 e máximo de 25 caracteres") ]) class UserReadForm(Form): username = StringField("Usuário", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=4, max=25, message="Mínimo de 4 e máximo de 25 caracteres") ]) class LoginForm(Form): username = StringField("Usuário", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=4, max=25, message="Mínimo de 4 e máximo de 25 caracteres") ]) password = PasswordField("Senha", [ validators.Required(message="Preenchimento obrigatório"), validators.length(min=6, max=15, message="Mínimo de 6 e máximo de 15 caracteres") ])
true
true
f72a6add468392d9b7eca586307a71cb8213bc22
10,197
py
Python
api/team/tests/test_update.py
BerniWittmann/beachanmeldung
9014dea5c31ea9e26f18d753d8d836741865c38e
[ "Unlicense", "MIT" ]
null
null
null
api/team/tests/test_update.py
BerniWittmann/beachanmeldung
9014dea5c31ea9e26f18d753d8d836741865c38e
[ "Unlicense", "MIT" ]
5
2020-06-05T17:31:08.000Z
2022-03-11T23:16:12.000Z
api/team/tests/test_update.py
BerniWittmann/beachanmeldung
9014dea5c31ea9e26f18d753d8d836741865c38e
[ "Unlicense", "MIT" ]
null
null
null
import json from django.core.urlresolvers import reverse from django.test import TestCase from django.utils import timezone from django.utils.translation import activate from rest_framework.test import APIClient from rest_framework_jwt.settings import api_settings from api.accounts.models import MyUser from api.team.models import Team from api.tournaments.models import Tournament activate('en-us') jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER token_regex = '^[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+/=]*$' class Teams(TestCase): token = None tournament = None team = None user = None def setUp(self): self.user = MyUser.objects.create_user(email='test@byom.de', first_name='Test', last_name='User', phone='+49192481024') self.user.set_password('test123') self.user.is_verified = True self.user.is_staff = True self.user.save() payload = jwt_payload_handler(self.user) self.token = jwt_encode_handler(payload) self.tournament = Tournament.objects \ .create(name='Test Turnier', gender='mixed', start_date='2017-01-01', end_date='2017-01-02', deadline_signup='2017-01-01T00:00:00Z', deadline_edit=timezone.now() + timezone.timedelta(days=30), advertisement_url='http://www.google.de', contact_email='test@byom.de', starting_fee=60.0, number_of_places=12 ) self.team = Team.objects.create( name='TSV Ismaning', beachname='THC Eh Drin!', tournament=self.tournament, trainer=self.user, ) def test_team_update(self): client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + self.token) response = client.put(reverse('v1:team-detail', kwargs={'pk': self.team.id}), { 'name': 'TSV Ismaning 2', 'beachname': 'New Name Name', }) data = json.loads(response.content.decode('utf-8')) self.assertEqual(response.status_code, 200) self.assertEqual(data['beachname'], 'New Name Name') self.assertEqual(Team.objects.first().beachname, 'New Name Name') self.assertEqual(data['name'], 'TSV Ismaning 2') self.assertEqual(Team.objects.first().name, 'TSV Ismaning 2') def test_team_update_as_other_trainer(self): other_user = MyUser.objects.create_user(email='newuser@byom.de', first_name='Another', last_name='User', phone='+49192481024') other_user.set_password('test123') other_user.is_verified = True other_user.is_staff = False other_user.save() other_payload = jwt_payload_handler(other_user) other_token = jwt_encode_handler(other_payload) client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + other_token) response = client.put(reverse('v1:team-detail', kwargs={'pk': self.team.id}), { 'beachname': 'Bad Name', 'name': 'TSV Ismaning', }) self.assertEqual(response.status_code, 403) def test_team_update_not_update_tournament(self): client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + self.token) response = client.put(reverse('v1:team-detail', kwargs={'pk': self.team.id}), { 'beachname': 'THC Eh Drin!', 'name': 'TSV Ismaning', 'tournament': 3, }) data = json.loads(response.content.decode('utf-8')) self.assertEqual(response.status_code, 200) self.assertEqual(data['tournament']['id'], self.tournament.id) self.assertEqual(Team.objects.first().tournament, self.tournament) def test_team_update_not_update_trainer(self): client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + self.token) response = client.put(reverse('v1:team-detail', kwargs={'pk': self.team.id}), { 'beachname': 'THC Eh Drin!', 'name': 'TSV Ismaning', 'trainer': 'hacker@dumb.com', }) self.assertEqual(response.status_code, 200) self.assertEqual(Team.objects.first().trainer, self.user) def test_team_update_not_update_paid(self): client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + self.token) response = client.put(reverse('v1:team-detail', kwargs={'pk': self.team.id}), { 'beachname': 'THC Eh Drin!', 'name': 'TSV Ismaning', 'paid': True, }) self.assertEqual(response.status_code, 200) self.assertEqual(Team.objects.first().paid, False) def test_team_update_not_update_state(self): client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + self.token) response = client.put(reverse('v1:team-detail', kwargs={'pk': self.team.id}), { 'beachname': 'THC Eh Drin!', 'name': 'TSV Ismaning', 'state': 'signed up', }) self.assertEqual(response.status_code, 200) self.assertEqual(Team.objects.first().state, 'needs approval') def test_team_name_not_unqiue(self): team2 = Team.objects.create( name='TSV Ismaning 2', beachname='THC Eh Drin! 2', tournament=self.tournament, trainer=self.user, ) client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + self.token) response = client.put(reverse('v1:team-detail', kwargs={'pk': team2.id}), { 'name': 'TSV Ismaning', 'beachname': 'THC Eh Drin!' }) data = json.loads(response.content.decode('utf-8')) self.assertEqual(response.status_code, 400) self.assertDictEqual(data, { 'detail': ['Name already taken'], 'key': ['name_already_taken'] }) self.assertEqual(Team.objects.last().name, team2.name) self.assertEqual(Team.objects.last().beachname, team2.beachname) def test_team_name_not_unqiue_without_beachname(self): team2 = Team.objects.create( name='TSV Ismaning 2', beachname='THC Eh Drin! 2', tournament=self.tournament, trainer=self.user, ) client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + self.token) response = client.put(reverse('v1:team-detail', kwargs={'pk': team2.id}), { 'name': 'TSV Ismaning', }) data = json.loads(response.content.decode('utf-8')) self.assertEqual(response.status_code, 400) self.assertDictEqual(data, { 'detail': ['Name already taken'], 'key': ['name_already_taken'] }) self.assertEqual(Team.objects.last().name, team2.name) self.assertEqual(Team.objects.last().beachname, team2.beachname) def test_team_update_after_deadline_staff(self): self.tournament.deadline_edit = timezone.now() - timezone.timedelta(days=3) self.tournament.save() client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + self.token) response = client.put(reverse('v1:team-detail', kwargs={'pk': self.team.id}), { 'name': 'TSV Ismaning 2', 'beachname': 'New Name Name', }) data = json.loads(response.content.decode('utf-8')) self.assertEqual(response.status_code, 200) self.assertEqual(data['beachname'], 'New Name Name') self.assertEqual(Team.objects.first().beachname, 'New Name Name') self.assertEqual(data['name'], 'TSV Ismaning 2') self.assertEqual(Team.objects.first().name, 'TSV Ismaning 2') def test_team_update_after_deadline_trainer(self): self.tournament.deadline_edit = timezone.now() - timezone.timedelta(days=3) self.tournament.save() self.user.is_staff = False self.user.save() client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + self.token) response = client.put(reverse('v1:team-detail', kwargs={'pk': self.team.id}), { 'name': 'TSV Ismaning 2', 'beachname': 'New Name Name', }) data = json.loads(response.content.decode('utf-8')) self.assertEqual(response.status_code, 400) self.assertDictEqual(data, { 'detail': 'Team Update not possible after Edit-Deadline', 'key': 'after_deadline_edit', }) self.assertNotEqual(Team.objects.first().beachname, 'New Name Name') self.assertNotEqual(Team.objects.first().name, 'TSV Ismaning 2')
44.142857
83
0.531529
import json from django.core.urlresolvers import reverse from django.test import TestCase from django.utils import timezone from django.utils.translation import activate from rest_framework.test import APIClient from rest_framework_jwt.settings import api_settings from api.accounts.models import MyUser from api.team.models import Team from api.tournaments.models import Tournament activate('en-us') jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER token_regex = '^[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+/=]*$' class Teams(TestCase): token = None tournament = None team = None user = None def setUp(self): self.user = MyUser.objects.create_user(email='test@byom.de', first_name='Test', last_name='User', phone='+49192481024') self.user.set_password('test123') self.user.is_verified = True self.user.is_staff = True self.user.save() payload = jwt_payload_handler(self.user) self.token = jwt_encode_handler(payload) self.tournament = Tournament.objects \ .create(name='Test Turnier', gender='mixed', start_date='2017-01-01', end_date='2017-01-02', deadline_signup='2017-01-01T00:00:00Z', deadline_edit=timezone.now() + timezone.timedelta(days=30), advertisement_url='http://www.google.de', contact_email='test@byom.de', starting_fee=60.0, number_of_places=12 ) self.team = Team.objects.create( name='TSV Ismaning', beachname='THC Eh Drin!', tournament=self.tournament, trainer=self.user, ) def test_team_update(self): client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + self.token) response = client.put(reverse('v1:team-detail', kwargs={'pk': self.team.id}), { 'name': 'TSV Ismaning 2', 'beachname': 'New Name Name', }) data = json.loads(response.content.decode('utf-8')) self.assertEqual(response.status_code, 200) self.assertEqual(data['beachname'], 'New Name Name') self.assertEqual(Team.objects.first().beachname, 'New Name Name') self.assertEqual(data['name'], 'TSV Ismaning 2') self.assertEqual(Team.objects.first().name, 'TSV Ismaning 2') def test_team_update_as_other_trainer(self): other_user = MyUser.objects.create_user(email='newuser@byom.de', first_name='Another', last_name='User', phone='+49192481024') other_user.set_password('test123') other_user.is_verified = True other_user.is_staff = False other_user.save() other_payload = jwt_payload_handler(other_user) other_token = jwt_encode_handler(other_payload) client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + other_token) response = client.put(reverse('v1:team-detail', kwargs={'pk': self.team.id}), { 'beachname': 'Bad Name', 'name': 'TSV Ismaning', }) self.assertEqual(response.status_code, 403) def test_team_update_not_update_tournament(self): client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + self.token) response = client.put(reverse('v1:team-detail', kwargs={'pk': self.team.id}), { 'beachname': 'THC Eh Drin!', 'name': 'TSV Ismaning', 'tournament': 3, }) data = json.loads(response.content.decode('utf-8')) self.assertEqual(response.status_code, 200) self.assertEqual(data['tournament']['id'], self.tournament.id) self.assertEqual(Team.objects.first().tournament, self.tournament) def test_team_update_not_update_trainer(self): client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + self.token) response = client.put(reverse('v1:team-detail', kwargs={'pk': self.team.id}), { 'beachname': 'THC Eh Drin!', 'name': 'TSV Ismaning', 'trainer': 'hacker@dumb.com', }) self.assertEqual(response.status_code, 200) self.assertEqual(Team.objects.first().trainer, self.user) def test_team_update_not_update_paid(self): client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + self.token) response = client.put(reverse('v1:team-detail', kwargs={'pk': self.team.id}), { 'beachname': 'THC Eh Drin!', 'name': 'TSV Ismaning', 'paid': True, }) self.assertEqual(response.status_code, 200) self.assertEqual(Team.objects.first().paid, False) def test_team_update_not_update_state(self): client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + self.token) response = client.put(reverse('v1:team-detail', kwargs={'pk': self.team.id}), { 'beachname': 'THC Eh Drin!', 'name': 'TSV Ismaning', 'state': 'signed up', }) self.assertEqual(response.status_code, 200) self.assertEqual(Team.objects.first().state, 'needs approval') def test_team_name_not_unqiue(self): team2 = Team.objects.create( name='TSV Ismaning 2', beachname='THC Eh Drin! 2', tournament=self.tournament, trainer=self.user, ) client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + self.token) response = client.put(reverse('v1:team-detail', kwargs={'pk': team2.id}), { 'name': 'TSV Ismaning', 'beachname': 'THC Eh Drin!' }) data = json.loads(response.content.decode('utf-8')) self.assertEqual(response.status_code, 400) self.assertDictEqual(data, { 'detail': ['Name already taken'], 'key': ['name_already_taken'] }) self.assertEqual(Team.objects.last().name, team2.name) self.assertEqual(Team.objects.last().beachname, team2.beachname) def test_team_name_not_unqiue_without_beachname(self): team2 = Team.objects.create( name='TSV Ismaning 2', beachname='THC Eh Drin! 2', tournament=self.tournament, trainer=self.user, ) client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + self.token) response = client.put(reverse('v1:team-detail', kwargs={'pk': team2.id}), { 'name': 'TSV Ismaning', }) data = json.loads(response.content.decode('utf-8')) self.assertEqual(response.status_code, 400) self.assertDictEqual(data, { 'detail': ['Name already taken'], 'key': ['name_already_taken'] }) self.assertEqual(Team.objects.last().name, team2.name) self.assertEqual(Team.objects.last().beachname, team2.beachname) def test_team_update_after_deadline_staff(self): self.tournament.deadline_edit = timezone.now() - timezone.timedelta(days=3) self.tournament.save() client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + self.token) response = client.put(reverse('v1:team-detail', kwargs={'pk': self.team.id}), { 'name': 'TSV Ismaning 2', 'beachname': 'New Name Name', }) data = json.loads(response.content.decode('utf-8')) self.assertEqual(response.status_code, 200) self.assertEqual(data['beachname'], 'New Name Name') self.assertEqual(Team.objects.first().beachname, 'New Name Name') self.assertEqual(data['name'], 'TSV Ismaning 2') self.assertEqual(Team.objects.first().name, 'TSV Ismaning 2') def test_team_update_after_deadline_trainer(self): self.tournament.deadline_edit = timezone.now() - timezone.timedelta(days=3) self.tournament.save() self.user.is_staff = False self.user.save() client = APIClient() client.credentials(HTTP_AUTHORIZATION='JWT ' + self.token) response = client.put(reverse('v1:team-detail', kwargs={'pk': self.team.id}), { 'name': 'TSV Ismaning 2', 'beachname': 'New Name Name', }) data = json.loads(response.content.decode('utf-8')) self.assertEqual(response.status_code, 400) self.assertDictEqual(data, { 'detail': 'Team Update not possible after Edit-Deadline', 'key': 'after_deadline_edit', }) self.assertNotEqual(Team.objects.first().beachname, 'New Name Name') self.assertNotEqual(Team.objects.first().name, 'TSV Ismaning 2')
true
true
f72a6bc23ff8f5945f5bfef16d9ffa3a49b4878d
2,563
py
Python
setup.py
ianhuang0630/CSQ
5f1fe99a8d9da73692643b3911d675dce269a03d
[ "MIT" ]
98
2019-04-05T08:22:38.000Z
2022-03-29T06:22:17.000Z
setup.py
ianhuang0630/CSQ
5f1fe99a8d9da73692643b3911d675dce269a03d
[ "MIT" ]
19
2019-06-28T20:26:01.000Z
2022-03-03T16:26:57.000Z
setup.py
ianhuang0630/CSQ
5f1fe99a8d9da73692643b3911d675dce269a03d
[ "MIT" ]
26
2019-04-15T00:54:06.000Z
2022-02-22T23:17:24.000Z
"""Setup learnable_primitives""" from distutils.core import setup from Cython.Build import cythonize from distutils.extension import Extension from itertools import dropwhile import numpy as np from os import path def collect_docstring(lines): """Return document docstring if it exists""" lines = dropwhile(lambda x: not x.startswith('"""'), lines) doc = "" for line in lines: doc += line if doc.endswith('"""\n'): break return doc[3:-4].replace("\r", "").replace("\n", " ") def collect_metadata(): meta = {} with open(path.join("learnable_primitives", "__init__.py")) as f: lines = iter(f) meta["description"] = collect_docstring(lines) for line in lines: if line.startswith("__"): key, value = map(lambda x: x.strip(), line.split("=")) meta[key[2:-2]] = value[1:-1] return meta def get_extensions(): return cythonize([ Extension( "learnable_primitives.fast_sampler._sampler", [ "learnable_primitives/fast_sampler/_sampler.pyx", "learnable_primitives/fast_sampler/sampling.cpp" ], language="c++11", libraries=["stdc++"], include_dirs=[np.get_include()], extra_compile_args=["-std=c++11", "-O3"] ) ]) def get_install_requirements(): return [ "numpy", "scikit-learn", "trimesh==2.38.42", "torch==0.4.1", "torchvision==0.1.8", "progress==1.4", "cython", "Pillow", "pyquaternion", "backports.functools_lru_cache", "sympy", "matplotlib==2.2.4", "seaborn", "mayavi" ] def setup_package(): meta = collect_metadata() setup( name="learnable_primitives", version=meta["version"], maintainer=meta["maintainer"], maintainer_email=meta["email"], url=meta["url"], license=meta["license"], classifiers=[ "Intended Audience :: Science/Research", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Topic :: Scientific/Engineering", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", ], install_requires=get_install_requirements(), ext_modules=get_extensions() ) if __name__ == "__main__": setup_package()
26.42268
70
0.55833
from distutils.core import setup from Cython.Build import cythonize from distutils.extension import Extension from itertools import dropwhile import numpy as np from os import path def collect_docstring(lines): lines = dropwhile(lambda x: not x.startswith('"""'), lines) doc = "" for line in lines: doc += line if doc.endswith('"""\n'): break return doc[3:-4].replace("\r", "").replace("\n", " ") def collect_metadata(): meta = {} with open(path.join("learnable_primitives", "__init__.py")) as f: lines = iter(f) meta["description"] = collect_docstring(lines) for line in lines: if line.startswith("__"): key, value = map(lambda x: x.strip(), line.split("=")) meta[key[2:-2]] = value[1:-1] return meta def get_extensions(): return cythonize([ Extension( "learnable_primitives.fast_sampler._sampler", [ "learnable_primitives/fast_sampler/_sampler.pyx", "learnable_primitives/fast_sampler/sampling.cpp" ], language="c++11", libraries=["stdc++"], include_dirs=[np.get_include()], extra_compile_args=["-std=c++11", "-O3"] ) ]) def get_install_requirements(): return [ "numpy", "scikit-learn", "trimesh==2.38.42", "torch==0.4.1", "torchvision==0.1.8", "progress==1.4", "cython", "Pillow", "pyquaternion", "backports.functools_lru_cache", "sympy", "matplotlib==2.2.4", "seaborn", "mayavi" ] def setup_package(): meta = collect_metadata() setup( name="learnable_primitives", version=meta["version"], maintainer=meta["maintainer"], maintainer_email=meta["email"], url=meta["url"], license=meta["license"], classifiers=[ "Intended Audience :: Science/Research", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Topic :: Scientific/Engineering", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", ], install_requires=get_install_requirements(), ext_modules=get_extensions() ) if __name__ == "__main__": setup_package()
true
true
f72a6c18f2dd71bf7e6d4454aa80d63e9fbe8e63
522
py
Python
Season 06 - Files in Python/Episode 12 - Imports Error & running as Python Scripts/Episode 12 - Imports Error & running as Python Scripts.py
Pythobit/Python-tutorial
b0743eaa9c237c3578131ead1b3f2c295f11b7ee
[ "MIT" ]
3
2021-02-19T18:33:00.000Z
2021-08-03T14:56:50.000Z
Season 06 - Files in Python/Episode 12 - Imports Error & running as Python Scripts/Episode 12 - Imports Error & running as Python Scripts.py
barawalojas/Python-tutorial
3f4b2b073e421888b3d62ff634658317d9abcb9b
[ "MIT" ]
1
2021-07-10T14:37:57.000Z
2021-07-20T09:51:39.000Z
Season 06 - Files in Python/Episode 12 - Imports Error & running as Python Scripts/Episode 12 - Imports Error & running as Python Scripts.py
barawalojas/Python-tutorial
3f4b2b073e421888b3d62ff634658317d9abcb9b
[ "MIT" ]
1
2021-08-02T05:39:38.000Z
2021-08-02T05:39:38.000Z
# Imports Error & running as Python Scripts. """ IMPORT ERROR if your module is already imported, you can import it the same way, but if you want to access something inside in it, python will look into the module & give you an error because it's going to be back n forth, called `circular import` [bad thing] """ """ RUNNING AS PYTHON SCRIPTS if you want to run a specific code when you run a specific file, do this if __name__ = '__main__': print(find_in(['Rolf', 'Jose', 'Jen'], lambda x: x, 'Jose')) """
26.1
117
0.701149
true
true
f72a6cb5cc483a8ad619bf7be7299edfe87310a0
592
py
Python
testing/test_is_infected.py
GalBenZvi/EpidemicSimulation
7aa551e18ad27e977a73452e708026ea85804a21
[ "MIT" ]
1
2020-07-15T07:11:55.000Z
2020-07-15T07:11:55.000Z
testing/test_is_infected.py
Hershkovitz-hub/EpidemicSimulation
7aa551e18ad27e977a73452e708026ea85804a21
[ "MIT" ]
2
2021-06-08T22:07:26.000Z
2021-09-08T02:22:40.000Z
testing/test_is_infected.py
GalBenZvi/EpidemicSimulation
7aa551e18ad27e977a73452e708026ea85804a21
[ "MIT" ]
null
null
null
from epidemic_simulation.simulation import SimulationManager import pytest @pytest.fixture def test_data(): test_calc=SimulationManager([],{'infection_r':100,'infection_p':0.99,'sickness_duration':6}) return test_calc def test_infection_prob_between_0_1(test_data): """ infection_prob must be between 0 and 1 """ try: test_data.infection_prob=-0.5 test_data.is_infected() except ValueError: try: test_data.infection_prob=1.5 test_data.is_infected() except ValueError: return True return False
26.909091
96
0.682432
from epidemic_simulation.simulation import SimulationManager import pytest @pytest.fixture def test_data(): test_calc=SimulationManager([],{'infection_r':100,'infection_p':0.99,'sickness_duration':6}) return test_calc def test_infection_prob_between_0_1(test_data): try: test_data.infection_prob=-0.5 test_data.is_infected() except ValueError: try: test_data.infection_prob=1.5 test_data.is_infected() except ValueError: return True return False
true
true
f72a6dcb2a0ebf8ec3765416a9db9ad3c3e0ae5e
1,253
py
Python
src/lm/metrics.py
source-data/soda-roberta
28f23ae68a1bb17c9844815a7c36d4c590e8c3d0
[ "MIT" ]
3
2021-04-23T05:06:23.000Z
2021-09-03T21:10:25.000Z
src/lm/metrics.py
source-data/soda-roberta
28f23ae68a1bb17c9844815a7c36d4c590e8c3d0
[ "MIT" ]
1
2021-12-14T15:21:16.000Z
2021-12-14T15:21:16.000Z
src/lm/metrics.py
source-data/soda-roberta
28f23ae68a1bb17c9844815a7c36d4c590e8c3d0
[ "MIT" ]
1
2022-03-29T08:03:25.000Z
2022-03-29T08:03:25.000Z
from transformers import EvalPrediction from sklearn.metrics import precision_recall_fscore_support import numpy as np def compute_metrics(pred: EvalPrediction): """Compute recall at the masked position """ mask = pred.label_ids != -100 # filter everything except the masked position and flatten tensors labels = pred.label_ids[mask].flatten() preds = pred.predictions[mask].flatten() _, recall, _, _ = precision_recall_fscore_support(y_true=labels, y_pred=preds, average='micro') return {'recall': recall} def self_test(): pred = EvalPrediction( label_ids=np.array([ [-100, 1, -100], [ 2, -100, -100], [-100, -100, 3], [-100, -100, 4] ]), predictions=np.array([ [-100, 1, -100], # 1 true positive [ 2, -100, -100], # 1 true positive [ 2, 6, 8], # 1 false positive, irrelevant pos will be ignored [ 1, 7, 4] # 1 true positive, irrelevant pos will be ignored ]) ) m = compute_metrics(pred) print(f"recall={m['recall']}") assert m['recall'] == 0.75 print("Looks like it is working!") if __name__ == "__main__": self_test()
31.325
99
0.581006
from transformers import EvalPrediction from sklearn.metrics import precision_recall_fscore_support import numpy as np def compute_metrics(pred: EvalPrediction): mask = pred.label_ids != -100 labels = pred.label_ids[mask].flatten() preds = pred.predictions[mask].flatten() _, recall, _, _ = precision_recall_fscore_support(y_true=labels, y_pred=preds, average='micro') return {'recall': recall} def self_test(): pred = EvalPrediction( label_ids=np.array([ [-100, 1, -100], [ 2, -100, -100], [-100, -100, 3], [-100, -100, 4] ]), predictions=np.array([ [-100, 1, -100], [ 2, -100, -100], [ 2, 6, 8], [ 1, 7, 4] ]) ) m = compute_metrics(pred) print(f"recall={m['recall']}") assert m['recall'] == 0.75 print("Looks like it is working!") if __name__ == "__main__": self_test()
true
true
f72a6ec3d3794ebec344131fa4c80510f1e78360
2,375
py
Python
VORDInstance.py
Daviddddl/i3d_pytorch
595172379bc669a30468119f629180141c2cbae2
[ "Apache-2.0" ]
3
2019-03-15T14:28:57.000Z
2020-06-18T04:00:46.000Z
VORDInstance.py
Daviddddl/i3d_pytorch
595172379bc669a30468119f629180141c2cbae2
[ "Apache-2.0" ]
1
2020-04-01T22:24:07.000Z
2020-04-01T22:24:07.000Z
VORDInstance.py
Daviddddl/I3D_pytorch
595172379bc669a30468119f629180141c2cbae2
[ "Apache-2.0" ]
null
null
null
class VORDInstance: def __init__(self, video_id, video_path, frame_count, fps, width, height, subject_objects, trajectories, relation_instances): self.video_id = video_id self.video_path = video_path self.frame_count = frame_count self.fps = fps self.height = height self.width = width self.subject_objects = subject_objects self.trajectories = trajectories self.relation_instances = relation_instances def __repr__(self): return "VORD Instance: video_id=" + str(self.video_id) def include_object(self, object_label): for each_so in self.subject_objects: if each_so['category'].lower() == object_label.lower(): return True return False def get_object_trajs(self, object_label): if self.include_object(object_label): trajs_list = [] for each_so in self.subject_objects: if object_label == each_so['category']: obj_tid = each_so['tid'] for each_traj in self.trajectories: for each_traj_obj in each_traj: if obj_tid == each_traj_obj['tid']: trajs_list.append(each_traj_obj) return trajs_list else: return None def get_object_relations_list(self): objects_list = [] relations_list = [] for each_so in self.subject_objects: objects_list.append(each_so['category']) for each_rel in self.relation_instances: relations_list.append(each_rel['predicate']) # print("Video " + str(self.video_id) + " has " # + str(len(objects_list)) + " objects and " + # str(len(relations_list)) + " relations.") return objects_list, relations_list def get_triplet_list(self): categorys = {} for each_os in self.subject_objects: categorys[each_os['tid']] = each_os['category'] triplet_list = [] for each_pred in self.relation_instances: each_trip = (categorys[each_pred['subject_tid']], each_pred['predicate'], categorys[each_pred['object_tid']]) triplet_list.append(each_trip) return triplet_list
36.538462
77
0.586105
class VORDInstance: def __init__(self, video_id, video_path, frame_count, fps, width, height, subject_objects, trajectories, relation_instances): self.video_id = video_id self.video_path = video_path self.frame_count = frame_count self.fps = fps self.height = height self.width = width self.subject_objects = subject_objects self.trajectories = trajectories self.relation_instances = relation_instances def __repr__(self): return "VORD Instance: video_id=" + str(self.video_id) def include_object(self, object_label): for each_so in self.subject_objects: if each_so['category'].lower() == object_label.lower(): return True return False def get_object_trajs(self, object_label): if self.include_object(object_label): trajs_list = [] for each_so in self.subject_objects: if object_label == each_so['category']: obj_tid = each_so['tid'] for each_traj in self.trajectories: for each_traj_obj in each_traj: if obj_tid == each_traj_obj['tid']: trajs_list.append(each_traj_obj) return trajs_list else: return None def get_object_relations_list(self): objects_list = [] relations_list = [] for each_so in self.subject_objects: objects_list.append(each_so['category']) for each_rel in self.relation_instances: relations_list.append(each_rel['predicate']) return objects_list, relations_list def get_triplet_list(self): categorys = {} for each_os in self.subject_objects: categorys[each_os['tid']] = each_os['category'] triplet_list = [] for each_pred in self.relation_instances: each_trip = (categorys[each_pred['subject_tid']], each_pred['predicate'], categorys[each_pred['object_tid']]) triplet_list.append(each_trip) return triplet_list
true
true
f72a6f1a0b1f6bc7143103cd94ad22fb05c13141
334
py
Python
school/extensions.py
leyyin/university-SE
7cc3625bda787d2e79ab22f30d6f6e732ca9abb3
[ "MIT" ]
3
2015-03-12T15:50:58.000Z
2015-05-04T12:55:19.000Z
school/extensions.py
leyyin/university-SE
7cc3625bda787d2e79ab22f30d6f6e732ca9abb3
[ "MIT" ]
2
2015-05-01T18:24:04.000Z
2015-05-15T15:58:47.000Z
school/extensions.py
leyyin/university-SE
7cc3625bda787d2e79ab22f30d6f6e732ca9abb3
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # init all the extensions instances from flask.ext.sqlalchemy import SQLAlchemy db = SQLAlchemy() from flask.ext.mail import Mail mail = Mail() from flask.ext.login import LoginManager login_manager = LoginManager() from flask_debugtoolbar import DebugToolbarExtension toolbar = DebugToolbarExtension()
18.555556
52
0.778443
from flask.ext.sqlalchemy import SQLAlchemy db = SQLAlchemy() from flask.ext.mail import Mail mail = Mail() from flask.ext.login import LoginManager login_manager = LoginManager() from flask_debugtoolbar import DebugToolbarExtension toolbar = DebugToolbarExtension()
true
true
f72a7184ee9e741944510976bfd4ac5d2d98ed14
9,090
py
Python
tectosaur/fmm/ts_terms.py
jlmaurer/tectosaur
7cc5606d814f061395b19754e7a4b6c5e4c236e5
[ "MIT" ]
17
2017-06-29T16:48:56.000Z
2021-10-03T18:31:41.000Z
tectosaur/fmm/ts_terms.py
jlmaurer/tectosaur
7cc5606d814f061395b19754e7a4b6c5e4c236e5
[ "MIT" ]
4
2018-05-29T08:21:13.000Z
2021-04-01T01:28:50.000Z
tectosaur/fmm/ts_terms.py
jlmaurer/tectosaur
7cc5606d814f061395b19754e7a4b6c5e4c236e5
[ "MIT" ]
8
2019-06-10T22:19:40.000Z
2022-01-12T20:55:37.000Z
from math import factorial import scipy.special import numpy as np def sloppy_spherical(y): r = np.linalg.norm(y) costheta = y[2] / r theta = np.arccos(costheta) phi = np.arccos(y[0] / r / np.sin(theta)) return r, theta, phi def Rdirect(n_max, y): r, theta, phi = sloppy_spherical(y) real = np.zeros((n_max + 1, 2 * n_max + 1)) imag = np.zeros((n_max + 1, 2 * n_max + 1)) Pmn = scipy.special.lpmn(n_max, n_max, np.cos(theta))[0] for i in range(n_max + 1): for j in range(-i, i + 1): if j < 0: lp = ( ((-1) ** (-j)) * (factorial(i + j) / factorial(i - j)) * Pmn[-j, i] / ((-1) ** -j) ) else: lp = Pmn[j, i] / ((-1) ** j) factor = (r ** i) * lp / factorial(i + j) real[i, n_max + j] = factor * np.cos(j * phi) imag[i, n_max + j] = factor * np.sin(j * phi) return real, imag def Sdirect(n_max, y): r, theta, phi = sloppy_spherical(y) real = np.zeros((n_max + 1, 2 * n_max + 1)) imag = np.zeros((n_max + 1, 2 * n_max + 1)) Pmn = scipy.special.lpmn(n_max, n_max, np.cos(theta))[0] for i in range(n_max + 1): for j in range(-i, i + 1): if j < 0: lp = ( ((-1) ** (-j)) * (factorial(i + j) / factorial(i - j)) * Pmn[-j, i] / ((-1) ** -j) ) else: lp = Pmn[j, i] / ((-1) ** j) factor = factorial(i - j) * lp / (r ** (i + 1)) real[i, n_max + j] = factor * np.cos(j * phi) imag[i, n_max + j] = factor * np.sin(j * phi) return real, imag def R(n_max, y): y1, y2, y3 = y real = np.zeros((n_max + 1, 2 * n_max + 1)) imag = np.zeros((n_max + 1, 2 * n_max + 1)) real[0, n_max] = 1.0 for i in range(0, n_max): real[i + 1, n_max + i + 1] = ( (y1 * real[i, n_max + i] - y2 * imag[i, n_max + i]) / (2 * (i + 1)) ) imag[i + 1, n_max + i + 1] = ( (y1 * imag[i, n_max + i] + y2 * real[i, n_max + i]) / (2 * (i + 1)) ) t2f = np.linalg.norm(y) ** 2 for j in range(n_max + 1): for i in range(j, n_max): factor = 1.0 / ((i + 1) ** 2 - j ** 2) t1f = (2 * i + 1) * y3 real[i + 1, n_max + j] = factor * (t1f * real[i, n_max + j] - t2f * real[i - 1, n_max + j]) imag[i + 1, n_max + j] = factor * (t1f * imag[i, n_max + j] - t2f * imag[i - 1, n_max + j]) for i in range(n_max + 1): for j in range(1, n_max + 1): real[i, n_max - j] = ((-1) ** j) * real[i, n_max + j] imag[i, n_max - j] = ((-1) ** (j + 1)) * imag[i, n_max + j] return real, imag def R_storagefree(n_max, y): def neg(real, imag, mi): return ( ((-1) ** mi) * real, ((-1) ** (mi + 1)) * imag ) y1, y2, y3 = y real = np.zeros((n_max + 1, 2 * n_max + 1)) imag = np.zeros((n_max + 1, 2 * n_max + 1)) t2f = np.linalg.norm(y) ** 2 Rsr = 1.0 Rsi = 0.0 for mi in range(0, n_max + 1): real[mi, n_max + mi] = Rsr imag[mi, n_max + mi] = Rsi real[mi, n_max - mi], imag[mi, n_max - mi] = neg(Rsr, Rsi, mi) Rm2r = 0.0 Rm2i = 0.0 Rm1r = Rsr Rm1i = Rsi for ni in range(mi, n_max): factor = 1.0 / ((ni + 1) ** 2 - mi ** 2) t1f = (2 * ni + 1) * y3 Rvr = factor * (t1f * Rm1r - t2f * Rm2r) Rvi = factor * (t1f * Rm1i - t2f * Rm2i) real[ni + 1, n_max + mi] = Rvr imag[ni + 1, n_max + mi] = Rvi real[ni + 1, n_max - mi], imag[ni + 1, n_max - mi] = neg(Rvr, Rvi, mi) Rm2r = Rm1r Rm2i = Rm1i Rm1r = Rvr Rm1i = Rvi Rsrold = Rsr Rsiold = Rsi Rsr = (y1 * Rsrold - y2 * Rsiold) / (2 * (mi + 1)) Rsi = (y1 * Rsiold + y2 * Rsrold) / (2 * (mi + 1)) return real, imag def Rderivs(n_max, y, d): Rvr, Rvi = R(n_max + 1, y) real = np.zeros((n_max + 1, 2 * n_max + 1)) imag = np.zeros((n_max + 1, 2 * n_max + 1)) if d == 0: for i in range(n_max): for j in range(-i, i + 1): real[i, n_max + j] = 0.5 * ( Rvr[i - 1, (n_max + 1) + j - 1] - Rvr[i - 1, (n_max + 1) + j + 1] ) imag[i, n_max + j] = 0.5 * ( Rvi[i - 1, (n_max + 1) + j - 1] - Rvi[i - 1, (n_max + 1) + j + 1] ) elif d == 1: for i in range(n_max + 1): for j in range(-i, i + 1): real[i, n_max + j] = -0.5 * ( Rvi[i - 1, (n_max + 1) + j - 1] + Rvi[i - 1, (n_max + 1) + j + 1] ) imag[i, n_max + j] = 0.5 * ( Rvr[i - 1, (n_max + 1) + j - 1] + Rvr[i - 1, (n_max + 1) + j + 1] ) else: for i in range(n_max + 1): for j in range(-i, i + 1): real[i, n_max + j] = Rvr[i - 1, (n_max + 1) + j] imag[i, n_max + j] = Rvi[i - 1, (n_max + 1) + j] return real, imag def S(n_max, y): y1, y2, y3 = y ynorm = np.linalg.norm(y) ynorm2 = ynorm ** 2 real = np.zeros((n_max + 1, 2 * n_max + 1)) imag = np.zeros((n_max + 1, 2 * n_max + 1)) real[0, n_max] = 1.0 / ynorm for i in range(0, n_max): factor = (2 * i + 1) / ynorm2 real[i + 1, n_max + i + 1] = factor * ( (y1 * real[i, n_max + i] - y2 * imag[i, n_max + i]) ) imag[i + 1, n_max + i + 1] = factor * ( (y1 * imag[i, n_max + i] + y2 * real[i, n_max + i]) ) for j in range(n_max + 1): for i in range(j, n_max): factor = 1.0 / ynorm2 t1f = (2 * i + 1) * y3 t2f = i ** 2 - j ** 2 real[i + 1, n_max + j] = factor * ( t1f * real[i, n_max + j] - t2f * real[i - 1, n_max + j] ) imag[i + 1, n_max + j] = factor * ( t1f * imag[i, n_max + j] - t2f * imag[i - 1, n_max + j] ) for i in range(n_max + 1): for j in range(1, n_max + 1): real[i, n_max - j] = ((-1) ** j) * real[i, n_max + j] imag[i, n_max - j] = ((-1) ** (j + 1)) * imag[i, n_max + j] return real, imag def S_storagefree(n_max, y): def neg(real, imag, mi): return ( ((-1) ** mi) * real, ((-1) ** (mi + 1)) * imag ) y1, y2, y3 = y real = np.zeros((n_max + 1, 2 * n_max + 1)) imag = np.zeros((n_max + 1, 2 * n_max + 1)) ynorm = np.linalg.norm(y) ynorm2 = ynorm ** 2 Ssr = 1.0 / ynorm Ssi = 0.0 for mi in range(0, n_max + 1): real[mi, n_max + mi] = Ssr imag[mi, n_max + mi] = Ssi real[mi, n_max - mi], imag[mi, n_max - mi] = neg(Ssr, Ssi, mi) Sm2r = 0.0 Sm2i = 0.0 Sm1r = Ssr Sm1i = Ssi for ni in range(mi, n_max): factor = 1.0 / ynorm2 t1f = (2 * ni + 1) * y3 t2f = ni ** 2 - mi ** 2 Svr = factor * (t1f * Sm1r - t2f * Sm2r) Svi = factor * (t1f * Sm1i - t2f * Sm2i) real[ni + 1, n_max + mi] = Svr imag[ni + 1, n_max + mi] = Svi real[ni + 1, n_max - mi], imag[ni + 1, n_max - mi] = neg(Svr, Svi, mi) Sm2r = Sm1r Sm2i = Sm1i Sm1r = Svr Sm1i = Svi Ssrold = Ssr Ssiold = Ssi factor = (2 * mi + 1) / ynorm2 Ssr = factor * (y1 * Ssrold - y2 * Ssiold) Ssi = factor * (y1 * Ssiold + y2 * Ssrold) return real, imag def Sderivs(n_max, y, d): Svr, Svi = S(n_max + 1, y) real = np.zeros((n_max + 1, 2 * n_max + 1)) imag = np.zeros((n_max + 1, 2 * n_max + 1)) if d == 0: for i in range(n_max + 1): for j in range(-i, i + 1): real[i, n_max + j] = 0.5 * ( Svr[i + 1, (n_max + 1) + j - 1] - Svr[i + 1, (n_max + 1) + j + 1] ) imag[i, n_max + j] = 0.5 * ( Svi[i + 1, (n_max + 1) + j - 1] - Svi[i + 1, (n_max + 1) + j + 1] ) elif d == 1: for i in range(n_max + 1): for j in range(-i, i + 1): real[i, n_max + j] = -0.5 * ( Svi[i + 1, (n_max + 1) + j - 1] + Svi[i + 1, (n_max + 1) + j + 1] ) imag[i, n_max + j] = 0.5 * ( Svr[i + 1, (n_max + 1) + j - 1] + Svr[i + 1, (n_max + 1) + j + 1] ) else: for i in range(n_max + 1): for j in range(-i, i + 1): real[i, n_max + j] = -Svr[i + 1, (n_max + 1) + j] imag[i, n_max + j] = -Svi[i + 1, (n_max + 1) + j] return real, imag
34.431818
103
0.394719
from math import factorial import scipy.special import numpy as np def sloppy_spherical(y): r = np.linalg.norm(y) costheta = y[2] / r theta = np.arccos(costheta) phi = np.arccos(y[0] / r / np.sin(theta)) return r, theta, phi def Rdirect(n_max, y): r, theta, phi = sloppy_spherical(y) real = np.zeros((n_max + 1, 2 * n_max + 1)) imag = np.zeros((n_max + 1, 2 * n_max + 1)) Pmn = scipy.special.lpmn(n_max, n_max, np.cos(theta))[0] for i in range(n_max + 1): for j in range(-i, i + 1): if j < 0: lp = ( ((-1) ** (-j)) * (factorial(i + j) / factorial(i - j)) * Pmn[-j, i] / ((-1) ** -j) ) else: lp = Pmn[j, i] / ((-1) ** j) factor = (r ** i) * lp / factorial(i + j) real[i, n_max + j] = factor * np.cos(j * phi) imag[i, n_max + j] = factor * np.sin(j * phi) return real, imag def Sdirect(n_max, y): r, theta, phi = sloppy_spherical(y) real = np.zeros((n_max + 1, 2 * n_max + 1)) imag = np.zeros((n_max + 1, 2 * n_max + 1)) Pmn = scipy.special.lpmn(n_max, n_max, np.cos(theta))[0] for i in range(n_max + 1): for j in range(-i, i + 1): if j < 0: lp = ( ((-1) ** (-j)) * (factorial(i + j) / factorial(i - j)) * Pmn[-j, i] / ((-1) ** -j) ) else: lp = Pmn[j, i] / ((-1) ** j) factor = factorial(i - j) * lp / (r ** (i + 1)) real[i, n_max + j] = factor * np.cos(j * phi) imag[i, n_max + j] = factor * np.sin(j * phi) return real, imag def R(n_max, y): y1, y2, y3 = y real = np.zeros((n_max + 1, 2 * n_max + 1)) imag = np.zeros((n_max + 1, 2 * n_max + 1)) real[0, n_max] = 1.0 for i in range(0, n_max): real[i + 1, n_max + i + 1] = ( (y1 * real[i, n_max + i] - y2 * imag[i, n_max + i]) / (2 * (i + 1)) ) imag[i + 1, n_max + i + 1] = ( (y1 * imag[i, n_max + i] + y2 * real[i, n_max + i]) / (2 * (i + 1)) ) t2f = np.linalg.norm(y) ** 2 for j in range(n_max + 1): for i in range(j, n_max): factor = 1.0 / ((i + 1) ** 2 - j ** 2) t1f = (2 * i + 1) * y3 real[i + 1, n_max + j] = factor * (t1f * real[i, n_max + j] - t2f * real[i - 1, n_max + j]) imag[i + 1, n_max + j] = factor * (t1f * imag[i, n_max + j] - t2f * imag[i - 1, n_max + j]) for i in range(n_max + 1): for j in range(1, n_max + 1): real[i, n_max - j] = ((-1) ** j) * real[i, n_max + j] imag[i, n_max - j] = ((-1) ** (j + 1)) * imag[i, n_max + j] return real, imag def R_storagefree(n_max, y): def neg(real, imag, mi): return ( ((-1) ** mi) * real, ((-1) ** (mi + 1)) * imag ) y1, y2, y3 = y real = np.zeros((n_max + 1, 2 * n_max + 1)) imag = np.zeros((n_max + 1, 2 * n_max + 1)) t2f = np.linalg.norm(y) ** 2 Rsr = 1.0 Rsi = 0.0 for mi in range(0, n_max + 1): real[mi, n_max + mi] = Rsr imag[mi, n_max + mi] = Rsi real[mi, n_max - mi], imag[mi, n_max - mi] = neg(Rsr, Rsi, mi) Rm2r = 0.0 Rm2i = 0.0 Rm1r = Rsr Rm1i = Rsi for ni in range(mi, n_max): factor = 1.0 / ((ni + 1) ** 2 - mi ** 2) t1f = (2 * ni + 1) * y3 Rvr = factor * (t1f * Rm1r - t2f * Rm2r) Rvi = factor * (t1f * Rm1i - t2f * Rm2i) real[ni + 1, n_max + mi] = Rvr imag[ni + 1, n_max + mi] = Rvi real[ni + 1, n_max - mi], imag[ni + 1, n_max - mi] = neg(Rvr, Rvi, mi) Rm2r = Rm1r Rm2i = Rm1i Rm1r = Rvr Rm1i = Rvi Rsrold = Rsr Rsiold = Rsi Rsr = (y1 * Rsrold - y2 * Rsiold) / (2 * (mi + 1)) Rsi = (y1 * Rsiold + y2 * Rsrold) / (2 * (mi + 1)) return real, imag def Rderivs(n_max, y, d): Rvr, Rvi = R(n_max + 1, y) real = np.zeros((n_max + 1, 2 * n_max + 1)) imag = np.zeros((n_max + 1, 2 * n_max + 1)) if d == 0: for i in range(n_max): for j in range(-i, i + 1): real[i, n_max + j] = 0.5 * ( Rvr[i - 1, (n_max + 1) + j - 1] - Rvr[i - 1, (n_max + 1) + j + 1] ) imag[i, n_max + j] = 0.5 * ( Rvi[i - 1, (n_max + 1) + j - 1] - Rvi[i - 1, (n_max + 1) + j + 1] ) elif d == 1: for i in range(n_max + 1): for j in range(-i, i + 1): real[i, n_max + j] = -0.5 * ( Rvi[i - 1, (n_max + 1) + j - 1] + Rvi[i - 1, (n_max + 1) + j + 1] ) imag[i, n_max + j] = 0.5 * ( Rvr[i - 1, (n_max + 1) + j - 1] + Rvr[i - 1, (n_max + 1) + j + 1] ) else: for i in range(n_max + 1): for j in range(-i, i + 1): real[i, n_max + j] = Rvr[i - 1, (n_max + 1) + j] imag[i, n_max + j] = Rvi[i - 1, (n_max + 1) + j] return real, imag def S(n_max, y): y1, y2, y3 = y ynorm = np.linalg.norm(y) ynorm2 = ynorm ** 2 real = np.zeros((n_max + 1, 2 * n_max + 1)) imag = np.zeros((n_max + 1, 2 * n_max + 1)) real[0, n_max] = 1.0 / ynorm for i in range(0, n_max): factor = (2 * i + 1) / ynorm2 real[i + 1, n_max + i + 1] = factor * ( (y1 * real[i, n_max + i] - y2 * imag[i, n_max + i]) ) imag[i + 1, n_max + i + 1] = factor * ( (y1 * imag[i, n_max + i] + y2 * real[i, n_max + i]) ) for j in range(n_max + 1): for i in range(j, n_max): factor = 1.0 / ynorm2 t1f = (2 * i + 1) * y3 t2f = i ** 2 - j ** 2 real[i + 1, n_max + j] = factor * ( t1f * real[i, n_max + j] - t2f * real[i - 1, n_max + j] ) imag[i + 1, n_max + j] = factor * ( t1f * imag[i, n_max + j] - t2f * imag[i - 1, n_max + j] ) for i in range(n_max + 1): for j in range(1, n_max + 1): real[i, n_max - j] = ((-1) ** j) * real[i, n_max + j] imag[i, n_max - j] = ((-1) ** (j + 1)) * imag[i, n_max + j] return real, imag def S_storagefree(n_max, y): def neg(real, imag, mi): return ( ((-1) ** mi) * real, ((-1) ** (mi + 1)) * imag ) y1, y2, y3 = y real = np.zeros((n_max + 1, 2 * n_max + 1)) imag = np.zeros((n_max + 1, 2 * n_max + 1)) ynorm = np.linalg.norm(y) ynorm2 = ynorm ** 2 Ssr = 1.0 / ynorm Ssi = 0.0 for mi in range(0, n_max + 1): real[mi, n_max + mi] = Ssr imag[mi, n_max + mi] = Ssi real[mi, n_max - mi], imag[mi, n_max - mi] = neg(Ssr, Ssi, mi) Sm2r = 0.0 Sm2i = 0.0 Sm1r = Ssr Sm1i = Ssi for ni in range(mi, n_max): factor = 1.0 / ynorm2 t1f = (2 * ni + 1) * y3 t2f = ni ** 2 - mi ** 2 Svr = factor * (t1f * Sm1r - t2f * Sm2r) Svi = factor * (t1f * Sm1i - t2f * Sm2i) real[ni + 1, n_max + mi] = Svr imag[ni + 1, n_max + mi] = Svi real[ni + 1, n_max - mi], imag[ni + 1, n_max - mi] = neg(Svr, Svi, mi) Sm2r = Sm1r Sm2i = Sm1i Sm1r = Svr Sm1i = Svi Ssrold = Ssr Ssiold = Ssi factor = (2 * mi + 1) / ynorm2 Ssr = factor * (y1 * Ssrold - y2 * Ssiold) Ssi = factor * (y1 * Ssiold + y2 * Ssrold) return real, imag def Sderivs(n_max, y, d): Svr, Svi = S(n_max + 1, y) real = np.zeros((n_max + 1, 2 * n_max + 1)) imag = np.zeros((n_max + 1, 2 * n_max + 1)) if d == 0: for i in range(n_max + 1): for j in range(-i, i + 1): real[i, n_max + j] = 0.5 * ( Svr[i + 1, (n_max + 1) + j - 1] - Svr[i + 1, (n_max + 1) + j + 1] ) imag[i, n_max + j] = 0.5 * ( Svi[i + 1, (n_max + 1) + j - 1] - Svi[i + 1, (n_max + 1) + j + 1] ) elif d == 1: for i in range(n_max + 1): for j in range(-i, i + 1): real[i, n_max + j] = -0.5 * ( Svi[i + 1, (n_max + 1) + j - 1] + Svi[i + 1, (n_max + 1) + j + 1] ) imag[i, n_max + j] = 0.5 * ( Svr[i + 1, (n_max + 1) + j - 1] + Svr[i + 1, (n_max + 1) + j + 1] ) else: for i in range(n_max + 1): for j in range(-i, i + 1): real[i, n_max + j] = -Svr[i + 1, (n_max + 1) + j] imag[i, n_max + j] = -Svi[i + 1, (n_max + 1) + j] return real, imag
true
true
f72a71fdb4445df86e6a963308c53723cb7372ed
43
py
Python
src/util/__init__.py
megemini/DataCastle2017
261134f760d8c1bbfc3e65e1362b7710e601947d
[ "MIT" ]
null
null
null
src/util/__init__.py
megemini/DataCastle2017
261134f760d8c1bbfc3e65e1362b7710e601947d
[ "MIT" ]
null
null
null
src/util/__init__.py
megemini/DataCastle2017
261134f760d8c1bbfc3e65e1362b7710e601947d
[ "MIT" ]
null
null
null
# import pandas as pd # import numpy as np
14.333333
21
0.72093
true
true
f72a72d605a3a44af713856c6084a9b2d5e7bef2
6,046
py
Python
src/attacks/base.py
DwaraknathT/sparsity
705f2cba074e6ab4f7655c6af98882773cd826bf
[ "MIT" ]
null
null
null
src/attacks/base.py
DwaraknathT/sparsity
705f2cba074e6ab4f7655c6af98882773cd826bf
[ "MIT" ]
null
null
null
src/attacks/base.py
DwaraknathT/sparsity
705f2cba074e6ab4f7655c6af98882773cd826bf
[ "MIT" ]
null
null
null
import torch class Attack(object): r""" Base class for all attacks. .. note:: It automatically set device to the device where given model is. It temporarily changes the original model's training mode to `test` by `.eval()` only during an attack process. """ def __init__(self, name, model): r""" Initializes internal attack state. Arguments: name (str) : name of an attack. model (torch.nn.Module): model to attack. """ self.attack = name self.model = model self.model_name = str(model).split("(")[0] self.training = model.training self.device = next(model.parameters()).device self._targeted = 1 self._attack_mode = "original" self._return_type = "float" def forward(self, *input): r""" It defines the computation performed at every call. Should be overridden by all subclasses. """ raise NotImplementedError def set_attack_mode(self, mode): r""" Set the attack mode. Arguments: mode (str) : 'original' (DEFAULT) 'targeted' - Use input labels as targeted labels. 'least_likely' - Use least likely labels as targeted labels. """ if self._attack_mode is "only_original": raise ValueError( "Changing attack mode is not supported in this attack method." ) if mode == "original": self._attack_mode = "original" self._targeted = 1 self._transform_label = self._get_label elif mode == "targeted": self._attack_mode = "targeted" self._targeted = -1 self._transform_label = self._get_label elif mode == "least_likely": self._attack_mode = "least_likely" self._targeted = -1 self._transform_label = self._get_least_likely_label else: raise ValueError( mode + " is not a valid mode. [Options : original, targeted, least_likely]" ) def set_return_type(self, type): r""" Set the return type of adversarial images: `int` or `float`. Arguments: type (str) : 'float' or 'int'. (DEFAULT : 'float') """ if type == "float": self._return_type = "float" elif type == "int": self._return_type = "int" else: raise ValueError(type + " is not a valid type. [Options : float, int]") def save(self, save_path, data_loader, verbose=True): r""" Save adversarial images as torch.tensor from given torch.utils.data.DataLoader. Arguments: save_path (str) : save_path. data_loader (torch.utils.data.DataLoader) : data loader. verbose (bool) : True for displaying detailed information. (DEFAULT : True) """ self.model.eval() image_list = [] label_list = [] correct = 0 total = 0 total_batch = len(data_loader) for step, (images, labels) in enumerate(data_loader): adv_images = self.__call__(images, labels) image_list.append(adv_images.cpu()) label_list.append(labels.cpu()) if self._return_type == "int": adv_images = adv_images.float() / 255 if verbose: outputs = self.model(adv_images) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels.to(self.device)).sum() acc = 100 * float(correct) / total print( "- Save Progress : %2.2f %% / Accuracy : %2.2f %%" % ((step + 1) / total_batch * 100, acc), end="\r", ) x = torch.cat(image_list, 0) y = torch.cat(label_list, 0) torch.save((x, y), save_path) print("\n- Save Complete!") self._switch_model() def _transform_label(self, images, labels): r""" Function for changing the attack mode. """ return labels def _get_label(self, images, labels): r""" Function for changing the attack mode. Return input labels. """ return labels def _get_least_likely_label(self, images, labels): r""" Function for changing the attack mode. Return least likely labels. """ outputs = self.model(images) _, labels = torch.min(outputs.data, 1) labels = labels.detach_() return labels def _to_uint(self, images): r""" Function for changing the return type. Return images as int. """ return (images * 255).type(torch.uint8) def _switch_model(self): r""" Function for changing the training mode of the model. """ if self.training: self.model.train() else: self.model.eval() def __str__(self): info = self.__dict__.copy() del_keys = ["model", "attack"] for key in info.keys(): if key[0] == "_": del_keys.append(key) for key in del_keys: del info[key] info["attack_mode"] = self._attack_mode if info["attack_mode"] == "only_original": info["attack_mode"] = "original" info["return_type"] = self._return_type return ( self.attack + "(" + ", ".join("{}={}".format(key, val) for key, val in info.items()) + ")" ) def __call__(self, *input, **kwargs): self.model.eval() images = self.forward(*input, **kwargs) self._switch_model() if self._return_type == "int": images = self._to_uint(images) return images
28.654028
87
0.531757
import torch class Attack(object): def __init__(self, name, model): self.attack = name self.model = model self.model_name = str(model).split("(")[0] self.training = model.training self.device = next(model.parameters()).device self._targeted = 1 self._attack_mode = "original" self._return_type = "float" def forward(self, *input): raise NotImplementedError def set_attack_mode(self, mode): if self._attack_mode is "only_original": raise ValueError( "Changing attack mode is not supported in this attack method." ) if mode == "original": self._attack_mode = "original" self._targeted = 1 self._transform_label = self._get_label elif mode == "targeted": self._attack_mode = "targeted" self._targeted = -1 self._transform_label = self._get_label elif mode == "least_likely": self._attack_mode = "least_likely" self._targeted = -1 self._transform_label = self._get_least_likely_label else: raise ValueError( mode + " is not a valid mode. [Options : original, targeted, least_likely]" ) def set_return_type(self, type): if type == "float": self._return_type = "float" elif type == "int": self._return_type = "int" else: raise ValueError(type + " is not a valid type. [Options : float, int]") def save(self, save_path, data_loader, verbose=True): self.model.eval() image_list = [] label_list = [] correct = 0 total = 0 total_batch = len(data_loader) for step, (images, labels) in enumerate(data_loader): adv_images = self.__call__(images, labels) image_list.append(adv_images.cpu()) label_list.append(labels.cpu()) if self._return_type == "int": adv_images = adv_images.float() / 255 if verbose: outputs = self.model(adv_images) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels.to(self.device)).sum() acc = 100 * float(correct) / total print( "- Save Progress : %2.2f %% / Accuracy : %2.2f %%" % ((step + 1) / total_batch * 100, acc), end="\r", ) x = torch.cat(image_list, 0) y = torch.cat(label_list, 0) torch.save((x, y), save_path) print("\n- Save Complete!") self._switch_model() def _transform_label(self, images, labels): return labels def _get_label(self, images, labels): return labels def _get_least_likely_label(self, images, labels): outputs = self.model(images) _, labels = torch.min(outputs.data, 1) labels = labels.detach_() return labels def _to_uint(self, images): return (images * 255).type(torch.uint8) def _switch_model(self): if self.training: self.model.train() else: self.model.eval() def __str__(self): info = self.__dict__.copy() del_keys = ["model", "attack"] for key in info.keys(): if key[0] == "_": del_keys.append(key) for key in del_keys: del info[key] info["attack_mode"] = self._attack_mode if info["attack_mode"] == "only_original": info["attack_mode"] = "original" info["return_type"] = self._return_type return ( self.attack + "(" + ", ".join("{}={}".format(key, val) for key, val in info.items()) + ")" ) def __call__(self, *input, **kwargs): self.model.eval() images = self.forward(*input, **kwargs) self._switch_model() if self._return_type == "int": images = self._to_uint(images) return images
true
true
f72a72f956c5cffe74f5d5fac3101a4868adb5bf
28,213
py
Python
src/test/isolation2/sql_isolation_testcase.py
fanfuxiaoran/gpdb
84e73a9eb2d4a7aff8ab66c0ee76e47b51676be6
[ "PostgreSQL", "Apache-2.0" ]
4
2017-11-28T08:12:58.000Z
2020-10-28T04:15:52.000Z
src/test/isolation2/sql_isolation_testcase.py
fanfuxiaoran/gpdb
84e73a9eb2d4a7aff8ab66c0ee76e47b51676be6
[ "PostgreSQL", "Apache-2.0" ]
null
null
null
src/test/isolation2/sql_isolation_testcase.py
fanfuxiaoran/gpdb
84e73a9eb2d4a7aff8ab66c0ee76e47b51676be6
[ "PostgreSQL", "Apache-2.0" ]
null
null
null
""" Copyright (c) 2004-Present VMware, Inc. or its affiliates. This program and the accompanying materials are made available under the terms of the 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 pg import os import subprocess import re import multiprocessing import tempfile import time import sys import socket from optparse import OptionParser import traceback def is_digit(n): try: int(n) return True except ValueError: return False def null_notice_receiver(notice): ''' Tests ignore notice messages when analyzing results, so silently drop notices from the pg.connection ''' return class SQLIsolationExecutor(object): def __init__(self, dbname=''): self.processes = {} # The re.S flag makes the "." in the regex match newlines. # When matched against a command in process_command(), all # lines in the command are matched and sent as SQL query. self.command_pattern = re.compile(r"^(-?\d+|[*])([&\\<\\>USq]*?)\:(.*)", re.S) if dbname: self.dbname = dbname else: self.dbname = os.environ.get('PGDATABASE') class SQLConnection(object): def __init__(self, out_file, name, mode, dbname): self.name = name self.mode = mode self.out_file = out_file self.dbname = dbname parent_conn, child_conn = multiprocessing.Pipe(True) self.p = multiprocessing.Process(target=self.session_process, args=(child_conn,)) self.pipe = parent_conn self.has_open = False self.p.start() # Close "our" copy of the child's handle, so that if the child dies, # recv() on the pipe will fail. child_conn.close(); self.out_file = out_file def session_process(self, pipe): sp = SQLIsolationExecutor.SQLSessionProcess(self.name, self.mode, pipe, self.dbname) sp.do() def query(self, command): print(file=self.out_file) self.out_file.flush() if len(command.strip()) == 0: return if self.has_open: raise Exception("Cannot query command while waiting for results") self.pipe.send((command, False)) r = self.pipe.recv() if r is None: raise Exception("Execution failed") print(r.rstrip(), file=self.out_file) def fork(self, command, blocking): print(" <waiting ...>", file=self.out_file) self.pipe.send((command, True)) if blocking: time.sleep(0.5) if self.pipe.poll(0): p = self.pipe.recv() raise Exception("Forked command is not blocking; got output: %s" % p.strip()) self.has_open = True def join(self): r = None print(" <... completed>", file=self.out_file) if self.has_open: r = self.pipe.recv() if r is None: raise Exception("Execution failed") print(r.rstrip(), file=self.out_file) self.has_open = False def stop(self): self.pipe.send(("", False)) self.p.join() if self.has_open: raise Exception("Should not finish test case while waiting for results") def quit(self): print(" ... <quitting>", file=self.out_file) self.stop() def terminate(self): self.pipe.close() self.p.terminate() class SQLSessionProcess(object): def __init__(self, name, mode, pipe, dbname): """ Constructor """ self.name = name self.mode = mode self.pipe = pipe self.dbname = dbname if self.mode == "utility": (hostname, port) = self.get_hostname_port(name, 'p') self.con = self.connectdb(given_dbname=self.dbname, given_host=hostname, given_port=port, given_opt="-c gp_role=utility") elif self.mode == "standby": # Connect to standby even when it's role is recorded # as mirror. This is useful for scenarios where a # test needs to promote a standby without using # gpactivatestandby. (hostname, port) = self.get_hostname_port(name, 'm') self.con = self.connectdb(given_dbname=self.dbname, given_host=hostname, given_port=port) else: self.con = self.connectdb(self.dbname) def connectdb(self, given_dbname, given_host = None, given_port = None, given_opt = None): con = None retry = 1000 while retry: try: if (given_port is None): con = pg.connect(host= given_host, opt= given_opt, dbname= given_dbname) else: con = pg.connect(host= given_host, port= given_port, opt= given_opt, dbname= given_dbname) break except Exception as e: if (("the database system is starting up" in str(e) or "the database system is in recovery mode" in str(e)) and retry > 1): retry -= 1 time.sleep(0.1) else: raise con.set_notice_receiver(null_notice_receiver) return con def get_hostname_port(self, contentid, role): """ Gets the port number/hostname combination of the contentid and role """ query = ("SELECT hostname, port FROM gp_segment_configuration WHERE" " content = %s AND role = '%s'") % (contentid, role) con = self.connectdb(self.dbname, given_opt="-c gp_role=utility") r = con.query(query).getresult() con.close() if len(r) == 0: raise Exception("Invalid content %s" % contentid) if r[0][0] == socket.gethostname(): return (None, int(r[0][1])) return (r[0][0], int(r[0][1])) def printout_result(self, r): """ Print out a pygresql result set (a Query object, after the query has been executed), in a format that imitates the default formatting of psql. This isn't a perfect imitation: we left-justify all the fields and headers, whereas psql centers the header, and right-justifies numeric fields. But this is close enough, to make gpdiff.pl recognize the result sets as such. (We used to just call str(r), and let PyGreSQL do the formatting. But even though PyGreSQL's default formatting is close to psql's, it's not close enough.) """ widths = [] # Figure out the widths of each column. fields = r.listfields() for f in fields: widths.append(len(str(f))) rset = r.getresult() for row in rset: colno = 0 for col in row: if col is None: col = "" widths[colno] = max(widths[colno], len(str(col))) colno = colno + 1 # Start printing. Header first. result = "" colno = 0 for f in fields: if colno > 0: result += "|" result += " " + f.ljust(widths[colno]) + " " colno = colno + 1 result += "\n" # Then the bar ("----+----") colno = 0 for f in fields: if colno > 0: result += "+" result += "".ljust(widths[colno] + 2, "-") colno = colno + 1 result += "\n" # Then the result set itself for row in rset: colno = 0 for col in row: if colno > 0: result += "|" if isinstance(col, float): col = format(col, "g") elif isinstance(col, bool): if col: col = 't' else: col = 'f' elif col is None: col = "" result += " " + str(col).ljust(widths[colno]) + " " colno = colno + 1 result += "\n" # Finally, the row count if len(rset) == 1: result += "(1 row)\n" else: result += "(" + str(len(rset)) + " rows)\n" return result def execute_command(self, command): """ Executes a given command """ try: r = self.con.query(command) if r is not None: if type(r) == str: # INSERT, UPDATE, etc that returns row count but not result set echo_content = command[:-1].partition(" ")[0].upper() return "%s %s" % (echo_content, r) else: # SELECT or similar, print the result set without the command (type pg.Query) return self.printout_result(r) else: # CREATE or other DDL without a result set or count echo_content = command[:-1].partition(" ")[0].upper() return echo_content except Exception as e: return str(e) def do(self): """ Process loop. Ends when the command None is received """ (c, wait) = self.pipe.recv() while c: if wait: time.sleep(0.1) r = self.execute_command(c) self.pipe.send(r) r = None (c, wait) = self.pipe.recv() def get_process(self, out_file, name, mode="", dbname=""): """ Gets or creates the process by the given name """ if len(name) > 0 and not is_digit(name): raise Exception("Name should be a number") if len(name) > 0 and mode != "utility" and int(name) >= 1024: raise Exception("Session name should be smaller than 1024 unless it is utility mode number") if not (name, mode) in self.processes: if not dbname: dbname = self.dbname self.processes[(name, mode)] = SQLIsolationExecutor.SQLConnection(out_file, name, mode, dbname) return self.processes[(name, mode)] def quit_process(self, out_file, name, mode="", dbname=""): """ Quits a process with the given name """ if len(name) > 0 and not is_digit(name): raise Exception("Name should be a number") if len(name) > 0 and mode != "utility" and int(name) >= 1024: raise Exception("Session name should be smaller than 1024 unless it is utility mode number") if not (name, mode) in self.processes: raise Exception("Sessions not started cannot be quit") self.processes[(name, mode)].quit() del self.processes[(name, mode)] def get_all_primary_contentids(self, dbname): """ Retrieves all primary content IDs (including the master). Intended for use by *U queries. """ if not dbname: dbname = self.dbname con = pg.connect(dbname=dbname) result = con.query("SELECT content FROM gp_segment_configuration WHERE role = 'p'").getresult() if len(result) == 0: raise Exception("Invalid gp_segment_configuration contents") return [int(content[0]) for content in result] def process_command(self, command, output_file): """ Processes the given command. The command at this point still includes the isolation behavior flags, e.g. which session to use. """ process_name = "" sql = command flag = "" con_mode = "" dbname = "" m = self.command_pattern.match(command) if m: process_name = m.groups()[0] flag = m.groups()[1] if flag and flag[0] == "U": con_mode = "utility" elif flag and flag[0] == "S": if len(flag) > 1: flag = flag[1:] con_mode = "standby" sql = m.groups()[2] sql = sql.lstrip() # If db_name is specifed , it should be of the following syntax: # 1:@db_name <db_name>: <sql> if sql.startswith('@db_name'): sql_parts = sql.split(':', 2) if not len(sql_parts) == 2: raise Exception("Invalid syntax with dbname, should be of the form 1:@db_name <db_name>: <sql>") if not sql_parts[0].startswith('@db_name'): raise Exception("Invalid syntax with dbname, should be of the form 1:@db_name <db_name>: <sql>") if not len(sql_parts[0].split()) == 2: raise Exception("Invalid syntax with dbname, should be of the form 1:@db_name <db_name>: <sql>") dbname = sql_parts[0].split()[1].strip() if not dbname: raise Exception("Invalid syntax with dbname, should be of the form 1:@db_name <db_name>: <sql>") sql = sql_parts[1] if not flag: if sql.startswith('!'): sql = sql[1:] # Check for execution mode. E.g. # !\retcode path/to/executable --option1 --option2 ... # # At the moment, we only recognize the \retcode mode, which # ignores all program output in the diff (it's still printed) # and adds the return code. mode = None if sql.startswith('\\'): mode, sql = sql.split(None, 1) if mode != '\\retcode': raise Exception('Invalid execution mode: {}'.format(mode)) cmd_output = subprocess.Popen(sql.strip(), stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=True) stdout, _ = cmd_output.communicate() print(file=output_file) if mode == '\\retcode': print('-- start_ignore', file=output_file) print(stdout.decode(), file=output_file) if mode == '\\retcode': print('-- end_ignore', file=output_file) print('(exited with code {})'.format(cmd_output.returncode), file=output_file) else: self.get_process(output_file, process_name, con_mode, dbname=dbname).query(sql.strip()) elif flag == "&": self.get_process(output_file, process_name, con_mode, dbname=dbname).fork(sql.strip(), True) elif flag == ">": self.get_process(output_file, process_name, con_mode, dbname=dbname).fork(sql.strip(), False) elif flag == "<": if len(sql) > 0: raise Exception("No query should be given on join") self.get_process(output_file, process_name, con_mode, dbname=dbname).join() elif flag == "q": if len(sql) > 0: raise Exception("No query should be given on quit") self.quit_process(output_file, process_name, con_mode, dbname=dbname) elif flag == "U": if process_name == '*': process_names = [str(content) for content in self.get_all_primary_contentids(dbname)] else: process_names = [process_name] for name in process_names: self.get_process(output_file, name, con_mode, dbname=dbname).query(sql.strip()) elif flag == "U&": self.get_process(output_file, process_name, con_mode, dbname=dbname).fork(sql.strip(), True) elif flag == "U<": if len(sql) > 0: raise Exception("No query should be given on join") self.get_process(output_file, process_name, con_mode, dbname=dbname).join() elif flag == "Uq": if len(sql) > 0: raise Exception("No query should be given on quit") self.quit_process(output_file, process_name, con_mode, dbname=dbname) elif flag == "S": self.get_process(output_file, process_name, con_mode, dbname=dbname).query(sql.strip()) else: raise Exception("Invalid isolation flag") def process_isolation_file(self, sql_file, output_file): """ Processes the given sql file and writes the output to output file """ try: command = "" newline = False for line in sql_file: # this logic replicates the python2 behavior of a trailing comma at the end of print # i.e. ''' print >>output_file, line.strip(), ''' print((" " if command and not newline else "") + line.strip(), end="", file=output_file) newline = False if line[0] == "!": command_part = line # shell commands can use -- for multichar options like --include elif re.match(r";.*--", line) or re.match(r"^--", line): command_part = line.partition("--")[0] # remove comment from line else: command_part = line if command_part == "" or command_part == "\n": print(file=output_file) newline = True elif re.match(r".*;\s*$", command_part) or re.match(r"^\d+[q\\<]:$", line) or re.match(r"^-?\d+[SU][q\\<]:$", line): command += command_part try: self.process_command(command, output_file) except Exception as e: print("FAILED: ", e, file=output_file) command = "" else: command += command_part for process in list(self.processes.values()): process.stop() except: for process in list(self.processes.values()): process.terminate() raise finally: for process in list(self.processes.values()): process.terminate() class SQLIsolationTestCase: """ The isolation test case allows a fine grained control of interleaved executing transactions. This is mainly used to test isolation behavior. [<#>[flag]:] <sql> | ! <shell scripts or command> #: either an integer indicating a unique session, or a content-id if followed by U (for utility-mode connections). In 'U' mode, the content-id can alternatively be an asterisk '*' to perform a utility-mode query on the master and all primaries. flag: &: expect blocking behavior >: running in background without blocking <: join an existing session q: quit the given session U: connect in utility mode to primary contentid from gp_segment_configuration U&: expect blocking behavior in utility mode (does not currently support an asterisk target) U<: join an existing utility mode session (does not currently support an asterisk target) An example is: Execute BEGIN in transaction 1 Execute BEGIN in transaction 2 Execute INSERT in transaction 2 Execute SELECT in transaction 1 Execute COMMIT in transaction 2 Execute SELECT in transaction 1 The isolation tests are specified identical to sql-scripts in normal SQLTestCases. However, it is possible to prefix a SQL line with an tranaction identifier followed by a colon (":"). The above example would be defined by 1: BEGIN; 2: BEGIN; 2: INSERT INTO a VALUES (1); 1: SELECT * FROM a; 2: COMMIT; 1: SELECT * FROM a; Blocking behavior can be tested by forking and joining. 1: BEGIN; 2: BEGIN; 1: DELETE FROM foo WHERE a = 4; 2&: DELETE FROM foo WHERE a = 4; 1: COMMIT; 2<: 2: COMMIT; 2& forks the command. It is executed in the background. If the command is NOT blocking at this point, it is considered an error. 2< joins the background command and outputs the result of the command execution. Session ids should be smaller than 1024. 2U: Executes a utility command connected to port 40000. One difference to SQLTestCase is the output of INSERT. SQLTestCase would output "INSERT 0 1" if one tuple is inserted. SQLIsolationTestCase would output "INSERT 1". As the SQLIsolationTestCase needs to have a more fine-grained control over the execution order than possible with PSQL, it uses the pygresql python library instead. Connecting to a specific database: 1. If you specify a db_name metadata in the sql file, connect to that database in all open sessions. 2. If you want a specific session to be connected to a specific database , specify the sql as follows: 1:@db_name testdb: <sql> 2:@db_name test2db: <sql> 1: <sql> 2: <sql> etc Here session 1 will be connected to testdb and session 2 will be connected to test2db. You can specify @db_name only at the beginning of the session. For eg:, following would error out: 1:@db_name testdb: <sql> 2:@db_name test2db: <sql> 1: @db_name testdb: <sql> 2: <sql> etc Quitting sessions: By default, all opened sessions will be stopped only at the end of the sql file execution. If you want to explicitly quit a session in the middle of the test execution, you can specify a flag 'q' with the session identifier. For eg: 1:@db_name testdb: <sql> 2:@db_name test2db: <sql> 1: <sql> 2: <sql> 1q: 2: <sql> 3: <sql> 2q: 3: <sql> 2: @db_name test: <sql> 1q: ---> Will quit the session established with testdb. 2q: ---> Will quit the session established with test2db. The subsequent 2: @db_name test: <sql> will open a new session with the database test and execute the sql against that session. Catalog Modification: Some tests are easier to write if it's possible to modify a system catalog across the *entire* cluster. To perform a utility-mode query on all segments and the master, you can use *U commands: *U: SET allow_system_table_mods = true; *U: UPDATE pg_catalog.<table> SET <column> = <value> WHERE <cond>; Since the number of query results returned by a *U command depends on the developer's cluster configuration, it can be useful to wrap them in a start_/end_ignore block. (Unfortunately, this also hides legitimate failures; a better long-term solution is needed.) Block/join flags are not currently supported with *U. Line continuation: If a line is not ended by a semicolon ';' which is followed by 0 or more spaces, the line will be combined with next line and sent together as a single statement. e.g.: Send to the server separately: 1: SELECT * FROM t1; -> send "SELECT * FROM t1;" SELECT * FROM t2; -> send "SELECT * FROM t2;" e.g.: Send to the server once: 1: SELECT * FROM t1; SELECT * FROM t2; -> "send SELECT * FROM t1; SELECT * FROM t2;" ATTENTION: Send multi SQL statements once: Multi SQL statements can be sent at once, but there are some known issues. Generally only the last query result will be printed. But due to the difficulties of dealing with semicolons insides quotes, we always echo the first SQL command instead of the last one if query() returns None. This created some strange issues like: CREATE TABLE t1 (a INT); INSERT INTO t1 SELECT generate_series(1,1000); CREATE 1000 (Should be INSERT 1000, but here the CREATE is taken due to the limitation) """ def run_sql_file(self, sql_file, out_file = None, out_dir = None, optimizer = None): """ Given a sql file and an ans file, this adds the specified gucs (self.gucs) to the sql file , runs the sql against the test case database (self.db_name) and verifies the output with the ans file. If an 'init_file' exists in the same location as the sql_file, this will be used while doing gpdiff. """ # Add gucs to the test sql and form the actual sql file to be run if not out_dir: out_dir = self.get_out_dir() if not os.path.exists(out_dir): TINCSystem.make_dirs(out_dir, ignore_exists_error = True) if optimizer is None: gucs_sql_file = os.path.join(out_dir, os.path.basename(sql_file)) else: # sql file will be <basename>_opt.sql or <basename>_planner.sql based on optimizer gucs_sql_file = os.path.join(out_dir, os.path.basename(sql_file).replace('.sql', '_%s.sql' %self._optimizer_suffix(optimizer))) self._add_gucs_to_sql_file(sql_file, gucs_sql_file, optimizer) self.test_artifacts.append(gucs_sql_file) if not out_file: if optimizer is None: out_file = os.path.join(self.get_out_dir(), os.path.basename(sql_file).replace('.sql', '.out')) else: # out file will be *_opt.out or *_planner.out based on optimizer out_file = os.path.join(self.get_out_dir(), os.path.basename(sql_file).replace('.sql', '_%s.out' %self._optimizer_suffix(optimizer))) self.test_artifacts.append(out_file) executor = SQLIsolationExecutor(dbname=self.db_name) with open(out_file, "w") as f: executor.process_isolation_file(open(sql_file), f) f.flush() if out_file[-2:] == '.t': out_file = out_file[:-2] return out_file if __name__ == "__main__": parser = OptionParser() parser.add_option("--dbname", dest="dbname", help="connect to database DBNAME", metavar="DBNAME") (options, args) = parser.parse_args() executor = SQLIsolationExecutor(dbname=options.dbname) executor.process_isolation_file(sys.stdin, sys.stdout)
41.007267
193
0.543296
import pg import os import subprocess import re import multiprocessing import tempfile import time import sys import socket from optparse import OptionParser import traceback def is_digit(n): try: int(n) return True except ValueError: return False def null_notice_receiver(notice): return class SQLIsolationExecutor(object): def __init__(self, dbname=''): self.processes = {} self.command_pattern = re.compile(r"^(-?\d+|[*])([&\\<\\>USq]*?)\:(.*)", re.S) if dbname: self.dbname = dbname else: self.dbname = os.environ.get('PGDATABASE') class SQLConnection(object): def __init__(self, out_file, name, mode, dbname): self.name = name self.mode = mode self.out_file = out_file self.dbname = dbname parent_conn, child_conn = multiprocessing.Pipe(True) self.p = multiprocessing.Process(target=self.session_process, args=(child_conn,)) self.pipe = parent_conn self.has_open = False self.p.start() # recv() on the pipe will fail. child_conn.close(); self.out_file = out_file def session_process(self, pipe): sp = SQLIsolationExecutor.SQLSessionProcess(self.name, self.mode, pipe, self.dbname) sp.do() def query(self, command): print(file=self.out_file) self.out_file.flush() if len(command.strip()) == 0: return if self.has_open: raise Exception("Cannot query command while waiting for results") self.pipe.send((command, False)) r = self.pipe.recv() if r is None: raise Exception("Execution failed") print(r.rstrip(), file=self.out_file) def fork(self, command, blocking): print(" <waiting ...>", file=self.out_file) self.pipe.send((command, True)) if blocking: time.sleep(0.5) if self.pipe.poll(0): p = self.pipe.recv() raise Exception("Forked command is not blocking; got output: %s" % p.strip()) self.has_open = True def join(self): r = None print(" <... completed>", file=self.out_file) if self.has_open: r = self.pipe.recv() if r is None: raise Exception("Execution failed") print(r.rstrip(), file=self.out_file) self.has_open = False def stop(self): self.pipe.send(("", False)) self.p.join() if self.has_open: raise Exception("Should not finish test case while waiting for results") def quit(self): print(" ... <quitting>", file=self.out_file) self.stop() def terminate(self): self.pipe.close() self.p.terminate() class SQLSessionProcess(object): def __init__(self, name, mode, pipe, dbname): self.name = name self.mode = mode self.pipe = pipe self.dbname = dbname if self.mode == "utility": (hostname, port) = self.get_hostname_port(name, 'p') self.con = self.connectdb(given_dbname=self.dbname, given_host=hostname, given_port=port, given_opt="-c gp_role=utility") elif self.mode == "standby": # Connect to standby even when it's role is recorded (hostname, port) = self.get_hostname_port(name, 'm') self.con = self.connectdb(given_dbname=self.dbname, given_host=hostname, given_port=port) else: self.con = self.connectdb(self.dbname) def connectdb(self, given_dbname, given_host = None, given_port = None, given_opt = None): con = None retry = 1000 while retry: try: if (given_port is None): con = pg.connect(host= given_host, opt= given_opt, dbname= given_dbname) else: con = pg.connect(host= given_host, port= given_port, opt= given_opt, dbname= given_dbname) break except Exception as e: if (("the database system is starting up" in str(e) or "the database system is in recovery mode" in str(e)) and retry > 1): retry -= 1 time.sleep(0.1) else: raise con.set_notice_receiver(null_notice_receiver) return con def get_hostname_port(self, contentid, role): query = ("SELECT hostname, port FROM gp_segment_configuration WHERE" " content = %s AND role = '%s'") % (contentid, role) con = self.connectdb(self.dbname, given_opt="-c gp_role=utility") r = con.query(query).getresult() con.close() if len(r) == 0: raise Exception("Invalid content %s" % contentid) if r[0][0] == socket.gethostname(): return (None, int(r[0][1])) return (r[0][0], int(r[0][1])) def printout_result(self, r): widths = [] fields = r.listfields() for f in fields: widths.append(len(str(f))) rset = r.getresult() for row in rset: colno = 0 for col in row: if col is None: col = "" widths[colno] = max(widths[colno], len(str(col))) colno = colno + 1 result = "" colno = 0 for f in fields: if colno > 0: result += "|" result += " " + f.ljust(widths[colno]) + " " colno = colno + 1 result += "\n" colno = 0 for f in fields: if colno > 0: result += "+" result += "".ljust(widths[colno] + 2, "-") colno = colno + 1 result += "\n" for row in rset: colno = 0 for col in row: if colno > 0: result += "|" if isinstance(col, float): col = format(col, "g") elif isinstance(col, bool): if col: col = 't' else: col = 'f' elif col is None: col = "" result += " " + str(col).ljust(widths[colno]) + " " colno = colno + 1 result += "\n" if len(rset) == 1: result += "(1 row)\n" else: result += "(" + str(len(rset)) + " rows)\n" return result def execute_command(self, command): try: r = self.con.query(command) if r is not None: if type(r) == str: echo_content = command[:-1].partition(" ")[0].upper() return "%s %s" % (echo_content, r) else: return self.printout_result(r) else: echo_content = command[:-1].partition(" ")[0].upper() return echo_content except Exception as e: return str(e) def do(self): (c, wait) = self.pipe.recv() while c: if wait: time.sleep(0.1) r = self.execute_command(c) self.pipe.send(r) r = None (c, wait) = self.pipe.recv() def get_process(self, out_file, name, mode="", dbname=""): if len(name) > 0 and not is_digit(name): raise Exception("Name should be a number") if len(name) > 0 and mode != "utility" and int(name) >= 1024: raise Exception("Session name should be smaller than 1024 unless it is utility mode number") if not (name, mode) in self.processes: if not dbname: dbname = self.dbname self.processes[(name, mode)] = SQLIsolationExecutor.SQLConnection(out_file, name, mode, dbname) return self.processes[(name, mode)] def quit_process(self, out_file, name, mode="", dbname=""): if len(name) > 0 and not is_digit(name): raise Exception("Name should be a number") if len(name) > 0 and mode != "utility" and int(name) >= 1024: raise Exception("Session name should be smaller than 1024 unless it is utility mode number") if not (name, mode) in self.processes: raise Exception("Sessions not started cannot be quit") self.processes[(name, mode)].quit() del self.processes[(name, mode)] def get_all_primary_contentids(self, dbname): if not dbname: dbname = self.dbname con = pg.connect(dbname=dbname) result = con.query("SELECT content FROM gp_segment_configuration WHERE role = 'p'").getresult() if len(result) == 0: raise Exception("Invalid gp_segment_configuration contents") return [int(content[0]) for content in result] def process_command(self, command, output_file): process_name = "" sql = command flag = "" con_mode = "" dbname = "" m = self.command_pattern.match(command) if m: process_name = m.groups()[0] flag = m.groups()[1] if flag and flag[0] == "U": con_mode = "utility" elif flag and flag[0] == "S": if len(flag) > 1: flag = flag[1:] con_mode = "standby" sql = m.groups()[2] sql = sql.lstrip() if sql.startswith('@db_name'): sql_parts = sql.split(':', 2) if not len(sql_parts) == 2: raise Exception("Invalid syntax with dbname, should be of the form 1:@db_name <db_name>: <sql>") if not sql_parts[0].startswith('@db_name'): raise Exception("Invalid syntax with dbname, should be of the form 1:@db_name <db_name>: <sql>") if not len(sql_parts[0].split()) == 2: raise Exception("Invalid syntax with dbname, should be of the form 1:@db_name <db_name>: <sql>") dbname = sql_parts[0].split()[1].strip() if not dbname: raise Exception("Invalid syntax with dbname, should be of the form 1:@db_name <db_name>: <sql>") sql = sql_parts[1] if not flag: if sql.startswith('!'): sql = sql[1:] # and adds the return code. mode = None if sql.startswith('\\'): mode, sql = sql.split(None, 1) if mode != '\\retcode': raise Exception('Invalid execution mode: {}'.format(mode)) cmd_output = subprocess.Popen(sql.strip(), stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=True) stdout, _ = cmd_output.communicate() print(file=output_file) if mode == '\\retcode': print('-- start_ignore', file=output_file) print(stdout.decode(), file=output_file) if mode == '\\retcode': print('-- end_ignore', file=output_file) print('(exited with code {})'.format(cmd_output.returncode), file=output_file) else: self.get_process(output_file, process_name, con_mode, dbname=dbname).query(sql.strip()) elif flag == "&": self.get_process(output_file, process_name, con_mode, dbname=dbname).fork(sql.strip(), True) elif flag == ">": self.get_process(output_file, process_name, con_mode, dbname=dbname).fork(sql.strip(), False) elif flag == "<": if len(sql) > 0: raise Exception("No query should be given on join") self.get_process(output_file, process_name, con_mode, dbname=dbname).join() elif flag == "q": if len(sql) > 0: raise Exception("No query should be given on quit") self.quit_process(output_file, process_name, con_mode, dbname=dbname) elif flag == "U": if process_name == '*': process_names = [str(content) for content in self.get_all_primary_contentids(dbname)] else: process_names = [process_name] for name in process_names: self.get_process(output_file, name, con_mode, dbname=dbname).query(sql.strip()) elif flag == "U&": self.get_process(output_file, process_name, con_mode, dbname=dbname).fork(sql.strip(), True) elif flag == "U<": if len(sql) > 0: raise Exception("No query should be given on join") self.get_process(output_file, process_name, con_mode, dbname=dbname).join() elif flag == "Uq": if len(sql) > 0: raise Exception("No query should be given on quit") self.quit_process(output_file, process_name, con_mode, dbname=dbname) elif flag == "S": self.get_process(output_file, process_name, con_mode, dbname=dbname).query(sql.strip()) else: raise Exception("Invalid isolation flag") def process_isolation_file(self, sql_file, output_file): try: command = "" newline = False for line in sql_file: # this logic replicates the python2 behavior of a trailing comma at the end of print # i.e. ''' print >>output_file, line.strip(), ''' print((" " if command and not newline else "") + line.strip(), end="", file=output_file) newline = False if line[0] == "!": command_part = line # shell commands can use -- for multichar options like --include elif re.match(r";.*--", line) or re.match(r"^--", line): command_part = line.partition("--")[0] # remove comment from line else: command_part = line if command_part == "" or command_part == "\n": print(file=output_file) newline = True elif re.match(r".*;\s*$", command_part) or re.match(r"^\d+[q\\<]:$", line) or re.match(r"^-?\d+[SU][q\\<]:$", line): command += command_part try: self.process_command(command, output_file) except Exception as e: print("FAILED: ", e, file=output_file) command = "" else: command += command_part for process in list(self.processes.values()): process.stop() except: for process in list(self.processes.values()): process.terminate() raise finally: for process in list(self.processes.values()): process.terminate() class SQLIsolationTestCase: def run_sql_file(self, sql_file, out_file = None, out_dir = None, optimizer = None): # Add gucs to the test sql and form the actual sql file to be run if not out_dir: out_dir = self.get_out_dir() if not os.path.exists(out_dir): TINCSystem.make_dirs(out_dir, ignore_exists_error = True) if optimizer is None: gucs_sql_file = os.path.join(out_dir, os.path.basename(sql_file)) else: # sql file will be <basename>_opt.sql or <basename>_planner.sql based on optimizer gucs_sql_file = os.path.join(out_dir, os.path.basename(sql_file).replace('.sql', '_%s.sql' %self._optimizer_suffix(optimizer))) self._add_gucs_to_sql_file(sql_file, gucs_sql_file, optimizer) self.test_artifacts.append(gucs_sql_file) if not out_file: if optimizer is None: out_file = os.path.join(self.get_out_dir(), os.path.basename(sql_file).replace('.sql', '.out')) else: # out file will be *_opt.out or *_planner.out based on optimizer out_file = os.path.join(self.get_out_dir(), os.path.basename(sql_file).replace('.sql', '_%s.out' %self._optimizer_suffix(optimizer))) self.test_artifacts.append(out_file) executor = SQLIsolationExecutor(dbname=self.db_name) with open(out_file, "w") as f: executor.process_isolation_file(open(sql_file), f) f.flush() if out_file[-2:] == '.t': out_file = out_file[:-2] return out_file if __name__ == "__main__": parser = OptionParser() parser.add_option("--dbname", dest="dbname", help="connect to database DBNAME", metavar="DBNAME") (options, args) = parser.parse_args() executor = SQLIsolationExecutor(dbname=options.dbname) executor.process_isolation_file(sys.stdin, sys.stdout)
true
true
f72a7465c1ba7ec4989c9a8c22e6229787aa0733
18,818
py
Python
log_complete/model_89.py
LoLab-VU/Bayesian_Inference_of_Network_Dynamics
54a5ef7e868be34289836bbbb024a2963c0c9c86
[ "MIT" ]
null
null
null
log_complete/model_89.py
LoLab-VU/Bayesian_Inference_of_Network_Dynamics
54a5ef7e868be34289836bbbb024a2963c0c9c86
[ "MIT" ]
null
null
null
log_complete/model_89.py
LoLab-VU/Bayesian_Inference_of_Network_Dynamics
54a5ef7e868be34289836bbbb024a2963c0c9c86
[ "MIT" ]
null
null
null
# exported from PySB model 'model' from pysb import Model, Monomer, Parameter, Expression, Compartment, Rule, Observable, Initial, MatchOnce, Annotation, ANY, WILD Model() Monomer('Ligand', ['Receptor']) Monomer('ParpU', ['C3A']) Monomer('C8A', ['BidU', 'C3pro']) Monomer('SmacM', ['BaxA']) Monomer('BaxM', ['BidM', 'BaxA']) Monomer('Apop', ['C3pro', 'Xiap']) Monomer('Fadd', ['Receptor', 'C8pro']) Monomer('SmacC', ['Xiap']) Monomer('ParpC') Monomer('Xiap', ['SmacC', 'Apop', 'C3A']) Monomer('C9') Monomer('C3ub') Monomer('C8pro', ['Fadd', 'C6A']) Monomer('C6A', ['C8pro']) Monomer('C3pro', ['Apop', 'C8A']) Monomer('CytoCM', ['BaxA']) Monomer('CytoCC') Monomer('BaxA', ['BaxM', 'BaxA_1', 'BaxA_2', 'SmacM', 'CytoCM']) Monomer('ApafI') Monomer('BidU', ['C8A']) Monomer('BidT') Monomer('C3A', ['Xiap', 'ParpU', 'C6pro']) Monomer('ApafA') Monomer('BidM', ['BaxM']) Monomer('Receptor', ['Ligand', 'Fadd']) Monomer('C6pro', ['C3A']) Parameter('bind_0_Ligand_binder_Receptor_binder_target_2kf', 1.0) Parameter('bind_0_Ligand_binder_Receptor_binder_target_1kr', 1.0) Parameter('bind_0_Receptor_binder_Fadd_binder_target_2kf', 1.0) Parameter('bind_0_Receptor_binder_Fadd_binder_target_1kr', 1.0) Parameter('substrate_binding_0_Fadd_catalyzer_C8pro_substrate_2kf', 1.0) Parameter('substrate_binding_0_Fadd_catalyzer_C8pro_substrate_1kr', 1.0) Parameter('catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product_1kc', 1.0) Parameter('catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_2kf', 1.0) Parameter('catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_1kr', 1.0) Parameter('catalysis_1_C8A_catalyzer_BidU_substrate_BidT_product_1kc', 1.0) Parameter('conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_2kf', 1.0) Parameter('conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_1kr', 1.0) Parameter('inhibition_0_SmacC_inhibitor_Xiap_inh_target_2kf', 1.0) Parameter('inhibition_0_SmacC_inhibitor_Xiap_inh_target_1kr', 1.0) Parameter('conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_2kf', 1.0) Parameter('conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_1kr', 1.0) Parameter('catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_2kf', 1.0) Parameter('catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_1kr', 1.0) Parameter('catalysis_1_Apop_catalyzer_C3pro_substrate_C3A_product_1kc', 1.0) Parameter('inhibition_0_Xiap_inhibitor_Apop_inh_target_2kf', 1.0) Parameter('inhibition_0_Xiap_inhibitor_Apop_inh_target_1kr', 1.0) Parameter('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_2kf', 1.0) Parameter('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_1kr', 1.0) Parameter('catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product_1kc', 1.0) Parameter('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_2kf', 1.0) Parameter('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_1kr', 1.0) Parameter('catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product_1kc', 1.0) Parameter('equilibration_0_BidT_equil_a_BidM_equil_b_1kf', 1.0) Parameter('equilibration_0_BidT_equil_a_BidM_equil_b_1kr', 1.0) Parameter('catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_2kf', 1.0) Parameter('catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_1kr', 1.0) Parameter('catalysis_1_BidM_catalyzer_BaxM_substrate_BaxA_product_1kc', 1.0) Parameter('self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_2kf', 1.0) Parameter('self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_1kr', 1.0) Parameter('self_catalyze_1_BaxA_self_catalyzer_BaxM_self_substrate_1kc', 1.0) Parameter('pore_formation_0_BaxA_pore_2kf', 1.0) Parameter('pore_formation_0_BaxA_pore_1kr', 1.0) Parameter('pore_formation_1_BaxA_pore_2kf', 1.0) Parameter('pore_formation_1_BaxA_pore_1kr', 1.0) Parameter('pore_formation_2_BaxA_pore_2kf', 1.0) Parameter('pore_formation_2_BaxA_pore_1kr', 1.0) Parameter('transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_2kf', 1.0) Parameter('transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kr', 1.0) Parameter('transport_1_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kc', 1.0) Parameter('transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_2kf', 1.0) Parameter('transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kr', 1.0) Parameter('transport_1_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kc', 1.0) Parameter('catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_2kf', 1.0) Parameter('catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_1kr', 1.0) Parameter('catalysis_1_C8A_catalyzer_C3pro_substrate_C3A_product_1kc', 1.0) Parameter('catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_2kf', 1.0) Parameter('catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_1kr', 1.0) Parameter('catalysis_1_C3A_catalyzer_C6pro_substrate_C6A_product_1kc', 1.0) Parameter('catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_2kf', 1.0) Parameter('catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_1kr', 1.0) Parameter('catalysis_1_C6A_catalyzer_C8pro_substrate_C8A_product_1kc', 1.0) Parameter('Ligand_0', 1000.0) Parameter('ParpU_0', 1000000.0) Parameter('C8A_0', 0.0) Parameter('SmacM_0', 100000.0) Parameter('BaxM_0', 40000.0) Parameter('Apop_0', 0.0) Parameter('Fadd_0', 130000.0) Parameter('SmacC_0', 0.0) Parameter('ParpC_0', 0.0) Parameter('Xiap_0', 22250.0) Parameter('C9_0', 100000.0) Parameter('C3ub_0', 0.0) Parameter('C8pro_0', 130000.0) Parameter('C6A_0', 0.0) Parameter('C3pro_0', 21000.0) Parameter('CytoCM_0', 500000.0) Parameter('CytoCC_0', 0.0) Parameter('BaxA_0', 0.0) Parameter('ApafI_0', 100000.0) Parameter('BidU_0', 171000.0) Parameter('BidT_0', 0.0) Parameter('C3A_0', 0.0) Parameter('ApafA_0', 0.0) Parameter('BidM_0', 0.0) Parameter('Receptor_0', 100.0) Parameter('C6pro_0', 100.0) Observable('Ligand_obs', Ligand()) Observable('ParpU_obs', ParpU()) Observable('C8A_obs', C8A()) Observable('SmacM_obs', SmacM()) Observable('BaxM_obs', BaxM()) Observable('Apop_obs', Apop()) Observable('Fadd_obs', Fadd()) Observable('SmacC_obs', SmacC()) Observable('ParpC_obs', ParpC()) Observable('Xiap_obs', Xiap()) Observable('C9_obs', C9()) Observable('C3ub_obs', C3ub()) Observable('C8pro_obs', C8pro()) Observable('C6A_obs', C6A()) Observable('C3pro_obs', C3pro()) Observable('CytoCM_obs', CytoCM()) Observable('CytoCC_obs', CytoCC()) Observable('BaxA_obs', BaxA()) Observable('ApafI_obs', ApafI()) Observable('BidU_obs', BidU()) Observable('BidT_obs', BidT()) Observable('C3A_obs', C3A()) Observable('ApafA_obs', ApafA()) Observable('BidM_obs', BidM()) Observable('Receptor_obs', Receptor()) Observable('C6pro_obs', C6pro()) Rule('bind_0_Ligand_binder_Receptor_binder_target', Ligand(Receptor=None) + Receptor(Ligand=None, Fadd=None) | Ligand(Receptor=1) % Receptor(Ligand=1, Fadd=None), bind_0_Ligand_binder_Receptor_binder_target_2kf, bind_0_Ligand_binder_Receptor_binder_target_1kr) Rule('bind_0_Receptor_binder_Fadd_binder_target', Receptor(Ligand=ANY, Fadd=None) + Fadd(Receptor=None, C8pro=None) | Receptor(Ligand=ANY, Fadd=1) % Fadd(Receptor=1, C8pro=None), bind_0_Receptor_binder_Fadd_binder_target_2kf, bind_0_Receptor_binder_Fadd_binder_target_1kr) Rule('substrate_binding_0_Fadd_catalyzer_C8pro_substrate', Fadd(Receptor=ANY, C8pro=None) + C8pro(Fadd=None, C6A=None) | Fadd(Receptor=ANY, C8pro=1) % C8pro(Fadd=1, C6A=None), substrate_binding_0_Fadd_catalyzer_C8pro_substrate_2kf, substrate_binding_0_Fadd_catalyzer_C8pro_substrate_1kr) Rule('catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product', Fadd(Receptor=ANY, C8pro=1) % C8pro(Fadd=1, C6A=None) >> Fadd(Receptor=ANY, C8pro=None) + C8A(BidU=None, C3pro=None), catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product_1kc) Rule('catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product', C8A(BidU=None, C3pro=None) + BidU(C8A=None) | C8A(BidU=1, C3pro=None) % BidU(C8A=1), catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_2kf, catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_1kr) Rule('catalysis_1_C8A_catalyzer_BidU_substrate_BidT_product', C8A(BidU=1, C3pro=None) % BidU(C8A=1) >> C8A(BidU=None, C3pro=None) + BidT(), catalysis_1_C8A_catalyzer_BidU_substrate_BidT_product_1kc) Rule('conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex', ApafI() + CytoCC() | ApafA(), conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_2kf, conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_1kr) Rule('inhibition_0_SmacC_inhibitor_Xiap_inh_target', SmacC(Xiap=None) + Xiap(SmacC=None, Apop=None, C3A=None) | SmacC(Xiap=1) % Xiap(SmacC=1, Apop=None, C3A=None), inhibition_0_SmacC_inhibitor_Xiap_inh_target_2kf, inhibition_0_SmacC_inhibitor_Xiap_inh_target_1kr) Rule('conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex', ApafA() + C9() | Apop(C3pro=None, Xiap=None), conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_2kf, conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_1kr) Rule('catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product', Apop(C3pro=None, Xiap=None) + C3pro(Apop=None, C8A=None) | Apop(C3pro=1, Xiap=None) % C3pro(Apop=1, C8A=None), catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_2kf, catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_1kr) Rule('catalysis_1_Apop_catalyzer_C3pro_substrate_C3A_product', Apop(C3pro=1, Xiap=None) % C3pro(Apop=1, C8A=None) >> Apop(C3pro=None, Xiap=None) + C3A(Xiap=None, ParpU=None, C6pro=None), catalysis_1_Apop_catalyzer_C3pro_substrate_C3A_product_1kc) Rule('inhibition_0_Xiap_inhibitor_Apop_inh_target', Xiap(SmacC=None, Apop=None, C3A=None) + Apop(C3pro=None, Xiap=None) | Xiap(SmacC=None, Apop=1, C3A=None) % Apop(C3pro=None, Xiap=1), inhibition_0_Xiap_inhibitor_Apop_inh_target_2kf, inhibition_0_Xiap_inhibitor_Apop_inh_target_1kr) Rule('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product', Xiap(SmacC=None, Apop=None, C3A=None) + C3A(Xiap=None, ParpU=None, C6pro=None) | Xiap(SmacC=None, Apop=None, C3A=1) % C3A(Xiap=1, ParpU=None, C6pro=None), catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_2kf, catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_1kr) Rule('catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product', Xiap(SmacC=None, Apop=None, C3A=1) % C3A(Xiap=1, ParpU=None, C6pro=None) >> Xiap(SmacC=None, Apop=None, C3A=None) + C3ub(), catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product_1kc) Rule('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product', C3A(Xiap=None, ParpU=None, C6pro=None) + ParpU(C3A=None) | C3A(Xiap=None, ParpU=1, C6pro=None) % ParpU(C3A=1), catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_2kf, catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_1kr) Rule('catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product', C3A(Xiap=None, ParpU=1, C6pro=None) % ParpU(C3A=1) >> C3A(Xiap=None, ParpU=None, C6pro=None) + ParpC(), catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product_1kc) Rule('equilibration_0_BidT_equil_a_BidM_equil_b', BidT() | BidM(BaxM=None), equilibration_0_BidT_equil_a_BidM_equil_b_1kf, equilibration_0_BidT_equil_a_BidM_equil_b_1kr) Rule('catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product', BidM(BaxM=None) + BaxM(BidM=None, BaxA=None) | BidM(BaxM=1) % BaxM(BidM=1, BaxA=None), catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_2kf, catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_1kr) Rule('catalysis_1_BidM_catalyzer_BaxM_substrate_BaxA_product', BidM(BaxM=1) % BaxM(BidM=1, BaxA=None) >> BidM(BaxM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None), catalysis_1_BidM_catalyzer_BaxM_substrate_BaxA_product_1kc) Rule('self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxM(BidM=None, BaxA=None) | BaxA(BaxM=1, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) % BaxM(BidM=None, BaxA=1), self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_2kf, self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_1kr) Rule('self_catalyze_1_BaxA_self_catalyzer_BaxM_self_substrate', BaxA(BaxM=1, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) % BaxM(BidM=None, BaxA=1) >> BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None), self_catalyze_1_BaxA_self_catalyzer_BaxM_self_substrate_1kc) Rule('pore_formation_0_BaxA_pore', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) | BaxA(BaxM=None, BaxA_1=None, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=None, SmacM=None, CytoCM=None), pore_formation_0_BaxA_pore_2kf, pore_formation_0_BaxA_pore_1kr) Rule('pore_formation_1_BaxA_pore', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=None, SmacM=None, CytoCM=None) | BaxA(BaxM=None, BaxA_1=3, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None), pore_formation_1_BaxA_pore_2kf, pore_formation_1_BaxA_pore_1kr) Rule('pore_formation_2_BaxA_pore', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, BaxA_1=3, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) | BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None), pore_formation_2_BaxA_pore_2kf, pore_formation_2_BaxA_pore_1kr) Rule('transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C', BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + SmacM(BaxA=None) | BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=5, CytoCM=None) % SmacM(BaxA=5), transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_2kf, transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kr) Rule('transport_1_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C', BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=5, CytoCM=None) % SmacM(BaxA=5) >> BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + SmacC(Xiap=None), transport_1_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kc) Rule('transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C', BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + CytoCM(BaxA=None) | BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=5) % CytoCM(BaxA=5), transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_2kf, transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kr) Rule('transport_1_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C', BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=5) % CytoCM(BaxA=5) >> BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + CytoCC(), transport_1_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kc) Rule('catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product', C8A(BidU=None, C3pro=None) + C3pro(Apop=None, C8A=None) | C8A(BidU=None, C3pro=1) % C3pro(Apop=None, C8A=1), catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_2kf, catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_1kr) Rule('catalysis_1_C8A_catalyzer_C3pro_substrate_C3A_product', C8A(BidU=None, C3pro=1) % C3pro(Apop=None, C8A=1) >> C8A(BidU=None, C3pro=None) + C3A(Xiap=None, ParpU=None, C6pro=None), catalysis_1_C8A_catalyzer_C3pro_substrate_C3A_product_1kc) Rule('catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product', C3A(Xiap=None, ParpU=None, C6pro=None) + C6pro(C3A=None) | C3A(Xiap=None, ParpU=None, C6pro=1) % C6pro(C3A=1), catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_2kf, catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_1kr) Rule('catalysis_1_C3A_catalyzer_C6pro_substrate_C6A_product', C3A(Xiap=None, ParpU=None, C6pro=1) % C6pro(C3A=1) >> C3A(Xiap=None, ParpU=None, C6pro=None) + C6A(C8pro=None), catalysis_1_C3A_catalyzer_C6pro_substrate_C6A_product_1kc) Rule('catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product', C6A(C8pro=None) + C8pro(Fadd=None, C6A=None) | C6A(C8pro=1) % C8pro(Fadd=None, C6A=1), catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_2kf, catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_1kr) Rule('catalysis_1_C6A_catalyzer_C8pro_substrate_C8A_product', C6A(C8pro=1) % C8pro(Fadd=None, C6A=1) >> C6A(C8pro=None) + C8A(BidU=None, C3pro=None), catalysis_1_C6A_catalyzer_C8pro_substrate_C8A_product_1kc) Initial(Ligand(Receptor=None), Ligand_0) Initial(ParpU(C3A=None), ParpU_0) Initial(C8A(BidU=None, C3pro=None), C8A_0) Initial(SmacM(BaxA=None), SmacM_0) Initial(BaxM(BidM=None, BaxA=None), BaxM_0) Initial(Apop(C3pro=None, Xiap=None), Apop_0) Initial(Fadd(Receptor=None, C8pro=None), Fadd_0) Initial(SmacC(Xiap=None), SmacC_0) Initial(ParpC(), ParpC_0) Initial(Xiap(SmacC=None, Apop=None, C3A=None), Xiap_0) Initial(C9(), C9_0) Initial(C3ub(), C3ub_0) Initial(C8pro(Fadd=None, C6A=None), C8pro_0) Initial(C6A(C8pro=None), C6A_0) Initial(C3pro(Apop=None, C8A=None), C3pro_0) Initial(CytoCM(BaxA=None), CytoCM_0) Initial(CytoCC(), CytoCC_0) Initial(BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None), BaxA_0) Initial(ApafI(), ApafI_0) Initial(BidU(C8A=None), BidU_0) Initial(BidT(), BidT_0) Initial(C3A(Xiap=None, ParpU=None, C6pro=None), C3A_0) Initial(ApafA(), ApafA_0) Initial(BidM(BaxM=None), BidM_0) Initial(Receptor(Ligand=None, Fadd=None), Receptor_0) Initial(C6pro(C3A=None), C6pro_0)
91.349515
710
0.806515
from pysb import Model, Monomer, Parameter, Expression, Compartment, Rule, Observable, Initial, MatchOnce, Annotation, ANY, WILD Model() Monomer('Ligand', ['Receptor']) Monomer('ParpU', ['C3A']) Monomer('C8A', ['BidU', 'C3pro']) Monomer('SmacM', ['BaxA']) Monomer('BaxM', ['BidM', 'BaxA']) Monomer('Apop', ['C3pro', 'Xiap']) Monomer('Fadd', ['Receptor', 'C8pro']) Monomer('SmacC', ['Xiap']) Monomer('ParpC') Monomer('Xiap', ['SmacC', 'Apop', 'C3A']) Monomer('C9') Monomer('C3ub') Monomer('C8pro', ['Fadd', 'C6A']) Monomer('C6A', ['C8pro']) Monomer('C3pro', ['Apop', 'C8A']) Monomer('CytoCM', ['BaxA']) Monomer('CytoCC') Monomer('BaxA', ['BaxM', 'BaxA_1', 'BaxA_2', 'SmacM', 'CytoCM']) Monomer('ApafI') Monomer('BidU', ['C8A']) Monomer('BidT') Monomer('C3A', ['Xiap', 'ParpU', 'C6pro']) Monomer('ApafA') Monomer('BidM', ['BaxM']) Monomer('Receptor', ['Ligand', 'Fadd']) Monomer('C6pro', ['C3A']) Parameter('bind_0_Ligand_binder_Receptor_binder_target_2kf', 1.0) Parameter('bind_0_Ligand_binder_Receptor_binder_target_1kr', 1.0) Parameter('bind_0_Receptor_binder_Fadd_binder_target_2kf', 1.0) Parameter('bind_0_Receptor_binder_Fadd_binder_target_1kr', 1.0) Parameter('substrate_binding_0_Fadd_catalyzer_C8pro_substrate_2kf', 1.0) Parameter('substrate_binding_0_Fadd_catalyzer_C8pro_substrate_1kr', 1.0) Parameter('catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product_1kc', 1.0) Parameter('catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_2kf', 1.0) Parameter('catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_1kr', 1.0) Parameter('catalysis_1_C8A_catalyzer_BidU_substrate_BidT_product_1kc', 1.0) Parameter('conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_2kf', 1.0) Parameter('conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_1kr', 1.0) Parameter('inhibition_0_SmacC_inhibitor_Xiap_inh_target_2kf', 1.0) Parameter('inhibition_0_SmacC_inhibitor_Xiap_inh_target_1kr', 1.0) Parameter('conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_2kf', 1.0) Parameter('conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_1kr', 1.0) Parameter('catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_2kf', 1.0) Parameter('catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_1kr', 1.0) Parameter('catalysis_1_Apop_catalyzer_C3pro_substrate_C3A_product_1kc', 1.0) Parameter('inhibition_0_Xiap_inhibitor_Apop_inh_target_2kf', 1.0) Parameter('inhibition_0_Xiap_inhibitor_Apop_inh_target_1kr', 1.0) Parameter('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_2kf', 1.0) Parameter('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_1kr', 1.0) Parameter('catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product_1kc', 1.0) Parameter('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_2kf', 1.0) Parameter('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_1kr', 1.0) Parameter('catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product_1kc', 1.0) Parameter('equilibration_0_BidT_equil_a_BidM_equil_b_1kf', 1.0) Parameter('equilibration_0_BidT_equil_a_BidM_equil_b_1kr', 1.0) Parameter('catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_2kf', 1.0) Parameter('catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_1kr', 1.0) Parameter('catalysis_1_BidM_catalyzer_BaxM_substrate_BaxA_product_1kc', 1.0) Parameter('self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_2kf', 1.0) Parameter('self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_1kr', 1.0) Parameter('self_catalyze_1_BaxA_self_catalyzer_BaxM_self_substrate_1kc', 1.0) Parameter('pore_formation_0_BaxA_pore_2kf', 1.0) Parameter('pore_formation_0_BaxA_pore_1kr', 1.0) Parameter('pore_formation_1_BaxA_pore_2kf', 1.0) Parameter('pore_formation_1_BaxA_pore_1kr', 1.0) Parameter('pore_formation_2_BaxA_pore_2kf', 1.0) Parameter('pore_formation_2_BaxA_pore_1kr', 1.0) Parameter('transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_2kf', 1.0) Parameter('transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kr', 1.0) Parameter('transport_1_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kc', 1.0) Parameter('transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_2kf', 1.0) Parameter('transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kr', 1.0) Parameter('transport_1_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kc', 1.0) Parameter('catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_2kf', 1.0) Parameter('catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_1kr', 1.0) Parameter('catalysis_1_C8A_catalyzer_C3pro_substrate_C3A_product_1kc', 1.0) Parameter('catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_2kf', 1.0) Parameter('catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_1kr', 1.0) Parameter('catalysis_1_C3A_catalyzer_C6pro_substrate_C6A_product_1kc', 1.0) Parameter('catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_2kf', 1.0) Parameter('catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_1kr', 1.0) Parameter('catalysis_1_C6A_catalyzer_C8pro_substrate_C8A_product_1kc', 1.0) Parameter('Ligand_0', 1000.0) Parameter('ParpU_0', 1000000.0) Parameter('C8A_0', 0.0) Parameter('SmacM_0', 100000.0) Parameter('BaxM_0', 40000.0) Parameter('Apop_0', 0.0) Parameter('Fadd_0', 130000.0) Parameter('SmacC_0', 0.0) Parameter('ParpC_0', 0.0) Parameter('Xiap_0', 22250.0) Parameter('C9_0', 100000.0) Parameter('C3ub_0', 0.0) Parameter('C8pro_0', 130000.0) Parameter('C6A_0', 0.0) Parameter('C3pro_0', 21000.0) Parameter('CytoCM_0', 500000.0) Parameter('CytoCC_0', 0.0) Parameter('BaxA_0', 0.0) Parameter('ApafI_0', 100000.0) Parameter('BidU_0', 171000.0) Parameter('BidT_0', 0.0) Parameter('C3A_0', 0.0) Parameter('ApafA_0', 0.0) Parameter('BidM_0', 0.0) Parameter('Receptor_0', 100.0) Parameter('C6pro_0', 100.0) Observable('Ligand_obs', Ligand()) Observable('ParpU_obs', ParpU()) Observable('C8A_obs', C8A()) Observable('SmacM_obs', SmacM()) Observable('BaxM_obs', BaxM()) Observable('Apop_obs', Apop()) Observable('Fadd_obs', Fadd()) Observable('SmacC_obs', SmacC()) Observable('ParpC_obs', ParpC()) Observable('Xiap_obs', Xiap()) Observable('C9_obs', C9()) Observable('C3ub_obs', C3ub()) Observable('C8pro_obs', C8pro()) Observable('C6A_obs', C6A()) Observable('C3pro_obs', C3pro()) Observable('CytoCM_obs', CytoCM()) Observable('CytoCC_obs', CytoCC()) Observable('BaxA_obs', BaxA()) Observable('ApafI_obs', ApafI()) Observable('BidU_obs', BidU()) Observable('BidT_obs', BidT()) Observable('C3A_obs', C3A()) Observable('ApafA_obs', ApafA()) Observable('BidM_obs', BidM()) Observable('Receptor_obs', Receptor()) Observable('C6pro_obs', C6pro()) Rule('bind_0_Ligand_binder_Receptor_binder_target', Ligand(Receptor=None) + Receptor(Ligand=None, Fadd=None) | Ligand(Receptor=1) % Receptor(Ligand=1, Fadd=None), bind_0_Ligand_binder_Receptor_binder_target_2kf, bind_0_Ligand_binder_Receptor_binder_target_1kr) Rule('bind_0_Receptor_binder_Fadd_binder_target', Receptor(Ligand=ANY, Fadd=None) + Fadd(Receptor=None, C8pro=None) | Receptor(Ligand=ANY, Fadd=1) % Fadd(Receptor=1, C8pro=None), bind_0_Receptor_binder_Fadd_binder_target_2kf, bind_0_Receptor_binder_Fadd_binder_target_1kr) Rule('substrate_binding_0_Fadd_catalyzer_C8pro_substrate', Fadd(Receptor=ANY, C8pro=None) + C8pro(Fadd=None, C6A=None) | Fadd(Receptor=ANY, C8pro=1) % C8pro(Fadd=1, C6A=None), substrate_binding_0_Fadd_catalyzer_C8pro_substrate_2kf, substrate_binding_0_Fadd_catalyzer_C8pro_substrate_1kr) Rule('catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product', Fadd(Receptor=ANY, C8pro=1) % C8pro(Fadd=1, C6A=None) >> Fadd(Receptor=ANY, C8pro=None) + C8A(BidU=None, C3pro=None), catalytic_step_0_Fadd_catalyzer_C8pro_substrate_C8A_product_1kc) Rule('catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product', C8A(BidU=None, C3pro=None) + BidU(C8A=None) | C8A(BidU=1, C3pro=None) % BidU(C8A=1), catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_2kf, catalysis_0_C8A_catalyzer_BidU_substrate_BidT_product_1kr) Rule('catalysis_1_C8A_catalyzer_BidU_substrate_BidT_product', C8A(BidU=1, C3pro=None) % BidU(C8A=1) >> C8A(BidU=None, C3pro=None) + BidT(), catalysis_1_C8A_catalyzer_BidU_substrate_BidT_product_1kc) Rule('conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex', ApafI() + CytoCC() | ApafA(), conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_2kf, conversion_0_CytoCC_subunit_d_ApafI_subunit_c_ApafA_complex_1kr) Rule('inhibition_0_SmacC_inhibitor_Xiap_inh_target', SmacC(Xiap=None) + Xiap(SmacC=None, Apop=None, C3A=None) | SmacC(Xiap=1) % Xiap(SmacC=1, Apop=None, C3A=None), inhibition_0_SmacC_inhibitor_Xiap_inh_target_2kf, inhibition_0_SmacC_inhibitor_Xiap_inh_target_1kr) Rule('conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex', ApafA() + C9() | Apop(C3pro=None, Xiap=None), conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_2kf, conversion_0_C9_subunit_d_ApafA_subunit_c_Apop_complex_1kr) Rule('catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product', Apop(C3pro=None, Xiap=None) + C3pro(Apop=None, C8A=None) | Apop(C3pro=1, Xiap=None) % C3pro(Apop=1, C8A=None), catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_2kf, catalysis_0_Apop_catalyzer_C3pro_substrate_C3A_product_1kr) Rule('catalysis_1_Apop_catalyzer_C3pro_substrate_C3A_product', Apop(C3pro=1, Xiap=None) % C3pro(Apop=1, C8A=None) >> Apop(C3pro=None, Xiap=None) + C3A(Xiap=None, ParpU=None, C6pro=None), catalysis_1_Apop_catalyzer_C3pro_substrate_C3A_product_1kc) Rule('inhibition_0_Xiap_inhibitor_Apop_inh_target', Xiap(SmacC=None, Apop=None, C3A=None) + Apop(C3pro=None, Xiap=None) | Xiap(SmacC=None, Apop=1, C3A=None) % Apop(C3pro=None, Xiap=1), inhibition_0_Xiap_inhibitor_Apop_inh_target_2kf, inhibition_0_Xiap_inhibitor_Apop_inh_target_1kr) Rule('catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product', Xiap(SmacC=None, Apop=None, C3A=None) + C3A(Xiap=None, ParpU=None, C6pro=None) | Xiap(SmacC=None, Apop=None, C3A=1) % C3A(Xiap=1, ParpU=None, C6pro=None), catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_2kf, catalysis_0_Xiap_catalyzer_C3A_substrate_C3ub_product_1kr) Rule('catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product', Xiap(SmacC=None, Apop=None, C3A=1) % C3A(Xiap=1, ParpU=None, C6pro=None) >> Xiap(SmacC=None, Apop=None, C3A=None) + C3ub(), catalysis_1_Xiap_catalyzer_C3A_substrate_C3ub_product_1kc) Rule('catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product', C3A(Xiap=None, ParpU=None, C6pro=None) + ParpU(C3A=None) | C3A(Xiap=None, ParpU=1, C6pro=None) % ParpU(C3A=1), catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_2kf, catalysis_0_C3A_catalyzer_ParpU_substrate_ParpC_product_1kr) Rule('catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product', C3A(Xiap=None, ParpU=1, C6pro=None) % ParpU(C3A=1) >> C3A(Xiap=None, ParpU=None, C6pro=None) + ParpC(), catalysis_1_C3A_catalyzer_ParpU_substrate_ParpC_product_1kc) Rule('equilibration_0_BidT_equil_a_BidM_equil_b', BidT() | BidM(BaxM=None), equilibration_0_BidT_equil_a_BidM_equil_b_1kf, equilibration_0_BidT_equil_a_BidM_equil_b_1kr) Rule('catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product', BidM(BaxM=None) + BaxM(BidM=None, BaxA=None) | BidM(BaxM=1) % BaxM(BidM=1, BaxA=None), catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_2kf, catalysis_0_BidM_catalyzer_BaxM_substrate_BaxA_product_1kr) Rule('catalysis_1_BidM_catalyzer_BaxM_substrate_BaxA_product', BidM(BaxM=1) % BaxM(BidM=1, BaxA=None) >> BidM(BaxM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None), catalysis_1_BidM_catalyzer_BaxM_substrate_BaxA_product_1kc) Rule('self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxM(BidM=None, BaxA=None) | BaxA(BaxM=1, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) % BaxM(BidM=None, BaxA=1), self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_2kf, self_catalyze_0_BaxA_self_catalyzer_BaxM_self_substrate_1kr) Rule('self_catalyze_1_BaxA_self_catalyzer_BaxM_self_substrate', BaxA(BaxM=1, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) % BaxM(BidM=None, BaxA=1) >> BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None), self_catalyze_1_BaxA_self_catalyzer_BaxM_self_substrate_1kc) Rule('pore_formation_0_BaxA_pore', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) | BaxA(BaxM=None, BaxA_1=None, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=None, SmacM=None, CytoCM=None), pore_formation_0_BaxA_pore_2kf, pore_formation_0_BaxA_pore_1kr) Rule('pore_formation_1_BaxA_pore', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, BaxA_1=None, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=None, SmacM=None, CytoCM=None) | BaxA(BaxM=None, BaxA_1=3, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None), pore_formation_1_BaxA_pore_2kf, pore_formation_1_BaxA_pore_1kr) Rule('pore_formation_2_BaxA_pore', BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None) + BaxA(BaxM=None, BaxA_1=3, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) | BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None), pore_formation_2_BaxA_pore_2kf, pore_formation_2_BaxA_pore_1kr) Rule('transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C', BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + SmacM(BaxA=None) | BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=5, CytoCM=None) % SmacM(BaxA=5), transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_2kf, transport_0_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kr) Rule('transport_1_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C', BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=5, CytoCM=None) % SmacM(BaxA=5) >> BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + SmacC(Xiap=None), transport_1_BaxA_pore_SmacM_cargo_M_SmacC_cargo_C_1kc) Rule('transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C', BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + CytoCM(BaxA=None) | BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=5) % CytoCM(BaxA=5), transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_2kf, transport_0_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kr) Rule('transport_1_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C', BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=5) % CytoCM(BaxA=5) >> BaxA(BaxM=None, BaxA_1=4, BaxA_2=1, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=1, BaxA_2=2, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=2, BaxA_2=3, SmacM=None, CytoCM=None) % BaxA(BaxM=None, BaxA_1=3, BaxA_2=4, SmacM=None, CytoCM=None) + CytoCC(), transport_1_BaxA_pore_CytoCM_cargo_M_CytoCC_cargo_C_1kc) Rule('catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product', C8A(BidU=None, C3pro=None) + C3pro(Apop=None, C8A=None) | C8A(BidU=None, C3pro=1) % C3pro(Apop=None, C8A=1), catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_2kf, catalysis_0_C8A_catalyzer_C3pro_substrate_C3A_product_1kr) Rule('catalysis_1_C8A_catalyzer_C3pro_substrate_C3A_product', C8A(BidU=None, C3pro=1) % C3pro(Apop=None, C8A=1) >> C8A(BidU=None, C3pro=None) + C3A(Xiap=None, ParpU=None, C6pro=None), catalysis_1_C8A_catalyzer_C3pro_substrate_C3A_product_1kc) Rule('catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product', C3A(Xiap=None, ParpU=None, C6pro=None) + C6pro(C3A=None) | C3A(Xiap=None, ParpU=None, C6pro=1) % C6pro(C3A=1), catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_2kf, catalysis_0_C3A_catalyzer_C6pro_substrate_C6A_product_1kr) Rule('catalysis_1_C3A_catalyzer_C6pro_substrate_C6A_product', C3A(Xiap=None, ParpU=None, C6pro=1) % C6pro(C3A=1) >> C3A(Xiap=None, ParpU=None, C6pro=None) + C6A(C8pro=None), catalysis_1_C3A_catalyzer_C6pro_substrate_C6A_product_1kc) Rule('catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product', C6A(C8pro=None) + C8pro(Fadd=None, C6A=None) | C6A(C8pro=1) % C8pro(Fadd=None, C6A=1), catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_2kf, catalysis_0_C6A_catalyzer_C8pro_substrate_C8A_product_1kr) Rule('catalysis_1_C6A_catalyzer_C8pro_substrate_C8A_product', C6A(C8pro=1) % C8pro(Fadd=None, C6A=1) >> C6A(C8pro=None) + C8A(BidU=None, C3pro=None), catalysis_1_C6A_catalyzer_C8pro_substrate_C8A_product_1kc) Initial(Ligand(Receptor=None), Ligand_0) Initial(ParpU(C3A=None), ParpU_0) Initial(C8A(BidU=None, C3pro=None), C8A_0) Initial(SmacM(BaxA=None), SmacM_0) Initial(BaxM(BidM=None, BaxA=None), BaxM_0) Initial(Apop(C3pro=None, Xiap=None), Apop_0) Initial(Fadd(Receptor=None, C8pro=None), Fadd_0) Initial(SmacC(Xiap=None), SmacC_0) Initial(ParpC(), ParpC_0) Initial(Xiap(SmacC=None, Apop=None, C3A=None), Xiap_0) Initial(C9(), C9_0) Initial(C3ub(), C3ub_0) Initial(C8pro(Fadd=None, C6A=None), C8pro_0) Initial(C6A(C8pro=None), C6A_0) Initial(C3pro(Apop=None, C8A=None), C3pro_0) Initial(CytoCM(BaxA=None), CytoCM_0) Initial(CytoCC(), CytoCC_0) Initial(BaxA(BaxM=None, BaxA_1=None, BaxA_2=None, SmacM=None, CytoCM=None), BaxA_0) Initial(ApafI(), ApafI_0) Initial(BidU(C8A=None), BidU_0) Initial(BidT(), BidT_0) Initial(C3A(Xiap=None, ParpU=None, C6pro=None), C3A_0) Initial(ApafA(), ApafA_0) Initial(BidM(BaxM=None), BidM_0) Initial(Receptor(Ligand=None, Fadd=None), Receptor_0) Initial(C6pro(C3A=None), C6pro_0)
true
true
f72a759aa3a375cf215b4b215a8f91d36710c4d8
316
py
Python
checkv/__init__.py
wolfQK/CheckV-fork
3519bf4bf07fb73806225946a5629ddc542b4252
[ "BSD-3-Clause-LBNL" ]
null
null
null
checkv/__init__.py
wolfQK/CheckV-fork
3519bf4bf07fb73806225946a5629ddc542b4252
[ "BSD-3-Clause-LBNL" ]
null
null
null
checkv/__init__.py
wolfQK/CheckV-fork
3519bf4bf07fb73806225946a5629ddc542b4252
[ "BSD-3-Clause-LBNL" ]
null
null
null
from checkv.modules import ( download_database, update_database, contamination, completeness, complete_genomes, quality_summary, end_to_end, ) try: from importlib import metadata except ImportError: import importlib_metadata as metadata __version__ = metadata.version("checkv")
18.588235
41
0.740506
from checkv.modules import ( download_database, update_database, contamination, completeness, complete_genomes, quality_summary, end_to_end, ) try: from importlib import metadata except ImportError: import importlib_metadata as metadata __version__ = metadata.version("checkv")
true
true
f72a75e5797e4be5ac376e8272c48fbbb2970c1a
126
py
Python
incomevis/utils/__init__.py
hieumtran/incomevis
90adca62803f767d7c96fc879e662d934dcf9123
[ "MIT" ]
null
null
null
incomevis/utils/__init__.py
hieumtran/incomevis
90adca62803f767d7c96fc879e662d934dcf9123
[ "MIT" ]
null
null
null
incomevis/utils/__init__.py
hieumtran/incomevis
90adca62803f767d7c96fc879e662d934dcf9123
[ "MIT" ]
null
null
null
from .getColor import * from .getDecile import * from .getPercentile import * from .getStateName import * from .path import *
21
28
0.761905
from .getColor import * from .getDecile import * from .getPercentile import * from .getStateName import * from .path import *
true
true
f72a7713a14d8330970b9d00cd1d55249c858748
2,944
py
Python
defusekit/mods/complicatedwires.py
Floozutter/defuse-kit
ef43450f93f71df6a563783da93fdefd45e0c82b
[ "Unlicense" ]
1
2020-01-15T03:57:25.000Z
2020-01-15T03:57:25.000Z
defusekit/mods/complicatedwires.py
Floozutter/defuse-kit
ef43450f93f71df6a563783da93fdefd45e0c82b
[ "Unlicense" ]
3
2019-11-26T00:23:21.000Z
2019-11-29T19:07:56.000Z
defusekit/mods/complicatedwires.py
Floozutter/defuse-kit
ef43450f93f71df6a563783da93fdefd45e0c82b
[ "Unlicense" ]
null
null
null
NAME = "complicated-wires" import curses from defusekit import wards from defusekit.kittypes import Window def get_instruction(red: bool, blue: bool, star: bool, led: bool) -> str: binstr = "".join(["1" if b else "0" for b in (red, blue, star, led)]) wirestate = int(binstr, 2) C = "Cut the wire" D = "Do not cut the wire" S = "Cut the wire if serial number's last digit is even" P = "Cut the wire if the bomb has a parallel port" B = "Cut the wire if the bomb has 2 or more batteries" INSTRUCTIONS = { 0b0000 : C, 0b0001 : D, 0b0010 : C, 0b0011 : B, 0b0100 : S, 0b0101 : P, 0b0110 : D, 0b0111 : P, 0b1000 : S, 0b1001 : B, 0b1010 : C, 0b1011 : B, 0b1100 : S, 0b1101 : S, 0b1110 : P, 0b1111 : D } return INSTRUCTIONS[wirestate] def main(scr: Window): wards.setup(scr) wards.print_modulename(scr, NAME) wards.print_controls(scr, ( ("ESC", "Quit the module."), ("Q/W/E/R", "Toggle wire options."), ("TAB", "Reset all wire options to NO.") )) scr.addstr("Wire Settings:", curses.color_pair(0)) setting_keys = ("Q", "W", "E", "R") setting_labels = ( "Has Red coloring", "Has Blue coloring", "Has Star symbol", "Has LED lit" ) setting_states = [False, False, False, False] setting_yxs = [] for i in range(4): scr.addstr("\n") scr.addstr((setting_keys[i]+" - ").rjust(6)) scr.addstr(setting_labels[i].ljust(18), curses.color_pair(0)) scr.addstr(": ", curses.color_pair(0)) setting_yxs.append(scr.getyx()) scr.addstr("\n\n") scr.addstr("Instruction: ") instruction_yx = scr.getyx() while True: # Show setting states for i in range(4): scr.move(setting_yxs[i][0], setting_yxs[i][1]) scr.clrtoeol() if setting_states[i]: scr.addstr("YES", curses.color_pair(2)) else: scr.addstr("NO", curses.color_pair(1)) # Show instruction scr.move(instruction_yx[0], instruction_yx[1]) scr.clrtoeol() scr.addstr(get_instruction( setting_states[0], setting_states[1], setting_states[2], setting_states[3] )) # Get input c = scr.getch() if c == 27: # Esc return elif c == 9: # Tab setting_states = [False, False, False, False] elif c in (81, 113): # Q setting_states[0] = not setting_states[0] elif c in (87, 119): # W setting_states[1] = not setting_states[1] elif c in (69, 101): # E setting_states[2] = not setting_states[2] elif c in (82, 114): # R setting_states[3] = not setting_states[3]
29.737374
73
0.53159
NAME = "complicated-wires" import curses from defusekit import wards from defusekit.kittypes import Window def get_instruction(red: bool, blue: bool, star: bool, led: bool) -> str: binstr = "".join(["1" if b else "0" for b in (red, blue, star, led)]) wirestate = int(binstr, 2) C = "Cut the wire" D = "Do not cut the wire" S = "Cut the wire if serial number's last digit is even" P = "Cut the wire if the bomb has a parallel port" B = "Cut the wire if the bomb has 2 or more batteries" INSTRUCTIONS = { 0b0000 : C, 0b0001 : D, 0b0010 : C, 0b0011 : B, 0b0100 : S, 0b0101 : P, 0b0110 : D, 0b0111 : P, 0b1000 : S, 0b1001 : B, 0b1010 : C, 0b1011 : B, 0b1100 : S, 0b1101 : S, 0b1110 : P, 0b1111 : D } return INSTRUCTIONS[wirestate] def main(scr: Window): wards.setup(scr) wards.print_modulename(scr, NAME) wards.print_controls(scr, ( ("ESC", "Quit the module."), ("Q/W/E/R", "Toggle wire options."), ("TAB", "Reset all wire options to NO.") )) scr.addstr("Wire Settings:", curses.color_pair(0)) setting_keys = ("Q", "W", "E", "R") setting_labels = ( "Has Red coloring", "Has Blue coloring", "Has Star symbol", "Has LED lit" ) setting_states = [False, False, False, False] setting_yxs = [] for i in range(4): scr.addstr("\n") scr.addstr((setting_keys[i]+" - ").rjust(6)) scr.addstr(setting_labels[i].ljust(18), curses.color_pair(0)) scr.addstr(": ", curses.color_pair(0)) setting_yxs.append(scr.getyx()) scr.addstr("\n\n") scr.addstr("Instruction: ") instruction_yx = scr.getyx() while True: # Show setting states for i in range(4): scr.move(setting_yxs[i][0], setting_yxs[i][1]) scr.clrtoeol() if setting_states[i]: scr.addstr("YES", curses.color_pair(2)) else: scr.addstr("NO", curses.color_pair(1)) # Show instruction scr.move(instruction_yx[0], instruction_yx[1]) scr.clrtoeol() scr.addstr(get_instruction( setting_states[0], setting_states[1], setting_states[2], setting_states[3] )) # Get input c = scr.getch() if c == 27: # Esc return elif c == 9: # Tab setting_states = [False, False, False, False] elif c in (81, 113): # Q setting_states[0] = not setting_states[0] elif c in (87, 119): # W setting_states[1] = not setting_states[1] elif c in (69, 101): # E setting_states[2] = not setting_states[2] elif c in (82, 114): # R setting_states[3] = not setting_states[3]
true
true
f72a784ed40b4a7d44700220e01f993eed20a5e0
1,277
py
Python
Problem 4.py
SuhelMehta9/Project-Euler
dbb06103ea702a137bce4e8644aa07d8913b8bd6
[ "Unlicense" ]
null
null
null
Problem 4.py
SuhelMehta9/Project-Euler
dbb06103ea702a137bce4e8644aa07d8913b8bd6
[ "Unlicense" ]
null
null
null
Problem 4.py
SuhelMehta9/Project-Euler
dbb06103ea702a137bce4e8644aa07d8913b8bd6
[ "Unlicense" ]
null
null
null
# Problem 4: Largest palindrome product # A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. # Find the largest palindrome made from the product of two 3-digit numbers. num = 999 # Numbers start from 999 num2 = 999 palindrome = [] # Store palindrome numbers while num != 99: # We only require 3 digit numbers so if a 2 digit number appears then loop will stop while num2 != 99: # Same with this loop also result = num*num2 # Multiplying each number orignal = result # It will be use to check palindrome number result = str(result) # It is easy to convert string to list result= list(result) result.reverse() # Reverse the number result = ''.join(result) # Convert list to string result = int(result) # Convert list to integer if result == orignal: # if number is palindrome palindrome.append(orignal) # Store the number to list(palindrome) num2 = num2-1 #decrement the number num2 = 999 # When first number is decrreased by one then the value of other number must be 999 to get the desired result num = num - 1 # decrease the number print(max(palindrome)) # Print the largest palindrome number
55.521739
135
0.696163
num = 999 num2 = 999 palindrome = [] while num != 99: while num2 != 99: result = num*num2 orignal = result result = str(result) result= list(result) result.reverse() result = ''.join(result) result = int(result) if result == orignal: palindrome.append(orignal) num2 = num2-1 num2 = 999 num = num - 1 print(max(palindrome))
true
true
f72a78f9746119f4da8555bf50e0ea8d48a5abbe
13,660
py
Python
hiddenlayer/graph.py
pyjhzwh/hiddenlayer
59f84299986d9aed7e0534147a87f7dd491ab08d
[ "MIT" ]
null
null
null
hiddenlayer/graph.py
pyjhzwh/hiddenlayer
59f84299986d9aed7e0534147a87f7dd491ab08d
[ "MIT" ]
null
null
null
hiddenlayer/graph.py
pyjhzwh/hiddenlayer
59f84299986d9aed7e0534147a87f7dd491ab08d
[ "MIT" ]
null
null
null
""" HiddenLayer Implementation of the Graph class. A framework independent directed graph to represent a neural network. Written by Waleed Abdulla. Additions by Phil Ferriere. Licensed under the MIT License """ from __future__ import absolute_import, division, print_function import os import re from random import getrandbits import inspect import numpy as np THEMES = { "basic": { "background_color": "#FFFFFF", "fill_color": "#E8E8E8", "outline_color": "#000000", "font_color": "#000000", "font_name": "Times", "font_size": "10", "margin": "0,0", "padding": "1.0,0.5", }, "blue": { "background_color": "#FFFFFF", "fill_color": "#BCD6FC", "outline_color": "#7C96BC", "font_color": "#202020", "font_name": "Verdana", "font_size": "10", "margin": "0,0", "padding": "1.0,0.5", }, } ########################################################################### # Utility Functions ########################################################################### def detect_framework(value): # Get all base classes classes = inspect.getmro(value.__class__) for c in classes: if c.__module__.startswith("torch"): return "torch" elif c.__module__.startswith("tensorflow"): return "tensorflow" ########################################################################### # Node ########################################################################### class Node(): """Represents a framework-agnostic neural network layer in a directed graph.""" def __init__(self, uid, name, op, output_shape=None, params=None): """ uid: unique ID for the layer that doesn't repeat in the computation graph. name: Name to display op: Framework-agnostic operation name. """ self.id = uid self.name = name # TODO: clarify the use of op vs name vs title self.op = op self.repeat = 1 if output_shape: assert isinstance(output_shape, (tuple, list)),\ "output_shape must be a tuple or list but received {}".format(type(output_shape)) self.output_shape = output_shape self.params = params if params else {} self._caption = "" @property def title(self): # Default title = self.name or self.op if "kernel_shape" in self.params: # Kernel kernel = self.params["kernel_shape"] title += "x".join(map(str, kernel)) if "stride" in self.params: stride = self.params["stride"] if np.unique(stride).size == 1: stride = stride[0] if stride != 1: title += "/s{}".format(str(stride)) # # Transposed # if node.transposed: # name = "Transposed" + name return title @property def caption(self): if self._caption: return self._caption caption = "" # Stride # if "stride" in self.params: # stride = self.params["stride"] # if np.unique(stride).size == 1: # stride = stride[0] # if stride != 1: # caption += "/{}".format(str(stride)) return caption def __repr__(self): args = (self.op, self.name, self.id, self.title, self.repeat) f = "<Node: op: {}, name: {}, id: {}, title: {}, repeat: {}" if self.output_shape: args += (str(self.output_shape),) f += ", shape: {:}" if self.params: args += (str(self.params),) f += ", params: {:}" f += ">" return f.format(*args) ########################################################################### # Graph ########################################################################### def build_graph(model=None, args=None, input_names=None, transforms="default", framework_transforms="default"): # Initialize an empty graph g = Graph() # Detect framwork framework = detect_framework(model) if framework == "torch": from .pytorch_builder import import_graph, FRAMEWORK_TRANSFORMS assert args is not None, "Argument args must be provided for Pytorch models." import_graph(g, model, args) elif framework == "tensorflow": from .tf_builder import import_graph, FRAMEWORK_TRANSFORMS import_graph(g, model) else: raise ValueError("`model` input param must be a PyTorch, TensorFlow, or Keras-with-TensorFlow-backend model.") # Apply Transforms if framework_transforms: if framework_transforms == "default": framework_transforms = FRAMEWORK_TRANSFORMS for t in framework_transforms: g = t.apply(g) if transforms: if transforms == "default": from .transforms import SIMPLICITY_TRANSFORMS transforms = SIMPLICITY_TRANSFORMS for t in transforms: g = t.apply(g) return g class Graph(): """Tracks nodes and edges of a directed graph and supports basic operations on them.""" def __init__(self, model=None, args=None, input_names=None, transforms="default", framework_transforms="default", meaningful_ids=False): self.nodes = {} self.edges = [] self.meaningful_ids = meaningful_ids # TODO self.theme = THEMES["basic"] if model: # Detect framwork framework = detect_framework(model) if framework == "torch": from .pytorch_builder import import_graph, FRAMEWORK_TRANSFORMS assert args is not None, "Argument args must be provided for Pytorch models." import_graph(self, model, args) elif framework == "tensorflow": from .tf_builder import import_graph, FRAMEWORK_TRANSFORMS import_graph(self, model) # Apply Transforms if framework_transforms: if framework_transforms == "default": framework_transforms = FRAMEWORK_TRANSFORMS for t in framework_transforms: t.apply(self) if transforms: if transforms == "default": from .transforms import SIMPLICITY_TRANSFORMS transforms = SIMPLICITY_TRANSFORMS for t in transforms: t.apply(self) def id(self, node): """Returns a unique node identifier. If the node has an id attribute (preferred), it's used. Otherwise, the hash() is returned.""" return node.id if hasattr(node, "id") else hash(node) def add_node(self, node): id = self.id(node) # assert(id not in self.nodes) self.nodes[id] = node def add_edge(self, node1, node2, label=None): # If the edge is already present, don't add it again. # TODO: If an edge exists with a different label, still don't add it again. edge = (self.id(node1), self.id(node2), label) if edge not in self.edges: self.edges.append(edge) def add_edge_by_id(self, vid1, vid2, label=None): self.edges.append((vid1, vid2, label)) def outgoing(self, node): """Returns nodes connecting out of the given node (or list of nodes).""" nodes = node if isinstance(node, list) else [node] node_ids = [self.id(n) for n in nodes] # Find edges outgoing from this group but not incoming to it outgoing = [self[e[1]] for e in self.edges if e[0] in node_ids and e[1] not in node_ids] return outgoing def incoming(self, node): """Returns nodes connecting to the given node (or list of nodes).""" nodes = node if isinstance(node, list) else [node] node_ids = [self.id(n) for n in nodes] # Find edges incoming to this group but not outgoing from it incoming = [self[e[0]] for e in self.edges if e[1] in node_ids and e[0] not in node_ids] return incoming def siblings(self, node): """Returns all nodes that share the same parent (incoming node) with the given node, including the node itself. """ incoming = self.incoming(node) # TODO: Not handling the case of multiple incoming nodes yet if len(incoming) == 1: incoming = incoming[0] siblings = self.outgoing(incoming) return siblings else: return [node] def __getitem__(self, key): if isinstance(key, list): return [self.nodes.get(k) for k in key] else: return self.nodes.get(key) def remove(self, nodes): """Remove a node and its edges.""" nodes = nodes if isinstance(nodes, list) else [nodes] for node in nodes: k = self.id(node) self.edges = list(filter(lambda e: e[0] != k and e[1] != k, self.edges)) del self.nodes[k] def replace(self, nodes, node): """Replace nodes with node. Edges incoming to nodes[0] are connected to the new node, and nodes outgoing from nodes[-1] become outgoing from the new node.""" nodes = nodes if isinstance(nodes, list) else [nodes] # Is the new node part of the replace nodes (i.e. want to collapse # a group of nodes into one of them)? collapse = self.id(node) in self.nodes # Add new node and edges if not collapse: self.add_node(node) for in_node in self.incoming(nodes): # TODO: check specifically for output_shape is not generic. Consider refactoring. self.add_edge(in_node, node, in_node.output_shape if hasattr(in_node, "output_shape") else None) for out_node in self.outgoing(nodes): self.add_edge(node, out_node, node.output_shape if hasattr(node, "output_shape") else None) # Remove the old nodes for n in nodes: if collapse and n == node: continue self.remove(n) def search(self, pattern): """Searches the graph for a sub-graph that matches the given pattern and returns the first match it finds. """ for node in self.nodes.values(): match, following = pattern.match(self, node) if match: return match, following return [], None def sequence_id(self, sequence): """Make up an ID for a sequence (list) of nodes. Note: `getrandbits()` is very uninformative as a "readable" ID. Here, we build a name such that when the mouse hovers over the drawn node in Jupyter, one can figure out which original nodes make up the sequence. This is actually quite useful. """ if self.meaningful_ids: # TODO: This might fail if the ID becomes too long return "><".join([node.id for node in sequence]) else: return getrandbits(64) def build_dot(self): """Generate a GraphViz Dot graph. Returns a GraphViz Digraph object. """ from graphviz import Digraph # Build GraphViz Digraph dot = Digraph() dot.attr("graph", bgcolor=self.theme["background_color"], color=self.theme["outline_color"], fontsize=self.theme["font_size"], fontcolor=self.theme["font_color"], fontname=self.theme["font_name"], margin=self.theme["margin"], rankdir="LR", pad=self.theme["padding"]) dot.attr("node", shape="box", style="filled", margin="0,0", fillcolor=self.theme["fill_color"], color=self.theme["outline_color"], fontsize=self.theme["font_size"], fontcolor=self.theme["font_color"], fontname=self.theme["font_name"]) dot.attr("edge", style="solid", color=self.theme["outline_color"], fontsize=self.theme["font_size"], fontcolor=self.theme["font_color"], fontname=self.theme["font_name"]) for k, n in self.nodes.items(): label = "<tr><td cellpadding='6'>{}</td></tr>".format(n.title) if n.caption: label += "<tr><td>{}</td></tr>".format(n.caption) if n.repeat > 1: label += "<tr><td align='right' cellpadding='2'>x{}</td></tr>".format(n.repeat) label = "<<table border='0' cellborder='0' cellpadding='0'>" + label + "</table>>" dot.node(str(k), label) for a, b, label in self.edges: if isinstance(label, (list, tuple)): label = "x".join([str(l or "?") for l in label]) dot.edge(str(a), str(b), label) return dot def _repr_svg_(self): """Allows Jupyter notebook to render the graph automatically.""" return self.build_dot()._repr_image_svg_xml() def save(self, path, format="pdf"): # TODO: assert on acceptable format values dot = self.build_dot() dot.format = format directory, file_name = os.path.split(path) # Remove extension from file name. dot.render() adds it. file_name = file_name.replace("." + format, "") dot.render(file_name, directory=directory, cleanup=True)
37.01897
119
0.553075
from __future__ import absolute_import, division, print_function import os import re from random import getrandbits import inspect import numpy as np THEMES = { "basic": { "background_color": "#FFFFFF", "fill_color": "#E8E8E8", "outline_color": "#000000", "font_color": "#000000", "font_name": "Times", "font_size": "10", "margin": "0,0", "padding": "1.0,0.5", }, "blue": { "background_color": "#FFFFFF", "fill_color": "#BCD6FC", "outline_color": "#7C96BC", "font_color": "#202020", "font_name": "Verdana", "font_size": "10", "margin": "0,0", "padding": "1.0,0.5", }, }
true
true
f72a79a9ba5f4c1690d21261e6cc829e1ab1cdfe
17,260
py
Python
scripts/greaseweazle/usb.py
zxrepo/keirf.Greaseweazle
a023ad364eb813856bb6632da87cde7e513d73d1
[ "Unlicense" ]
1
2022-03-05T14:50:48.000Z
2022-03-05T14:50:48.000Z
scripts/greaseweazle/usb.py
zxrepo/keirf.Greaseweazle
a023ad364eb813856bb6632da87cde7e513d73d1
[ "Unlicense" ]
null
null
null
scripts/greaseweazle/usb.py
zxrepo/keirf.Greaseweazle
a023ad364eb813856bb6632da87cde7e513d73d1
[ "Unlicense" ]
null
null
null
# greaseweazle/usb.py # # Written & released by Keir Fraser <keir.xen@gmail.com> # # This is free and unencumbered software released into the public domain. # See the file COPYING for more details, or visit <http://unlicense.org>. import struct import itertools as it from greaseweazle import version from greaseweazle import error from greaseweazle.flux import Flux ## Control-Path command set class ControlCmd: ClearComms = 10000 Normal = 9600 ## Command set class Cmd: GetInfo = 0 Update = 1 Seek = 2 Side = 3 SetParams = 4 GetParams = 5 Motor = 6 ReadFlux = 7 WriteFlux = 8 GetFluxStatus = 9 GetIndexTimes = 10 SwitchFwMode = 11 Select = 12 Deselect = 13 SetBusType = 14 SetPin = 15 Reset = 16 EraseFlux = 17 SourceBytes = 18 SinkBytes = 19 str = { GetInfo: "GetInfo", Update: "Update", Seek: "Seek", Side: "Side", SetParams: "SetParams", GetParams: "GetParams", Motor: "Motor", ReadFlux: "ReadFlux", WriteFlux: "WriteFlux", GetFluxStatus: "GetFluxStatus", GetIndexTimes: "GetIndexTimes", SwitchFwMode: "SwitchFwMode", Select: "Select", Deselect: "Deselect", SetBusType: "SetBusType", SetPin: "SetPin", Reset: "Reset", EraseFlux: "EraseFlux", SourceBytes: "SourceBytes", SinkBytes: "SinkBytes" } ## Command responses/acknowledgements class Ack: Okay = 0 BadCommand = 1 NoIndex = 2 NoTrk0 = 3 FluxOverflow = 4 FluxUnderflow = 5 Wrprot = 6 NoUnit = 7 NoBus = 8 BadUnit = 9 BadPin = 10 BadCylinder = 11 str = { Okay: "Okay", BadCommand: "Bad Command", NoIndex: "No Index", NoTrk0: "Track 0 not found", FluxOverflow: "Flux Overflow", FluxUnderflow: "Flux Underflow", Wrprot: "Disk is Write Protected", NoUnit: "No drive unit selected", NoBus: "No bus type (eg. Shugart, IBM/PC) specified", BadUnit: "Invalid unit number", BadPin: "Not a modifiable pin", BadCylinder: "Invalid cylinder" } ## Cmd.GetInfo indexes class GetInfo: Firmware = 0 BandwidthStats = 1 ## Cmd.{Get,Set}Params indexes class Params: Delays = 0 ## Cmd.SetBusType values class BusType: Invalid = 0 IBMPC = 1 Shugart = 2 ## Flux read stream opcodes, preceded by 0xFF byte class FluxOp: Index = 1 Space = 2 Astable = 3 ## CmdError: Encapsulates a command acknowledgement. class CmdError(Exception): def __init__(self, cmd, code): self.cmd = cmd self.code = code def cmd_str(self): return Cmd.str.get(self.cmd[0], "UnknownCmd") def errcode_str(self): if self.code == Ack.BadCylinder: s = Ack.str[Ack.BadCylinder] return s + " %d" % struct.unpack('2Bb', self.cmd)[2] return Ack.str.get(self.code, "Unknown Error (%u)" % self.code) def __str__(self): return "%s: %s" % (self.cmd_str(), self.errcode_str()) class Unit: ## Unit information, instance variables: ## major, minor: Greaseweazle firmware version number ## max_cmd: Maximum Cmd number accepted by this unit ## sample_freq: Resolution of all time values passed to/from this unit ## update_mode: True iff the Greaseweazle unit is in update mode ## Unit(ser): ## Accepts a Pyserial instance for Greaseweazle communications. def __init__(self, ser): self.ser = ser self.reset() # Copy firmware info to instance variables (see above for definitions). self._send_cmd(struct.pack("3B", Cmd.GetInfo, 3, GetInfo.Firmware)) x = struct.unpack("<4BI3B21x", self.ser.read(32)) (self.major, self.minor, is_main_firmware, self.max_cmd, self.sample_freq, self.hw_model, self.hw_submodel, self.usb_speed) = x # Old firmware doesn't report HW type but runs on STM32F1 only. if self.hw_model == 0: self.hw_model = 1 # Check whether firmware is in update mode: limited command set if so. self.update_mode = (is_main_firmware == 0) if self.update_mode: self.update_jumpered = (self.sample_freq & 1) del self.sample_freq return # We are running main firmware: Check whether an update is needed. # We can use only the GetInfo command if the firmware is out of date. self.update_needed = (version.major != self.major or version.minor != self.minor) if self.update_needed: return # Initialise the delay properties with current firmware values. self._send_cmd(struct.pack("4B", Cmd.GetParams, 4, Params.Delays, 10)) (self._select_delay, self._step_delay, self._seek_settle_delay, self._motor_delay, self._auto_off_delay) = struct.unpack("<5H", self.ser.read(10)) ## reset: ## Resets communications with Greaseweazle. def reset(self): self.ser.reset_output_buffer() self.ser.baudrate = ControlCmd.ClearComms self.ser.baudrate = ControlCmd.Normal self.ser.reset_input_buffer() ## _send_cmd: ## Send given command byte sequence to Greaseweazle. ## Raise a CmdError if command fails. def _send_cmd(self, cmd): self.ser.write(cmd) (c,r) = struct.unpack("2B", self.ser.read(2)) error.check(c == cmd[0], "Command returned garbage (%02x != %02x)" % (c, cmd[0])) if r != 0: raise CmdError(cmd, r) ## seek: ## Seek the selected drive's heads to the specified track (cyl, side). def seek(self, cyl, side): self._send_cmd(struct.pack("2Bb", Cmd.Seek, 3, cyl)) self._send_cmd(struct.pack("3B", Cmd.Side, 3, side)) ## set_bus_type: ## Set the floppy bus type. def set_bus_type(self, type): self._send_cmd(struct.pack("3B", Cmd.SetBusType, 3, type)) ## set_pin: ## Set a pin level. def set_pin(self, pin, level): self._send_cmd(struct.pack("4B", Cmd.SetPin, 4, pin, int(level))) ## power_on_reset: ## Re-initialise to power-on defaults. def power_on_reset(self): self._send_cmd(struct.pack("2B", Cmd.Reset, 2)) ## drive_select: ## Select the specified drive unit. def drive_select(self, unit): self._send_cmd(struct.pack("3B", Cmd.Select, 3, unit)) ## drive_deselect: ## Deselect currently-selected drive unit (if any). def drive_deselect(self): self._send_cmd(struct.pack("2B", Cmd.Deselect, 2)) ## drive_motor: ## Turn the specified drive's motor on/off. def drive_motor(self, unit, state): self._send_cmd(struct.pack("4B", Cmd.Motor, 4, unit, int(state))) ## switch_fw_mode: ## Switch between update bootloader and main firmware. def switch_fw_mode(self, mode): self._send_cmd(struct.pack("3B", Cmd.SwitchFwMode, 3, int(mode))) ## update_firmware: ## Update Greaseweazle to the given new firmware. def update_firmware(self, dat): self._send_cmd(struct.pack("<2BI", Cmd.Update, 6, len(dat))) self.ser.write(dat) (ack,) = struct.unpack("B", self.ser.read(1)) return ack ## update_bootloader: ## Update Greaseweazle with the given new bootloader. def update_bootloader(self, dat): self._send_cmd(struct.pack("<2B2I", Cmd.Update, 10, len(dat), 0xdeafbee3)) self.ser.write(dat) (ack,) = struct.unpack("B", self.ser.read(1)) return ack ## _decode_flux: ## Decode the Greaseweazle data stream into a list of flux samples. def _decode_flux(self, dat): flux, index = [], [] assert dat[-1] == 0 dat_i = it.islice(dat, 0, len(dat)-1) ticks, ticks_since_index = 0, 0 def _read_28bit(): val = (next(dat_i) & 254) >> 1 val += (next(dat_i) & 254) << 6 val += (next(dat_i) & 254) << 13 val += (next(dat_i) & 254) << 20 return val try: while True: i = next(dat_i) if i == 255: opcode = next(dat_i) if opcode == FluxOp.Index: val = _read_28bit() index.append(ticks_since_index + ticks + val) ticks_since_index = -(ticks + val) elif opcode == FluxOp.Space: ticks += _read_28bit() else: raise error.Fatal("Bad opcode in flux stream (%d)" % opcode) else: if i < 250: val = i else: val = 250 + (i - 250) * 255 val += next(dat_i) - 1 ticks += val flux.append(ticks) ticks_since_index += ticks ticks = 0 except StopIteration: pass return flux, index ## _encode_flux: ## Convert the given flux timings into an encoded data stream. def _encode_flux(self, flux): nfa_thresh = round(150e-6 * self.sample_freq) # 150us nfa_period = round(1.25e-6 * self.sample_freq) # 1.25us dat = bytearray() def _write_28bit(x): dat.append(1 | (x<<1) & 255) dat.append(1 | (x>>6) & 255) dat.append(1 | (x>>13) & 255) dat.append(1 | (x>>20) & 255) for val in flux: if val == 0: pass elif val < 250: dat.append(val) elif val > nfa_thresh: dat.append(255) dat.append(FluxOp.Space) _write_28bit(val) dat.append(255) dat.append(FluxOp.Astable) _write_28bit(nfa_period) else: high = (val-250) // 255 if high < 5: dat.append(250 + high) dat.append(1 + (val-250) % 255) else: dat.append(255) dat.append(FluxOp.Space) _write_28bit(val - 249) dat.append(249) dat.append(0) # End of Stream return dat ## _read_track: ## Private helper which issues command requests to Greaseweazle. def _read_track(self, nr_revs): # Request and read all flux timings for this track. dat = bytearray() self._send_cmd(struct.pack("<2BH", Cmd.ReadFlux, 4, nr_revs+1)) while True: dat += self.ser.read(1) dat += self.ser.read(self.ser.in_waiting) if dat[-1] == 0: break # Check flux status. An exception is raised if there was an error. self._send_cmd(struct.pack("2B", Cmd.GetFluxStatus, 2)) return dat ## read_track: ## Read and decode flux and index timings for the current track. def read_track(self, nr_revs, nr_retries=5): retry = 0 while True: try: dat = self._read_track(nr_revs) except CmdError as error: # An error occurred. We may retry on transient overflows. if error.code == Ack.FluxOverflow and retry < nr_retries: retry += 1 else: raise error else: # Success! break # Decode the flux list and read the index-times list. flux_list, index_list = self._decode_flux(dat) # Clip the initial partial revolution. to_index = index_list[0] for i in range(len(flux_list)): to_index -= flux_list[i] if to_index < 0: flux_list[i] = -to_index flux_list = flux_list[i:] break if to_index >= 0: # We ran out of flux. flux_list = [] index_list = index_list[1:] # Success: Return the requested full index-to-index revolutions. return Flux(index_list, flux_list, self.sample_freq) ## write_track: ## Write the given flux stream to the current track via Greaseweazle. def write_track(self, flux_list, terminate_at_index, nr_retries=5): # Create encoded data stream. dat = self._encode_flux(flux_list) retry = 0 while True: try: # Write the flux stream to the track via Greaseweazle. self._send_cmd(struct.pack("3B", Cmd.WriteFlux, 3, int(terminate_at_index))) self.ser.write(dat) self.ser.read(1) # Sync with Greaseweazle self._send_cmd(struct.pack("2B", Cmd.GetFluxStatus, 2)) except CmdError as error: # An error occurred. We may retry on transient underflows. if error.code == Ack.FluxUnderflow and retry < nr_retries: retry += 1 else: raise error else: # Success! break ## erase_track: ## Erase the current track via Greaseweazle. def erase_track(self, ticks): self._send_cmd(struct.pack("<2BI", Cmd.EraseFlux, 6, int(ticks))) self.ser.read(1) # Sync with Greaseweazle self._send_cmd(struct.pack("2B", Cmd.GetFluxStatus, 2)) ## source_bytes: ## Command Greaseweazle to source 'nr' garbage bytes. def source_bytes(self, nr): self._send_cmd(struct.pack("<2BI", Cmd.SourceBytes, 6, nr)) while nr > 0: self.ser.read(1) waiting = self.ser.in_waiting self.ser.read(waiting) nr -= 1 + waiting ## sink_bytes: ## Command Greaseweazle to sink 'nr' garbage bytes. def sink_bytes(self, nr): self._send_cmd(struct.pack("<2BI", Cmd.SinkBytes, 6, nr)) dat = bytes(1024*1024) while nr > len(dat): self.ser.write(dat) nr -= len(dat) self.ser.write(dat[:nr]) self.ser.read(1) # Sync with Greaseweazle ## bw_stats: ## Get min/max bandwidth for previous source/sink command. Mbps (float). def bw_stats(self): self._send_cmd(struct.pack("3B", Cmd.GetInfo, 3, GetInfo.BandwidthStats)) min_bytes, min_usecs, max_bytes, max_usecs = struct.unpack( "<4I16x", self.ser.read(32)) min_bw = (8 * min_bytes) / min_usecs max_bw = (8 * max_bytes) / max_usecs return min_bw, max_bw ## ## Delay-property public getters and setters: ## select_delay: Delay (usec) after asserting drive select ## step_delay: Delay (usec) after issuing a head-step command ## seek_settle_delay: Delay (msec) after completing a head-seek operation ## motor_delay: Delay (msec) after turning on drive spindle motor ## auto_off_delay: Timeout (msec) since last command upon which all ## drives are deselected and spindle motors turned off ## def _set_delays(self): self._send_cmd(struct.pack("<3B5H", Cmd.SetParams, 3+5*2, Params.Delays, self._select_delay, self._step_delay, self._seek_settle_delay, self._motor_delay, self._auto_off_delay)) @property def select_delay(self): return self._select_delay @select_delay.setter def select_delay(self, select_delay): self._select_delay = select_delay self._set_delays() @property def step_delay(self): return self._step_delay @step_delay.setter def step_delay(self, step_delay): self._step_delay = step_delay self._set_delays() @property def seek_settle_delay(self): return self._seek_settle_delay @seek_settle_delay.setter def seek_settle_delay(self, seek_settle_delay): self._seek_settle_delay = seek_settle_delay self._set_delays() @property def motor_delay(self): return self._motor_delay @motor_delay.setter def motor_delay(self, motor_delay): self._motor_delay = motor_delay self._set_delays() @property def auto_off_delay(self): return self._auto_off_delay @auto_off_delay.setter def auto_off_delay(self, auto_off_delay): self._auto_off_delay = auto_off_delay self._set_delays() # Local variables: # python-indent: 4 # End:
32.081784
79
0.554693
import struct import itertools as it from greaseweazle import version from greaseweazle import error from greaseweazle.flux import Flux arComms = 10000 Normal = 9600 GetInfo = 0 Update = 1 Seek = 2 Side = 3 SetParams = 4 GetParams = 5 Motor = 6 ReadFlux = 7 WriteFlux = 8 GetFluxStatus = 9 GetIndexTimes = 10 SwitchFwMode = 11 Select = 12 Deselect = 13 SetBusType = 14 SetPin = 15 Reset = 16 EraseFlux = 17 SourceBytes = 18 SinkBytes = 19 str = { GetInfo: "GetInfo", Update: "Update", Seek: "Seek", Side: "Side", SetParams: "SetParams", GetParams: "GetParams", Motor: "Motor", ReadFlux: "ReadFlux", WriteFlux: "WriteFlux", GetFluxStatus: "GetFluxStatus", GetIndexTimes: "GetIndexTimes", SwitchFwMode: "SwitchFwMode", Select: "Select", Deselect: "Deselect", SetBusType: "SetBusType", SetPin: "SetPin", Reset: "Reset", EraseFlux: "EraseFlux", SourceBytes: "SourceBytes", SinkBytes: "SinkBytes" } BadCommand = 1 NoIndex = 2 NoTrk0 = 3 FluxOverflow = 4 FluxUnderflow = 5 Wrprot = 6 NoUnit = 7 NoBus = 8 BadUnit = 9 BadPin = 10 BadCylinder = 11 str = { Okay: "Okay", BadCommand: "Bad Command", NoIndex: "No Index", NoTrk0: "Track 0 not found", FluxOverflow: "Flux Overflow", FluxUnderflow: "Flux Underflow", Wrprot: "Disk is Write Protected", NoUnit: "No drive unit selected", NoBus: "No bus type (eg. Shugart, IBM/PC) specified", BadUnit: "Invalid unit number", BadPin: "Not a modifiable pin", BadCylinder: "Invalid cylinder" } irmware = 0 BandwidthStats = 1 = 0 alid = 0 IBMPC = 1 Shugart = 2 = 2 Astable = 3 cmd, code): self.cmd = cmd self.code = code def cmd_str(self): return Cmd.str.get(self.cmd[0], "UnknownCmd") def errcode_str(self): if self.code == Ack.BadCylinder: s = Ack.str[Ack.BadCylinder] return s + " %d" % struct.unpack('2Bb', self.cmd)[2] return Ack.str.get(self.code, "Unknown Error (%u)" % self.code) def __str__(self): return "%s: %s" % (self.cmd_str(), self.errcode_str()) class Unit: self.hw_submodel, self.usb_speed) = x if self.hw_model == 0: self.hw_model = 1 # Check whether firmware is in update mode: limited command set if so. self.update_mode = (is_main_firmware == 0) if self.update_mode: self.update_jumpered = (self.sample_freq & 1) del self.sample_freq return # We are running main firmware: Check whether an update is needed. # We can use only the GetInfo command if the firmware is out of date. self.update_needed = (version.major != self.major or version.minor != self.minor) if self.update_needed: return # Initialise the delay properties with current firmware values. self._send_cmd(struct.pack("4B", Cmd.GetParams, 4, Params.Delays, 10)) (self._select_delay, self._step_delay, self._seek_settle_delay, self._motor_delay, self._auto_off_delay) = struct.unpack("<5H", self.ser.read(10)) ## reset: ## Resets communications with Greaseweazle. def reset(self): self.ser.reset_output_buffer() self.ser.baudrate = ControlCmd.ClearComms self.ser.baudrate = ControlCmd.Normal self.ser.reset_input_buffer() ## _send_cmd: ## Send given command byte sequence to Greaseweazle. ## Raise a CmdError if command fails. def _send_cmd(self, cmd): self.ser.write(cmd) (c,r) = struct.unpack("2B", self.ser.read(2)) error.check(c == cmd[0], "Command returned garbage (%02x != %02x)" % (c, cmd[0])) if r != 0: raise CmdError(cmd, r) ## seek: ## Seek the selected drive's heads to the specified track (cyl, side). def seek(self, cyl, side): self._send_cmd(struct.pack("2Bb", Cmd.Seek, 3, cyl)) self._send_cmd(struct.pack("3B", Cmd.Side, 3, side)) self._send_cmd(struct.pack("3B", Cmd.SetBusType, 3, type)) pin, level): self._send_cmd(struct.pack("4B", Cmd.SetPin, 4, pin, int(level))) _cmd(struct.pack("2B", Cmd.Reset, 2)) elf._send_cmd(struct.pack("3B", Cmd.Select, 3, unit)) ack("2B", Cmd.Deselect, 2)) lf._send_cmd(struct.pack("4B", Cmd.Motor, 4, unit, int(state))) ## switch_fw_mode: ## Switch between update bootloader and main firmware. def switch_fw_mode(self, mode): self._send_cmd(struct.pack("3B", Cmd.SwitchFwMode, 3, int(mode))) ## update_firmware: ## Update Greaseweazle to the given new firmware. def update_firmware(self, dat): self._send_cmd(struct.pack("<2BI", Cmd.Update, 6, len(dat))) self.ser.write(dat) (ack,) = struct.unpack("B", self.ser.read(1)) return ack ## update_bootloader: ## Update Greaseweazle with the given new bootloader. def update_bootloader(self, dat): self._send_cmd(struct.pack("<2B2I", Cmd.Update, 10, len(dat), 0xdeafbee3)) self.ser.write(dat) (ack,) = struct.unpack("B", self.ser.read(1)) return ack ## _decode_flux: ## Decode the Greaseweazle data stream into a list of flux samples. def _decode_flux(self, dat): flux, index = [], [] assert dat[-1] == 0 dat_i = it.islice(dat, 0, len(dat)-1) ticks, ticks_since_index = 0, 0 def _read_28bit(): val = (next(dat_i) & 254) >> 1 val += (next(dat_i) & 254) << 6 val += (next(dat_i) & 254) << 13 val += (next(dat_i) & 254) << 20 return val try: while True: i = next(dat_i) if i == 255: opcode = next(dat_i) if opcode == FluxOp.Index: val = _read_28bit() index.append(ticks_since_index + ticks + val) ticks_since_index = -(ticks + val) elif opcode == FluxOp.Space: ticks += _read_28bit() else: raise error.Fatal("Bad opcode in flux stream (%d)" % opcode) else: if i < 250: val = i else: val = 250 + (i - 250) * 255 val += next(dat_i) - 1 ticks += val flux.append(ticks) ticks_since_index += ticks ticks = 0 except StopIteration: pass return flux, index ## _encode_flux: ## Convert the given flux timings into an encoded data stream. def _encode_flux(self, flux): nfa_thresh = round(150e-6 * self.sample_freq) # 150us nfa_period = round(1.25e-6 * self.sample_freq) # 1.25us dat = bytearray() def _write_28bit(x): dat.append(1 | (x<<1) & 255) dat.append(1 | (x>>6) & 255) dat.append(1 | (x>>13) & 255) dat.append(1 | (x>>20) & 255) for val in flux: if val == 0: pass elif val < 250: dat.append(val) elif val > nfa_thresh: dat.append(255) dat.append(FluxOp.Space) _write_28bit(val) dat.append(255) dat.append(FluxOp.Astable) _write_28bit(nfa_period) else: high = (val-250) // 255 if high < 5: dat.append(250 + high) dat.append(1 + (val-250) % 255) else: dat.append(255) dat.append(FluxOp.Space) _write_28bit(val - 249) dat.append(249) dat.append(0) # End of Stream return dat ## _read_track: ## Private helper which issues command requests to Greaseweazle. def _read_track(self, nr_revs): # Request and read all flux timings for this track. dat = bytearray() self._send_cmd(struct.pack("<2BH", Cmd.ReadFlux, 4, nr_revs+1)) while True: dat += self.ser.read(1) dat += self.ser.read(self.ser.in_waiting) if dat[-1] == 0: break # Check flux status. An exception is raised if there was an error. self._send_cmd(struct.pack("2B", Cmd.GetFluxStatus, 2)) return dat ## read_track: ## Read and decode flux and index timings for the current track. def read_track(self, nr_revs, nr_retries=5): retry = 0 while True: try: dat = self._read_track(nr_revs) except CmdError as error: # An error occurred. We may retry on transient overflows. if error.code == Ack.FluxOverflow and retry < nr_retries: retry += 1 else: raise error else: # Success! break # Decode the flux list and read the index-times list. flux_list, index_list = self._decode_flux(dat) # Clip the initial partial revolution. to_index = index_list[0] for i in range(len(flux_list)): to_index -= flux_list[i] if to_index < 0: flux_list[i] = -to_index flux_list = flux_list[i:] break if to_index >= 0: # We ran out of flux. flux_list = [] index_list = index_list[1:] # Success: Return the requested full index-to-index revolutions. return Flux(index_list, flux_list, self.sample_freq) ## write_track: ## Write the given flux stream to the current track via Greaseweazle. def write_track(self, flux_list, terminate_at_index, nr_retries=5): # Create encoded data stream. dat = self._encode_flux(flux_list) retry = 0 while True: try: # Write the flux stream to the track via Greaseweazle. self._send_cmd(struct.pack("3B", Cmd.WriteFlux, 3, int(terminate_at_index))) self.ser.write(dat) self.ser.read(1) # Sync with Greaseweazle self._send_cmd(struct.pack("2B", Cmd.GetFluxStatus, 2)) except CmdError as error: # An error occurred. We may retry on transient underflows. if error.code == Ack.FluxUnderflow and retry < nr_retries: retry += 1 else: raise error else: # Success! break ## erase_track: ## Erase the current track via Greaseweazle. def erase_track(self, ticks): self._send_cmd(struct.pack("<2BI", Cmd.EraseFlux, 6, int(ticks))) self.ser.read(1) # Sync with Greaseweazle self._send_cmd(struct.pack("2B", Cmd.GetFluxStatus, 2)) ## source_bytes: ## Command Greaseweazle to source 'nr' garbage bytes. def source_bytes(self, nr): self._send_cmd(struct.pack("<2BI", Cmd.SourceBytes, 6, nr)) while nr > 0: self.ser.read(1) waiting = self.ser.in_waiting self.ser.read(waiting) nr -= 1 + waiting ## sink_bytes: ## Command Greaseweazle to sink 'nr' garbage bytes. def sink_bytes(self, nr): self._send_cmd(struct.pack("<2BI", Cmd.SinkBytes, 6, nr)) dat = bytes(1024*1024) while nr > len(dat): self.ser.write(dat) nr -= len(dat) self.ser.write(dat[:nr]) self.ser.read(1) # Sync with Greaseweazle ## bw_stats: ## Get min/max bandwidth for previous source/sink command. Mbps (float). def bw_stats(self): self._send_cmd(struct.pack("3B", Cmd.GetInfo, 3, GetInfo.BandwidthStats)) min_bytes, min_usecs, max_bytes, max_usecs = struct.unpack( "<4I16x", self.ser.read(32)) min_bw = (8 * min_bytes) / min_usecs max_bw = (8 * max_bytes) / max_usecs return min_bw, max_bw ## ## Delay-property public getters and setters: ## select_delay: Delay (usec) after asserting drive select ## step_delay: Delay (usec) after issuing a head-step command ## seek_settle_delay: Delay (msec) after completing a head-seek operation ## motor_delay: Delay (msec) after turning on drive spindle motor ## auto_off_delay: Timeout (msec) since last command upon which all ## drives are deselected and spindle motors turned off ## def _set_delays(self): self._send_cmd(struct.pack("<3B5H", Cmd.SetParams, 3+5*2, Params.Delays, self._select_delay, self._step_delay, self._seek_settle_delay, self._motor_delay, self._auto_off_delay)) @property def select_delay(self): return self._select_delay @select_delay.setter def select_delay(self, select_delay): self._select_delay = select_delay self._set_delays() @property def step_delay(self): return self._step_delay @step_delay.setter def step_delay(self, step_delay): self._step_delay = step_delay self._set_delays() @property def seek_settle_delay(self): return self._seek_settle_delay @seek_settle_delay.setter def seek_settle_delay(self, seek_settle_delay): self._seek_settle_delay = seek_settle_delay self._set_delays() @property def motor_delay(self): return self._motor_delay @motor_delay.setter def motor_delay(self, motor_delay): self._motor_delay = motor_delay self._set_delays() @property def auto_off_delay(self): return self._auto_off_delay @auto_off_delay.setter def auto_off_delay(self, auto_off_delay): self._auto_off_delay = auto_off_delay self._set_delays() # Local variables: # python-indent: 4 # End:
true
true
f72a79d3d2c56e71938e0ba2cdbc1fa44b6c0c29
3,576
py
Python
Vault7/Lost-in-Translation/windows/Resources/Ops/PyScripts/lib/ops/cmd/performance.py
dendisuhubdy/grokmachine
120a21a25c2730ed356739231ec8b99fc0575c8b
[ "BSD-3-Clause" ]
46
2017-05-15T11:15:08.000Z
2018-07-02T03:32:52.000Z
Vault7/Lost-in-Translation/windows/Resources/Ops/PyScripts/lib/ops/cmd/performance.py
dendisuhubdy/grokmachine
120a21a25c2730ed356739231ec8b99fc0575c8b
[ "BSD-3-Clause" ]
null
null
null
Vault7/Lost-in-Translation/windows/Resources/Ops/PyScripts/lib/ops/cmd/performance.py
dendisuhubdy/grokmachine
120a21a25c2730ed356739231ec8b99fc0575c8b
[ "BSD-3-Clause" ]
24
2017-05-17T03:26:17.000Z
2018-07-09T07:00:50.000Z
import ops.cmd import util.ip DATA_TYPES = ['all', 'browser', 'cache', 'expensive', 'icmp', 'ip', 'jobobject', 'jobobjectdetails', 'logicaldisk', 'memory', 'networkinterface', 'objects', 'pagingfile', 'physicaldisk', 'process', 'processor', 'system', 'tcp', 'telephony', 'terminalservices', 'thread', 'udp'] class PerformanceCommand(ops.cmd.DszCommand, ): def __init__(self, plugin='performance', data=None, objectNumber=None, initialBufferSize=None, bare=False, target=None, **optdict): self.data = data self.objectNumber = objectNumber self.initialBufferSize = initialBufferSize self.bare = bare self.target = target ops.cmd.DszCommand.__init__(self, plugin, **optdict) def _getInitialBufferSize(self): return self._opt_initial def _setInitialBufferSize(self, bufferSize): assert ((bufferSize is None) or ((type(bufferSize) is int) and (bufferSize > 0))), 'bufferSize must be an integer greater than zero; or None to clear this option.' self._opt_initial = bufferSize initialBufferSize = property(_getInitialBufferSize, _setInitialBufferSize) def _getObjectNumber(self): return self._opt_objectNumber def _setObjectNumber(self, objectNumber): assert ((objectNumber is None) or ((type(objectNumber) is int) and (objectNumber >= 0))), 'Object number must be a positive integer or zero; or None to clear this option.' self._opt_objectNumber = objectNumber objectNumber = property(_getObjectNumber, _setObjectNumber) def _getData(self): return self._opt_data def _setData(self, data): assert ((type(data) is str) or (type(data) is unicode) or (data is None)), 'Data must be a string value or None to clear this option.' assert ((data is None) or (data.lower() in DATA_TYPES)), 'Data must be one of the valid data type queries.' self._opt_data = data data = property(_getData, _setData) def _getBare(self): return self._opt_bare def _setBare(self, bare): assert (type(bare) is bool), 'Bare must be Boolean.' self._opt_bare = bare bare = property(_getBare, _setBare) def _getTarget(self): return self._opt_target def _setTarget(self, target): assert ((type(target) is str) or (type(target) is unicode) or (target is None)), 'Target must be a string representation or None to clear.' assert ((target is None) or util.ip.validate(target)), 'Target address must be a valid IPv4 or IPv6 address.' self._opt_target = target target = property(_getTarget, _setTarget) def validateInput(self): if ((self.data is not None) and (self.objectNumber is not None)): return False if ((self.data is None) and (self.objectNumber is None)): return False return True def __str__(self): cmdstr = u'' for prefix in self.prefixes: cmdstr += ('%s ' % prefix) cmdstr += (self.plugin + ' ') if self.initialBufferSize: cmdstr += ('-initial %s ' % self.initalBufferSize) if self.objectNumber: cmdstr += ('-objectnum %s ' % self.objectNumber) if self.data: cmdstr += ('-data %s ' % self.data) if self.bare: cmdstr += '-bare ' if self.target: cmdstr += ('-target %s ' % self.target) return ops.utf8(cmdstr) ops.cmd.command_classes['performance'] = PerformanceCommand
44.148148
278
0.635906
import ops.cmd import util.ip DATA_TYPES = ['all', 'browser', 'cache', 'expensive', 'icmp', 'ip', 'jobobject', 'jobobjectdetails', 'logicaldisk', 'memory', 'networkinterface', 'objects', 'pagingfile', 'physicaldisk', 'process', 'processor', 'system', 'tcp', 'telephony', 'terminalservices', 'thread', 'udp'] class PerformanceCommand(ops.cmd.DszCommand, ): def __init__(self, plugin='performance', data=None, objectNumber=None, initialBufferSize=None, bare=False, target=None, **optdict): self.data = data self.objectNumber = objectNumber self.initialBufferSize = initialBufferSize self.bare = bare self.target = target ops.cmd.DszCommand.__init__(self, plugin, **optdict) def _getInitialBufferSize(self): return self._opt_initial def _setInitialBufferSize(self, bufferSize): assert ((bufferSize is None) or ((type(bufferSize) is int) and (bufferSize > 0))), 'bufferSize must be an integer greater than zero; or None to clear this option.' self._opt_initial = bufferSize initialBufferSize = property(_getInitialBufferSize, _setInitialBufferSize) def _getObjectNumber(self): return self._opt_objectNumber def _setObjectNumber(self, objectNumber): assert ((objectNumber is None) or ((type(objectNumber) is int) and (objectNumber >= 0))), 'Object number must be a positive integer or zero; or None to clear this option.' self._opt_objectNumber = objectNumber objectNumber = property(_getObjectNumber, _setObjectNumber) def _getData(self): return self._opt_data def _setData(self, data): assert ((type(data) is str) or (type(data) is unicode) or (data is None)), 'Data must be a string value or None to clear this option.' assert ((data is None) or (data.lower() in DATA_TYPES)), 'Data must be one of the valid data type queries.' self._opt_data = data data = property(_getData, _setData) def _getBare(self): return self._opt_bare def _setBare(self, bare): assert (type(bare) is bool), 'Bare must be Boolean.' self._opt_bare = bare bare = property(_getBare, _setBare) def _getTarget(self): return self._opt_target def _setTarget(self, target): assert ((type(target) is str) or (type(target) is unicode) or (target is None)), 'Target must be a string representation or None to clear.' assert ((target is None) or util.ip.validate(target)), 'Target address must be a valid IPv4 or IPv6 address.' self._opt_target = target target = property(_getTarget, _setTarget) def validateInput(self): if ((self.data is not None) and (self.objectNumber is not None)): return False if ((self.data is None) and (self.objectNumber is None)): return False return True def __str__(self): cmdstr = u'' for prefix in self.prefixes: cmdstr += ('%s ' % prefix) cmdstr += (self.plugin + ' ') if self.initialBufferSize: cmdstr += ('-initial %s ' % self.initalBufferSize) if self.objectNumber: cmdstr += ('-objectnum %s ' % self.objectNumber) if self.data: cmdstr += ('-data %s ' % self.data) if self.bare: cmdstr += '-bare ' if self.target: cmdstr += ('-target %s ' % self.target) return ops.utf8(cmdstr) ops.cmd.command_classes['performance'] = PerformanceCommand
true
true
f72a79de3ba6052a6dc1da390b52adbd516b2242
19,851
py
Python
train/t2m2/run.py
SungbinChoi/traffic4cast2021
3d63b7e90ad0d9c7346f2a6c6c89d605849bf49e
[ "Apache-2.0" ]
null
null
null
train/t2m2/run.py
SungbinChoi/traffic4cast2021
3d63b7e90ad0d9c7346f2a6c6c89d605849bf49e
[ "Apache-2.0" ]
null
null
null
train/t2m2/run.py
SungbinChoi/traffic4cast2021
3d63b7e90ad0d9c7346f2a6c6c89d605849bf49e
[ "Apache-2.0" ]
null
null
null
import random from random import shuffle import numpy as np from datetime import datetime import time import queue import threading import logging from PIL import Image import itertools import re import os import glob import shutil import sys import copy import h5py from typing import Any, List, Tuple import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.nn.parallel.data_parallel import data_parallel import torch.utils.checkpoint as cp from collections import OrderedDict from torch import Tensor target_city = 'ANTWERP' other_city_list = ['ANTWERP', 'BANGKOK', 'BARCELONA', 'MOSCOW', 'BERLIN', 'CHICAGO', 'ISTANBUL', 'MELBOURNE', ] input_train_data_folder_path = '../../0_data/' + target_city + '/' + 'training' input_static_data_path = '../../0_data/' + target_city + '/' + target_city + "_static.h5" out_dir = 'output' os.environ['CUDA_VISIBLE_DEVICES'] = '0' SEED = int(time.time()) num_train_file = 180 num_frame_per_day = 288 num_frame_before = 12 num_frame_sequence = 24 num_frame_out = 6 num_sequence_per_day = num_frame_per_day - num_frame_sequence + 1 height=495 width =436 num_channel=8 num_channel_out=8 num_channel_static = 9 visual_input_channels=105 visual_output_channels=48 vector_input_channels=1 num_epoch_to_train = 100000000 save_per_iteration = 5000 global_step_start = 0 initial_checkpoint = None initial_checkpoint_optimizer = None LEARNING_RATE = 3e-4 batch_size = 2 batch_size_val = 1 num_thread=2 num_groups = 8 EPS = 1e-12 np.set_printoptions(precision=8) NUM_INPUT_CHANNEL = visual_input_channels NUM_OUTPUT_CHANNEL = visual_output_channels def get_data_filepath_list_by_year(input_data_folder_path): data_filepath_list_1 = [] data_filepath_list_2 = [] for filename in os.listdir(input_data_folder_path): if filename.split('.')[-1] != 'h5': continue if filename.startswith('2019'): data_filepath_list_1.append(os.path.join(input_data_folder_path, filename)) elif filename.startswith('2020'): data_filepath_list_2.append(os.path.join(input_data_folder_path, filename)) else: print('Error - Unknown data year\t', filename) exit(-1) data_filepath_list_1 = sorted(data_filepath_list_1) data_filepath_list_2 = sorted(data_filepath_list_2) return data_filepath_list_1, data_filepath_list_2 class Deconv3x3Block(nn.Sequential): def __init__(self, in_size: int, h_size: int, ) -> None: super(Deconv3x3Block, self).__init__() self.add_module('deconv', nn.ConvTranspose2d(in_size, h_size, kernel_size=3, stride=2, padding=1, bias=True)) self.add_module('elu', nn.ELU(inplace=True)) self.add_module('norm', nn.GroupNorm(num_groups=num_groups, num_channels=h_size)) class Conv1x1Block(nn.Sequential): def __init__(self, in_size: int, h_size: int, ) -> None: super(Conv1x1Block, self).__init__() self.add_module('conv', nn.Conv2d(in_size, h_size, kernel_size=1, stride=1, padding=0, bias=True)) class Conv3x3Block(nn.Sequential): def __init__(self, in_size: int, h_size: int, ) -> None: super(Conv3x3Block, self).__init__() self.add_module('conv', nn.Conv2d(in_size, h_size, kernel_size=3, stride=1, padding=1, bias=True)) self.add_module('elu', nn.ELU(inplace=True)) self.add_module('norm', nn.GroupNorm(num_groups=num_groups, num_channels=h_size)) class AvgBlock(nn.Sequential): def __init__(self, kernel_size: int, stride: int, padding: int) -> None: super(AvgBlock, self).__init__() self.add_module('pool', nn.AvgPool2d(kernel_size=kernel_size, stride=stride, padding=padding)) class MaxBlock(nn.Sequential): def __init__(self, kernel_size: int, stride: int, padding: int) -> None: super(MaxBlock, self).__init__() self.add_module('pool', nn.MaxPool2d(kernel_size=kernel_size, stride=stride, padding=padding)) class DownBlock(nn.Module): def __init__(self, in_size: int, h_size: int, out_size: int, do_pool: int = True): super(DownBlock, self).__init__() self.do_pool = do_pool in_size_cum = in_size self.conv_1 = Conv3x3Block( in_size=in_size_cum, h_size=h_size) in_size_cum += h_size self.conv_3 = Conv3x3Block( in_size=in_size_cum, h_size=h_size) in_size_cum += h_size self.conv_2 = Conv1x1Block( in_size=in_size_cum, h_size=out_size) def forward(self, x): batch_size = len(x) if self.do_pool: x = F.interpolate(x, scale_factor=0.7, mode='bilinear', align_corners=False, recompute_scale_factor=None) x_list = [] x_list.append(x) x = self.conv_1(x) x_list.append(x) x = torch.cat(x_list, 1) x = self.conv_3(x) x_list.append(x) x = torch.cat(x_list, 1) x = self.conv_2(x) return x def cuda(self, ): super(DownBlock, self).cuda() self.conv_1.cuda() self.conv_3.cuda() self.conv_2.cuda() return self class UpBlock(nn.Module): def __init__(self, in_size: int, in_size_2: int, h_size: int, out_size: int, ): super(UpBlock, self).__init__() self.deconv = Conv3x3Block( in_size=in_size, h_size=h_size) self.out_conv = Conv3x3Block( in_size=h_size + in_size_2, h_size=out_size) def forward(self, x1, x2): x1 = self.deconv(x1) x1 = F.interpolate(x1, size=x2.size()[2:4], scale_factor=None, mode='bilinear', align_corners=False, recompute_scale_factor=None) x = torch.cat([x2, x1], dim=1) return self.out_conv(x) def cuda(self, ): super(UpBlock, self).cuda() self.deconv.cuda() self.out_conv.cuda() return self class NetA(nn.Module): def __init__(self,): super(NetA, self).__init__() self.block0 = DownBlock(in_size=NUM_INPUT_CHANNEL, h_size=128, out_size=128, do_pool=False) self.block1 = DownBlock(in_size=128, h_size=128, out_size=128,) self.block2 = DownBlock(in_size=128, h_size=128, out_size=128, ) self.block3 = DownBlock(in_size=128, h_size=128, out_size=128, ) self.block4 = DownBlock(in_size=128, h_size=128, out_size=128, ) self.block5 = DownBlock(in_size=128, h_size=128, out_size=128, ) self.block6 = DownBlock(in_size=128, h_size=128, out_size=128,) self.block7 = DownBlock(in_size=128, h_size=128, out_size=128,) self.block20 = Conv3x3Block(in_size=128, h_size=128) self.block16 = UpBlock(in_size=128, in_size_2=128, h_size=128, out_size=128,) self.block15 = UpBlock(in_size=128, in_size_2=128, h_size=128, out_size=128,) self.block14 = UpBlock(in_size=128, in_size_2=128, h_size=128, out_size=128,) self.block13 = UpBlock(in_size=128, in_size_2=128, h_size=128, out_size=128,) self.block12 = UpBlock(in_size=128, in_size_2=128, h_size=128, out_size=128,) self.block11 = UpBlock(in_size=128, in_size_2=128 , h_size=128, out_size=128,) self.block10 = UpBlock(in_size=128, in_size_2=128 , h_size=128, out_size=128,) self.out_conv = nn.Sequential(nn.Conv2d(128*1, NUM_OUTPUT_CHANNEL, kernel_size=3, stride=1, padding=1, bias=True)) if 1: for name, m in self.named_modules(): if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d): nn.init.kaiming_normal_(m.weight) elif isinstance(m, nn.BatchNorm2d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) elif isinstance(m, nn.GroupNorm): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) elif isinstance(m, nn.Linear): nn.init.constant_(m.bias, 0) def forward(self, x): batch_size = len(x) x0 = self.block0(x) x1 = self.block1(x0) x2 = self.block2(x1) x3 = self.block3(x2) x4 = self.block4(x3) x5 = self.block5(x4) x6 = self.block6(x5) x7 = self.block7(x6) x = self.block20(x7) x = self.block16(x, x6) x = self.block15(x, x5) x = self.block14(x, x4) x = self.block13(x, x3) x = self.block12(x, x2) x = self.block11(x, x1) x = self.block10(x, x0) x = self.out_conv(x) x = torch.sigmoid(x) return x def cuda(self, ): super(NetA, self).cuda() self.block0.cuda() self.block1.cuda() self.block2.cuda() self.block3.cuda() self.block4.cuda() self.block5.cuda() self.block6.cuda() self.block7.cuda() self.block20.cuda() self.block16.cuda() self.block15.cuda() self.block14.cuda() self.block13.cuda() self.block12.cuda() self.block11.cuda() self.block10.cuda() self.out_conv.cuda() return self if __name__ == '__main__': if initial_checkpoint == None: assert global_step_start == 0 else: assert global_step_start > 0 random.seed(SEED) np.random.seed(SEED) torch.manual_seed(SEED) torch.cuda.manual_seed_all(SEED) torch.backends.cudnn.enabled = True torch.backends.cudnn.benchmark = True torch.backends.cudnn.deterministic = False try: if not os.path.exists(out_dir): os.makedirs(out_dir) except Exception: print('out_dir not made') net = NetA().cuda() optimizer = optim.Adam(filter(lambda p: p.requires_grad, net.parameters()),lr=LEARNING_RATE) loss_func2 = nn.MSELoss() if initial_checkpoint is not None: print('Loading ', initial_checkpoint) state_dict = torch.load(initial_checkpoint, map_location=lambda storage, loc: storage) net.load_state_dict(state_dict, strict=True) optimizer_state_dict_ = torch.load(initial_checkpoint_optimizer, map_location=lambda storage, loc: storage) optimizer_state_dict = optimizer_state_dict_['optimizer'] optimizer.load_state_dict(optimizer_state_dict) static_data = None if 1: file_path = input_static_data_path fr = h5py.File(file_path, 'r') a_group_key = list(fr.keys())[0] data = np.asarray(fr[a_group_key], np.uint8) static_data = data[np.newaxis,:,:,:] static_data = static_data.astype(np.float32) static_data = static_data / 255.0 static_data_list = [] if 1: for other_city in other_city_list: file_path = '../../0_data/' + other_city + '/' + other_city + "_static.h5" fr = h5py.File(file_path, 'r') a_group_key = list(fr.keys())[0] data = np.asarray(fr[a_group_key], np.uint8) static_data_ = data[np.newaxis,:,:,:] static_data_ = static_data_.astype(np.float32) static_data_ = static_data_ / 255.0 static_data_list.append(static_data_) train_static_data_index_list = [] train_data_filepath_list, val_data_filepath_list = get_data_filepath_list_by_year(input_train_data_folder_path) target_city_i = other_city_list.index(target_city) for _ in range(len(train_data_filepath_list)): train_static_data_index_list.append(target_city_i) for o, other_city in enumerate(other_city_list): if o == target_city_i: continue train_data_filepath_list_one, _ = get_data_filepath_list_by_year('../../0_data/' + other_city + '/' + 'training') for _ in range(len(train_data_filepath_list_one)): train_static_data_index_list.append(o) train_data_filepath_list += train_data_filepath_list_one train_set = [] for i in range(len(train_data_filepath_list)): for j in range(num_sequence_per_day): train_set.append( (i,j) ) num_iteration_per_epoch = int(len(train_set) / batch_size) print('num_iteration_per_epoch:', num_iteration_per_epoch) assert num_iteration_per_epoch > 10 val_set = [] val_skip_k = 0 val_skip_ratio = 5 for i in range(len(val_data_filepath_list)): for j in range(0, num_sequence_per_day, num_frame_sequence): val_skip_k += 1 if val_skip_k % val_skip_ratio == 0: val_set.append( (i,j) ) num_val_iteration_per_epoch = int(len(val_set) / batch_size_val) print('num_val_iteration_per_epoch:', num_val_iteration_per_epoch) train_input_queue = queue.Queue() train_output_queue = queue.Queue() def load_train_multithread(): while True: if train_input_queue.empty() or train_output_queue.qsize() > 8: time.sleep(0.1) continue i_j_list = train_input_queue.get() train_orig_data_batch_list = [] train_data_batch_list = [] train_data_mask_list = [] train_stat_batch_list = [] train_static_data_batch_list = [] for train_i_j in i_j_list: (i,j) = train_i_j file_path = train_data_filepath_list[i] train_static_data_batch_list.append(static_data_list[train_static_data_index_list[i]]) fr = h5py.File(file_path, 'r') a_group_key = list(fr.keys())[0] data = fr[a_group_key] train_data_batch_list.append(data[j:j+num_frame_sequence,:,:,:][np.newaxis,:,:,:,:]) train_data_batch = np.concatenate(train_data_batch_list, axis=0) train_static_data_batch = np.concatenate(train_static_data_batch_list,axis=0) input_data = train_data_batch[:,:num_frame_before ,:,:,:] orig_label = train_data_batch[:, num_frame_before:,:,:,:num_channel_out] true_label = np.concatenate((orig_label[:, 0:3, :,:,:], orig_label[:, 5::3,:,:,:] ), axis=1) input_data = input_data.astype(np.float32) true_label = true_label.astype(np.float32) input_data = input_data / 255.0 true_label = true_label / 255.0 flip_dr = np.random.randint(0,2) if flip_dr == 1: input_data_flipped = copy.deepcopy(input_data) input_data_flipped[:,:,:,:,4:8] = input_data[:,:,:,:,0:4] input_data_flipped[:,:,:,:,0:4] = input_data[:,:,:,:,4:8] input_data = input_data_flipped[:,:,::-1,::-1,:] true_label_flipped = copy.deepcopy(true_label) true_label_flipped[:,:,:,:,4:8] = true_label[:,:,:,:,0:4] true_label_flipped[:,:,:,:,0:4] = true_label[:,:,:,:,4:8] true_label = true_label_flipped[:,:,::-1,::-1,:] train_static_data_batch_flipped = copy.deepcopy(train_static_data_batch) train_static_data_batch_flipped[:,5:9,:,:] = train_static_data_batch[:,1:5,:,:] train_static_data_batch_flipped[:,1:5,:,:] = train_static_data_batch[:,5:9,:,:] train_static_data_batch = train_static_data_batch_flipped[:,:,::-1,::-1] input_data = np.moveaxis(input_data, -1, 2).reshape((batch_size, -1, height, width)) true_label = np.moveaxis(true_label, -1, 2).reshape((batch_size, -1, height, width)) input_data = np.concatenate((input_data, train_static_data_batch), axis=1) train_output_queue.put( (input_data, true_label) ) thread_list = [] assert num_thread > 0 for i in range(num_thread): t = threading.Thread(target=load_train_multithread) t.start() net.train() sum_train_loss = 0.0 sum_train_iter = 0 global_step = global_step_start for epoch in range(num_epoch_to_train): np.random.shuffle(train_set) for a in range(num_iteration_per_epoch): i_j_list = [] for train_i_j in train_set[a * batch_size : (a+1) * batch_size]: i_j_list.append(train_i_j) train_input_queue.put(i_j_list) for a in range(num_iteration_per_epoch): if global_step % save_per_iteration == 0: net.eval() state_dict_0 = copy.deepcopy(net.state_dict()) torch.save(state_dict_0, out_dir + '/%09d_model.pth' % (global_step)) torch.save( { 'optimizer': optimizer.state_dict(), 'global_step': global_step, 'epoch': epoch, }, out_dir + '/%09d_optimizer.pth' % (global_step)) eval_loss_list = list() eval_loss_list = [0] with torch.no_grad(): for a in range(num_val_iteration_per_epoch): val_orig_data_batch_list = [] val_data_batch_list = [] val_data_mask_list = [] val_stat_batch_list = [] for i_j in val_set[a * batch_size_val : (a+1) * batch_size_val]: (i,j) = i_j file_path = val_data_filepath_list[i] fr = h5py.File(file_path, 'r') a_group_key = list(fr.keys())[0] data = fr[a_group_key] val_data_batch_list.append(data[j:j+num_frame_sequence,:,:,:][np.newaxis,:,:,:,:]) val_data_batch = np.concatenate(val_data_batch_list, axis=0) input_data = val_data_batch[:,:num_frame_before ,:,:,:] orig_label = val_data_batch[:, num_frame_before:,:,:,:num_channel_out] true_label = np.concatenate((orig_label[:, 0:3, :,:,:], orig_label[:, 5::3,:,:,:]), axis=1) input_data = input_data.astype(np.float32) true_label = true_label.astype(np.float32) input_data = input_data / 255.0 true_label = true_label / 255.0 input_data = np.moveaxis(input_data, -1, 2).reshape((batch_size_val, -1, height, width)) true_label = np.moveaxis(true_label, -1, 2).reshape((batch_size_val, -1, height, width)) input_data = np.concatenate((input_data,np.repeat(static_data, batch_size_val, axis=0)), axis=1) input = torch.from_numpy(input_data).float().cuda() target = torch.from_numpy(true_label).float().cuda() prediction = net(input) loss = loss_func2(prediction, target) eval_loss_list.append(loss.item()) avg_train_loss = sum_train_loss / (float(sum_train_iter)+EPS) sum_train_loss = 0.0 sum_train_iter = 0 print('global_step:', global_step, '\t', 'epoch:', epoch, \ '\t', 'train_loss:', avg_train_loss, \ '\t', 'eval_loss:', np.mean(eval_loss_list), \ '\t', datetime.now(), ) debug_out = open('res.txt', 'a') debug_out.write(str(global_step)) debug_out.write('\t') debug_out.write('%.8f' % float(avg_train_loss)) debug_out.write('\t') debug_out.write('%.8f' % float(np.mean(eval_loss_list))) debug_out.write('\n') debug_out.close() net.train() while train_output_queue.empty(): time.sleep(0.1) (input_data, true_label) = train_output_queue.get() optimizer.zero_grad() input = torch.from_numpy(input_data).float().cuda() target = torch.from_numpy(true_label).float().cuda() prediction = net(input) loss = loss_func2(prediction, target) sum_train_iter += 1 sum_train_loss += loss.item() loss.backward() optimizer.step() global_step += 1
37.596591
137
0.622236
import random from random import shuffle import numpy as np from datetime import datetime import time import queue import threading import logging from PIL import Image import itertools import re import os import glob import shutil import sys import copy import h5py from typing import Any, List, Tuple import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.nn.parallel.data_parallel import data_parallel import torch.utils.checkpoint as cp from collections import OrderedDict from torch import Tensor target_city = 'ANTWERP' other_city_list = ['ANTWERP', 'BANGKOK', 'BARCELONA', 'MOSCOW', 'BERLIN', 'CHICAGO', 'ISTANBUL', 'MELBOURNE', ] input_train_data_folder_path = '../../0_data/' + target_city + '/' + 'training' input_static_data_path = '../../0_data/' + target_city + '/' + target_city + "_static.h5" out_dir = 'output' os.environ['CUDA_VISIBLE_DEVICES'] = '0' SEED = int(time.time()) num_train_file = 180 num_frame_per_day = 288 num_frame_before = 12 num_frame_sequence = 24 num_frame_out = 6 num_sequence_per_day = num_frame_per_day - num_frame_sequence + 1 height=495 width =436 num_channel=8 num_channel_out=8 num_channel_static = 9 visual_input_channels=105 visual_output_channels=48 vector_input_channels=1 num_epoch_to_train = 100000000 save_per_iteration = 5000 global_step_start = 0 initial_checkpoint = None initial_checkpoint_optimizer = None LEARNING_RATE = 3e-4 batch_size = 2 batch_size_val = 1 num_thread=2 num_groups = 8 EPS = 1e-12 np.set_printoptions(precision=8) NUM_INPUT_CHANNEL = visual_input_channels NUM_OUTPUT_CHANNEL = visual_output_channels def get_data_filepath_list_by_year(input_data_folder_path): data_filepath_list_1 = [] data_filepath_list_2 = [] for filename in os.listdir(input_data_folder_path): if filename.split('.')[-1] != 'h5': continue if filename.startswith('2019'): data_filepath_list_1.append(os.path.join(input_data_folder_path, filename)) elif filename.startswith('2020'): data_filepath_list_2.append(os.path.join(input_data_folder_path, filename)) else: print('Error - Unknown data year\t', filename) exit(-1) data_filepath_list_1 = sorted(data_filepath_list_1) data_filepath_list_2 = sorted(data_filepath_list_2) return data_filepath_list_1, data_filepath_list_2 class Deconv3x3Block(nn.Sequential): def __init__(self, in_size: int, h_size: int, ) -> None: super(Deconv3x3Block, self).__init__() self.add_module('deconv', nn.ConvTranspose2d(in_size, h_size, kernel_size=3, stride=2, padding=1, bias=True)) self.add_module('elu', nn.ELU(inplace=True)) self.add_module('norm', nn.GroupNorm(num_groups=num_groups, num_channels=h_size)) class Conv1x1Block(nn.Sequential): def __init__(self, in_size: int, h_size: int, ) -> None: super(Conv1x1Block, self).__init__() self.add_module('conv', nn.Conv2d(in_size, h_size, kernel_size=1, stride=1, padding=0, bias=True)) class Conv3x3Block(nn.Sequential): def __init__(self, in_size: int, h_size: int, ) -> None: super(Conv3x3Block, self).__init__() self.add_module('conv', nn.Conv2d(in_size, h_size, kernel_size=3, stride=1, padding=1, bias=True)) self.add_module('elu', nn.ELU(inplace=True)) self.add_module('norm', nn.GroupNorm(num_groups=num_groups, num_channels=h_size)) class AvgBlock(nn.Sequential): def __init__(self, kernel_size: int, stride: int, padding: int) -> None: super(AvgBlock, self).__init__() self.add_module('pool', nn.AvgPool2d(kernel_size=kernel_size, stride=stride, padding=padding)) class MaxBlock(nn.Sequential): def __init__(self, kernel_size: int, stride: int, padding: int) -> None: super(MaxBlock, self).__init__() self.add_module('pool', nn.MaxPool2d(kernel_size=kernel_size, stride=stride, padding=padding)) class DownBlock(nn.Module): def __init__(self, in_size: int, h_size: int, out_size: int, do_pool: int = True): super(DownBlock, self).__init__() self.do_pool = do_pool in_size_cum = in_size self.conv_1 = Conv3x3Block( in_size=in_size_cum, h_size=h_size) in_size_cum += h_size self.conv_3 = Conv3x3Block( in_size=in_size_cum, h_size=h_size) in_size_cum += h_size self.conv_2 = Conv1x1Block( in_size=in_size_cum, h_size=out_size) def forward(self, x): batch_size = len(x) if self.do_pool: x = F.interpolate(x, scale_factor=0.7, mode='bilinear', align_corners=False, recompute_scale_factor=None) x_list = [] x_list.append(x) x = self.conv_1(x) x_list.append(x) x = torch.cat(x_list, 1) x = self.conv_3(x) x_list.append(x) x = torch.cat(x_list, 1) x = self.conv_2(x) return x def cuda(self, ): super(DownBlock, self).cuda() self.conv_1.cuda() self.conv_3.cuda() self.conv_2.cuda() return self class UpBlock(nn.Module): def __init__(self, in_size: int, in_size_2: int, h_size: int, out_size: int, ): super(UpBlock, self).__init__() self.deconv = Conv3x3Block( in_size=in_size, h_size=h_size) self.out_conv = Conv3x3Block( in_size=h_size + in_size_2, h_size=out_size) def forward(self, x1, x2): x1 = self.deconv(x1) x1 = F.interpolate(x1, size=x2.size()[2:4], scale_factor=None, mode='bilinear', align_corners=False, recompute_scale_factor=None) x = torch.cat([x2, x1], dim=1) return self.out_conv(x) def cuda(self, ): super(UpBlock, self).cuda() self.deconv.cuda() self.out_conv.cuda() return self class NetA(nn.Module): def __init__(self,): super(NetA, self).__init__() self.block0 = DownBlock(in_size=NUM_INPUT_CHANNEL, h_size=128, out_size=128, do_pool=False) self.block1 = DownBlock(in_size=128, h_size=128, out_size=128,) self.block2 = DownBlock(in_size=128, h_size=128, out_size=128, ) self.block3 = DownBlock(in_size=128, h_size=128, out_size=128, ) self.block4 = DownBlock(in_size=128, h_size=128, out_size=128, ) self.block5 = DownBlock(in_size=128, h_size=128, out_size=128, ) self.block6 = DownBlock(in_size=128, h_size=128, out_size=128,) self.block7 = DownBlock(in_size=128, h_size=128, out_size=128,) self.block20 = Conv3x3Block(in_size=128, h_size=128) self.block16 = UpBlock(in_size=128, in_size_2=128, h_size=128, out_size=128,) self.block15 = UpBlock(in_size=128, in_size_2=128, h_size=128, out_size=128,) self.block14 = UpBlock(in_size=128, in_size_2=128, h_size=128, out_size=128,) self.block13 = UpBlock(in_size=128, in_size_2=128, h_size=128, out_size=128,) self.block12 = UpBlock(in_size=128, in_size_2=128, h_size=128, out_size=128,) self.block11 = UpBlock(in_size=128, in_size_2=128 , h_size=128, out_size=128,) self.block10 = UpBlock(in_size=128, in_size_2=128 , h_size=128, out_size=128,) self.out_conv = nn.Sequential(nn.Conv2d(128*1, NUM_OUTPUT_CHANNEL, kernel_size=3, stride=1, padding=1, bias=True)) if 1: for name, m in self.named_modules(): if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d): nn.init.kaiming_normal_(m.weight) elif isinstance(m, nn.BatchNorm2d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) elif isinstance(m, nn.GroupNorm): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) elif isinstance(m, nn.Linear): nn.init.constant_(m.bias, 0) def forward(self, x): batch_size = len(x) x0 = self.block0(x) x1 = self.block1(x0) x2 = self.block2(x1) x3 = self.block3(x2) x4 = self.block4(x3) x5 = self.block5(x4) x6 = self.block6(x5) x7 = self.block7(x6) x = self.block20(x7) x = self.block16(x, x6) x = self.block15(x, x5) x = self.block14(x, x4) x = self.block13(x, x3) x = self.block12(x, x2) x = self.block11(x, x1) x = self.block10(x, x0) x = self.out_conv(x) x = torch.sigmoid(x) return x def cuda(self, ): super(NetA, self).cuda() self.block0.cuda() self.block1.cuda() self.block2.cuda() self.block3.cuda() self.block4.cuda() self.block5.cuda() self.block6.cuda() self.block7.cuda() self.block20.cuda() self.block16.cuda() self.block15.cuda() self.block14.cuda() self.block13.cuda() self.block12.cuda() self.block11.cuda() self.block10.cuda() self.out_conv.cuda() return self if __name__ == '__main__': if initial_checkpoint == None: assert global_step_start == 0 else: assert global_step_start > 0 random.seed(SEED) np.random.seed(SEED) torch.manual_seed(SEED) torch.cuda.manual_seed_all(SEED) torch.backends.cudnn.enabled = True torch.backends.cudnn.benchmark = True torch.backends.cudnn.deterministic = False try: if not os.path.exists(out_dir): os.makedirs(out_dir) except Exception: print('out_dir not made') net = NetA().cuda() optimizer = optim.Adam(filter(lambda p: p.requires_grad, net.parameters()),lr=LEARNING_RATE) loss_func2 = nn.MSELoss() if initial_checkpoint is not None: print('Loading ', initial_checkpoint) state_dict = torch.load(initial_checkpoint, map_location=lambda storage, loc: storage) net.load_state_dict(state_dict, strict=True) optimizer_state_dict_ = torch.load(initial_checkpoint_optimizer, map_location=lambda storage, loc: storage) optimizer_state_dict = optimizer_state_dict_['optimizer'] optimizer.load_state_dict(optimizer_state_dict) static_data = None if 1: file_path = input_static_data_path fr = h5py.File(file_path, 'r') a_group_key = list(fr.keys())[0] data = np.asarray(fr[a_group_key], np.uint8) static_data = data[np.newaxis,:,:,:] static_data = static_data.astype(np.float32) static_data = static_data / 255.0 static_data_list = [] if 1: for other_city in other_city_list: file_path = '../../0_data/' + other_city + '/' + other_city + "_static.h5" fr = h5py.File(file_path, 'r') a_group_key = list(fr.keys())[0] data = np.asarray(fr[a_group_key], np.uint8) static_data_ = data[np.newaxis,:,:,:] static_data_ = static_data_.astype(np.float32) static_data_ = static_data_ / 255.0 static_data_list.append(static_data_) train_static_data_index_list = [] train_data_filepath_list, val_data_filepath_list = get_data_filepath_list_by_year(input_train_data_folder_path) target_city_i = other_city_list.index(target_city) for _ in range(len(train_data_filepath_list)): train_static_data_index_list.append(target_city_i) for o, other_city in enumerate(other_city_list): if o == target_city_i: continue train_data_filepath_list_one, _ = get_data_filepath_list_by_year('../../0_data/' + other_city + '/' + 'training') for _ in range(len(train_data_filepath_list_one)): train_static_data_index_list.append(o) train_data_filepath_list += train_data_filepath_list_one train_set = [] for i in range(len(train_data_filepath_list)): for j in range(num_sequence_per_day): train_set.append( (i,j) ) num_iteration_per_epoch = int(len(train_set) / batch_size) print('num_iteration_per_epoch:', num_iteration_per_epoch) assert num_iteration_per_epoch > 10 val_set = [] val_skip_k = 0 val_skip_ratio = 5 for i in range(len(val_data_filepath_list)): for j in range(0, num_sequence_per_day, num_frame_sequence): val_skip_k += 1 if val_skip_k % val_skip_ratio == 0: val_set.append( (i,j) ) num_val_iteration_per_epoch = int(len(val_set) / batch_size_val) print('num_val_iteration_per_epoch:', num_val_iteration_per_epoch) train_input_queue = queue.Queue() train_output_queue = queue.Queue() def load_train_multithread(): while True: if train_input_queue.empty() or train_output_queue.qsize() > 8: time.sleep(0.1) continue i_j_list = train_input_queue.get() train_orig_data_batch_list = [] train_data_batch_list = [] train_data_mask_list = [] train_stat_batch_list = [] train_static_data_batch_list = [] for train_i_j in i_j_list: (i,j) = train_i_j file_path = train_data_filepath_list[i] train_static_data_batch_list.append(static_data_list[train_static_data_index_list[i]]) fr = h5py.File(file_path, 'r') a_group_key = list(fr.keys())[0] data = fr[a_group_key] train_data_batch_list.append(data[j:j+num_frame_sequence,:,:,:][np.newaxis,:,:,:,:]) train_data_batch = np.concatenate(train_data_batch_list, axis=0) train_static_data_batch = np.concatenate(train_static_data_batch_list,axis=0) input_data = train_data_batch[:,:num_frame_before ,:,:,:] orig_label = train_data_batch[:, num_frame_before:,:,:,:num_channel_out] true_label = np.concatenate((orig_label[:, 0:3, :,:,:], orig_label[:, 5::3,:,:,:] ), axis=1) input_data = input_data.astype(np.float32) true_label = true_label.astype(np.float32) input_data = input_data / 255.0 true_label = true_label / 255.0 flip_dr = np.random.randint(0,2) if flip_dr == 1: input_data_flipped = copy.deepcopy(input_data) input_data_flipped[:,:,:,:,4:8] = input_data[:,:,:,:,0:4] input_data_flipped[:,:,:,:,0:4] = input_data[:,:,:,:,4:8] input_data = input_data_flipped[:,:,::-1,::-1,:] true_label_flipped = copy.deepcopy(true_label) true_label_flipped[:,:,:,:,4:8] = true_label[:,:,:,:,0:4] true_label_flipped[:,:,:,:,0:4] = true_label[:,:,:,:,4:8] true_label = true_label_flipped[:,:,::-1,::-1,:] train_static_data_batch_flipped = copy.deepcopy(train_static_data_batch) train_static_data_batch_flipped[:,5:9,:,:] = train_static_data_batch[:,1:5,:,:] train_static_data_batch_flipped[:,1:5,:,:] = train_static_data_batch[:,5:9,:,:] train_static_data_batch = train_static_data_batch_flipped[:,:,::-1,::-1] input_data = np.moveaxis(input_data, -1, 2).reshape((batch_size, -1, height, width)) true_label = np.moveaxis(true_label, -1, 2).reshape((batch_size, -1, height, width)) input_data = np.concatenate((input_data, train_static_data_batch), axis=1) train_output_queue.put( (input_data, true_label) ) thread_list = [] assert num_thread > 0 for i in range(num_thread): t = threading.Thread(target=load_train_multithread) t.start() net.train() sum_train_loss = 0.0 sum_train_iter = 0 global_step = global_step_start for epoch in range(num_epoch_to_train): np.random.shuffle(train_set) for a in range(num_iteration_per_epoch): i_j_list = [] for train_i_j in train_set[a * batch_size : (a+1) * batch_size]: i_j_list.append(train_i_j) train_input_queue.put(i_j_list) for a in range(num_iteration_per_epoch): if global_step % save_per_iteration == 0: net.eval() state_dict_0 = copy.deepcopy(net.state_dict()) torch.save(state_dict_0, out_dir + '/%09d_model.pth' % (global_step)) torch.save( { 'optimizer': optimizer.state_dict(), 'global_step': global_step, 'epoch': epoch, }, out_dir + '/%09d_optimizer.pth' % (global_step)) eval_loss_list = list() eval_loss_list = [0] with torch.no_grad(): for a in range(num_val_iteration_per_epoch): val_orig_data_batch_list = [] val_data_batch_list = [] val_data_mask_list = [] val_stat_batch_list = [] for i_j in val_set[a * batch_size_val : (a+1) * batch_size_val]: (i,j) = i_j file_path = val_data_filepath_list[i] fr = h5py.File(file_path, 'r') a_group_key = list(fr.keys())[0] data = fr[a_group_key] val_data_batch_list.append(data[j:j+num_frame_sequence,:,:,:][np.newaxis,:,:,:,:]) val_data_batch = np.concatenate(val_data_batch_list, axis=0) input_data = val_data_batch[:,:num_frame_before ,:,:,:] orig_label = val_data_batch[:, num_frame_before:,:,:,:num_channel_out] true_label = np.concatenate((orig_label[:, 0:3, :,:,:], orig_label[:, 5::3,:,:,:]), axis=1) input_data = input_data.astype(np.float32) true_label = true_label.astype(np.float32) input_data = input_data / 255.0 true_label = true_label / 255.0 input_data = np.moveaxis(input_data, -1, 2).reshape((batch_size_val, -1, height, width)) true_label = np.moveaxis(true_label, -1, 2).reshape((batch_size_val, -1, height, width)) input_data = np.concatenate((input_data,np.repeat(static_data, batch_size_val, axis=0)), axis=1) input = torch.from_numpy(input_data).float().cuda() target = torch.from_numpy(true_label).float().cuda() prediction = net(input) loss = loss_func2(prediction, target) eval_loss_list.append(loss.item()) avg_train_loss = sum_train_loss / (float(sum_train_iter)+EPS) sum_train_loss = 0.0 sum_train_iter = 0 print('global_step:', global_step, '\t', 'epoch:', epoch, \ '\t', 'train_loss:', avg_train_loss, \ '\t', 'eval_loss:', np.mean(eval_loss_list), \ '\t', datetime.now(), ) debug_out = open('res.txt', 'a') debug_out.write(str(global_step)) debug_out.write('\t') debug_out.write('%.8f' % float(avg_train_loss)) debug_out.write('\t') debug_out.write('%.8f' % float(np.mean(eval_loss_list))) debug_out.write('\n') debug_out.close() net.train() while train_output_queue.empty(): time.sleep(0.1) (input_data, true_label) = train_output_queue.get() optimizer.zero_grad() input = torch.from_numpy(input_data).float().cuda() target = torch.from_numpy(true_label).float().cuda() prediction = net(input) loss = loss_func2(prediction, target) sum_train_iter += 1 sum_train_loss += loss.item() loss.backward() optimizer.step() global_step += 1
true
true
f72a7bae230cca8397b711afd302b87ab9ee0214
995
py
Python
techminer2/co_citation_network_degree_plot.py
jdvelasq/techminer-api
d2bb7d20c326f2fe7cc06d7005dfb3f2053ea1da
[ "MIT" ]
null
null
null
techminer2/co_citation_network_degree_plot.py
jdvelasq/techminer-api
d2bb7d20c326f2fe7cc06d7005dfb3f2053ea1da
[ "MIT" ]
null
null
null
techminer2/co_citation_network_degree_plot.py
jdvelasq/techminer-api
d2bb7d20c326f2fe7cc06d7005dfb3f2053ea1da
[ "MIT" ]
null
null
null
""" Co-citation Network / Degree Plot =============================================================================== >>> from techminer2 import * >>> directory = "/workspaces/techminer2/data/" >>> file_name = "/workspaces/techminer2/sphinx/images/co_citation_network_degree_plot.png" >>> co_citation_network_degree_plot(directory=directory).savefig(file_name) .. image:: images/co_citation_network_degree_plot.png :width: 700px :align: center """ from .co_citation_matrix import co_citation_matrix from .network import network from .network_degree_plot import network_degree_plot def co_citation_network_degree_plot( top_n=50, clustering_method="louvain", figsize=(8, 8), directory="./", ): matrix = co_citation_matrix( top_n=top_n, directory=directory, ) network_ = network( matrix=matrix, clustering_method=clustering_method, ) return network_degree_plot( network_, figsize=figsize, )
22.613636
90
0.650251
from .co_citation_matrix import co_citation_matrix from .network import network from .network_degree_plot import network_degree_plot def co_citation_network_degree_plot( top_n=50, clustering_method="louvain", figsize=(8, 8), directory="./", ): matrix = co_citation_matrix( top_n=top_n, directory=directory, ) network_ = network( matrix=matrix, clustering_method=clustering_method, ) return network_degree_plot( network_, figsize=figsize, )
true
true
f72a7ebb2f409e0799fadb3a1f5eb1b4ad602fb0
7,089
py
Python
huaweicloud-sdk-drs/huaweicloudsdkdrs/v3/model/query_compare_result_req.py
huaweicloud/huaweicloud-sdk-python-v3
7a6270390fcbf192b3882bf763e7016e6026ef78
[ "Apache-2.0" ]
64
2020-06-12T07:05:07.000Z
2022-03-30T03:32:50.000Z
huaweicloud-sdk-drs/huaweicloudsdkdrs/v3/model/query_compare_result_req.py
huaweicloud/huaweicloud-sdk-python-v3
7a6270390fcbf192b3882bf763e7016e6026ef78
[ "Apache-2.0" ]
11
2020-07-06T07:56:54.000Z
2022-01-11T11:14:40.000Z
huaweicloud-sdk-drs/huaweicloudsdkdrs/v3/model/query_compare_result_req.py
huaweicloud/huaweicloud-sdk-python-v3
7a6270390fcbf192b3882bf763e7016e6026ef78
[ "Apache-2.0" ]
24
2020-06-08T11:42:13.000Z
2022-03-04T06:44:08.000Z
# coding: utf-8 import re import six from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization class QueryCompareResultReq: """ Attributes: openapi_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. """ sensitive_list = [] openapi_types = { 'job_id': 'str', 'object_level_compare_id': 'str', 'line_compare_id': 'str', 'content_compare_id': 'str', 'current_page': 'int', 'per_page': 'int' } attribute_map = { 'job_id': 'job_id', 'object_level_compare_id': 'object_level_compare_id', 'line_compare_id': 'line_compare_id', 'content_compare_id': 'content_compare_id', 'current_page': 'current_page', 'per_page': 'per_page' } def __init__(self, job_id=None, object_level_compare_id=None, line_compare_id=None, content_compare_id=None, current_page=None, per_page=None): """QueryCompareResultReq - a model defined in huaweicloud sdk""" self._job_id = None self._object_level_compare_id = None self._line_compare_id = None self._content_compare_id = None self._current_page = None self._per_page = None self.discriminator = None self.job_id = job_id if object_level_compare_id is not None: self.object_level_compare_id = object_level_compare_id if line_compare_id is not None: self.line_compare_id = line_compare_id if content_compare_id is not None: self.content_compare_id = content_compare_id self.current_page = current_page self.per_page = per_page @property def job_id(self): """Gets the job_id of this QueryCompareResultReq. 任务id。 :return: The job_id of this QueryCompareResultReq. :rtype: str """ return self._job_id @job_id.setter def job_id(self, job_id): """Sets the job_id of this QueryCompareResultReq. 任务id。 :param job_id: The job_id of this QueryCompareResultReq. :type: str """ self._job_id = job_id @property def object_level_compare_id(self): """Gets the object_level_compare_id of this QueryCompareResultReq. 请求查询结果的对象级对比任务id。 :return: The object_level_compare_id of this QueryCompareResultReq. :rtype: str """ return self._object_level_compare_id @object_level_compare_id.setter def object_level_compare_id(self, object_level_compare_id): """Sets the object_level_compare_id of this QueryCompareResultReq. 请求查询结果的对象级对比任务id。 :param object_level_compare_id: The object_level_compare_id of this QueryCompareResultReq. :type: str """ self._object_level_compare_id = object_level_compare_id @property def line_compare_id(self): """Gets the line_compare_id of this QueryCompareResultReq. 请求查询结果的行对比任务id。 :return: The line_compare_id of this QueryCompareResultReq. :rtype: str """ return self._line_compare_id @line_compare_id.setter def line_compare_id(self, line_compare_id): """Sets the line_compare_id of this QueryCompareResultReq. 请求查询结果的行对比任务id。 :param line_compare_id: The line_compare_id of this QueryCompareResultReq. :type: str """ self._line_compare_id = line_compare_id @property def content_compare_id(self): """Gets the content_compare_id of this QueryCompareResultReq. 请求查询结果的内容对比任务id。 :return: The content_compare_id of this QueryCompareResultReq. :rtype: str """ return self._content_compare_id @content_compare_id.setter def content_compare_id(self, content_compare_id): """Sets the content_compare_id of this QueryCompareResultReq. 请求查询结果的内容对比任务id。 :param content_compare_id: The content_compare_id of this QueryCompareResultReq. :type: str """ self._content_compare_id = content_compare_id @property def current_page(self): """Gets the current_page of this QueryCompareResultReq. 分页查询的当前页码,对查询对比任务的结果生效。 :return: The current_page of this QueryCompareResultReq. :rtype: int """ return self._current_page @current_page.setter def current_page(self, current_page): """Sets the current_page of this QueryCompareResultReq. 分页查询的当前页码,对查询对比任务的结果生效。 :param current_page: The current_page of this QueryCompareResultReq. :type: int """ self._current_page = current_page @property def per_page(self): """Gets the per_page of this QueryCompareResultReq. 分页查询的每页个数,对查询对比任务的结果生效。 :return: The per_page of this QueryCompareResultReq. :rtype: int """ return self._per_page @per_page.setter def per_page(self, per_page): """Sets the per_page of this QueryCompareResultReq. 分页查询的每页个数,对查询对比任务的结果生效。 :param per_page: The per_page of this QueryCompareResultReq. :type: int """ self._per_page = per_page def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_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: if attr in self.sensitive_list: result[attr] = "****" else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" import simplejson as json if six.PY2: import sys reload(sys) sys.setdefaultencoding("utf-8") return json.dumps(sanitize_for_serialization(self), ensure_ascii=False) def __repr__(self): """For `print`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, QueryCompareResultReq): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
28.700405
147
0.616871
import re import six from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization class QueryCompareResultReq: sensitive_list = [] openapi_types = { 'job_id': 'str', 'object_level_compare_id': 'str', 'line_compare_id': 'str', 'content_compare_id': 'str', 'current_page': 'int', 'per_page': 'int' } attribute_map = { 'job_id': 'job_id', 'object_level_compare_id': 'object_level_compare_id', 'line_compare_id': 'line_compare_id', 'content_compare_id': 'content_compare_id', 'current_page': 'current_page', 'per_page': 'per_page' } def __init__(self, job_id=None, object_level_compare_id=None, line_compare_id=None, content_compare_id=None, current_page=None, per_page=None): self._job_id = None self._object_level_compare_id = None self._line_compare_id = None self._content_compare_id = None self._current_page = None self._per_page = None self.discriminator = None self.job_id = job_id if object_level_compare_id is not None: self.object_level_compare_id = object_level_compare_id if line_compare_id is not None: self.line_compare_id = line_compare_id if content_compare_id is not None: self.content_compare_id = content_compare_id self.current_page = current_page self.per_page = per_page @property def job_id(self): return self._job_id @job_id.setter def job_id(self, job_id): self._job_id = job_id @property def object_level_compare_id(self): return self._object_level_compare_id @object_level_compare_id.setter def object_level_compare_id(self, object_level_compare_id): self._object_level_compare_id = object_level_compare_id @property def line_compare_id(self): return self._line_compare_id @line_compare_id.setter def line_compare_id(self, line_compare_id): self._line_compare_id = line_compare_id @property def content_compare_id(self): return self._content_compare_id @content_compare_id.setter def content_compare_id(self, content_compare_id): self._content_compare_id = content_compare_id @property def current_page(self): return self._current_page @current_page.setter def current_page(self, current_page): self._current_page = current_page @property def per_page(self): return self._per_page @per_page.setter def per_page(self, per_page): self._per_page = per_page def to_dict(self): result = {} for attr, _ in six.iteritems(self.openapi_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: if attr in self.sensitive_list: result[attr] = "****" else: result[attr] = value return result def to_str(self): import simplejson as json if six.PY2: import sys reload(sys) sys.setdefaultencoding("utf-8") return json.dumps(sanitize_for_serialization(self), ensure_ascii=False) def __repr__(self): return self.to_str() def __eq__(self, other): if not isinstance(other, QueryCompareResultReq): return False return self.__dict__ == other.__dict__ def __ne__(self, other): return not self == other
true
true
f72a7fa08a350d2bd0ecab68ced86f7e2f4dcc7d
1,205
py
Python
ch05/solar_ce/polysol.py
jabrena/space-math
313d66f48ef642d7ce4d2c9765d55bc4bdade17b
[ "Apache-2.0" ]
1
2021-07-26T18:40:15.000Z
2021-07-26T18:40:15.000Z
ch05/solar_ce/polysol.py
jabrena/space-math
313d66f48ef642d7ce4d2c9765d55bc4bdade17b
[ "Apache-2.0" ]
24
2021-07-10T15:31:05.000Z
2022-03-17T06:43:36.000Z
ch05/solar_ce/polysol.py
jabrena/space-math
313d66f48ef642d7ce4d2c9765d55bc4bdade17b
[ "Apache-2.0" ]
null
null
null
#cas def get_infos(): import ti_graphics, ti_system fnop = lambda : None screen_w, screen_h, screen_y0, font_w, font_h, poly_set_pixel, poly_fill_rect, poly_draw_ellipse, poly_fill_circle, poly_get_key, poly_draw_string = 320, 210, 30, 10, 15, fnop, fnop, fnop, fnop, ti_system.wait_key, fnop def poly_fill_rect(x, y, w, h, c): ti_graphics.setColor(c) ti_graphics.fillRect(x, y + screen_y0, w, h) def poly_set_pixel(x, y, c): ti_graphics.setPixel(x, y + screen_y0, c) def poly_draw_ellipse(x, y, rx, ry, c): ti_graphics.setColor(c) x0, y0 = x - rx, y - ry for dy in range(1 + (y0 > int(y0))): for dx in range(1 + (x0 > int(x0))): ti_graphics.drawArc(x0 + dx, y0 + dy + screen_y0, 2 * rx, 2 * ry, 0, 3600) def poly_fill_circle(x, y, r, c): ti_graphics.setColor(c) ti_graphics.fillCircle(xx, y + screen_y0, r) def poly_draw_string(s, x, y, cf, cb): poly_fill_rect(x, y, font_w, font_h, cb) ti_graphics.setColor(cf) ti_graphics.drawString(s, x, y + screen_y0) return screen_w, screen_h, font_h, poly_set_pixel, poly_fill_rect, poly_draw_ellipse, poly_fill_circle, poly_draw_string, poly_get_key
41.551724
222
0.66556
def get_infos(): import ti_graphics, ti_system fnop = lambda : None screen_w, screen_h, screen_y0, font_w, font_h, poly_set_pixel, poly_fill_rect, poly_draw_ellipse, poly_fill_circle, poly_get_key, poly_draw_string = 320, 210, 30, 10, 15, fnop, fnop, fnop, fnop, ti_system.wait_key, fnop def poly_fill_rect(x, y, w, h, c): ti_graphics.setColor(c) ti_graphics.fillRect(x, y + screen_y0, w, h) def poly_set_pixel(x, y, c): ti_graphics.setPixel(x, y + screen_y0, c) def poly_draw_ellipse(x, y, rx, ry, c): ti_graphics.setColor(c) x0, y0 = x - rx, y - ry for dy in range(1 + (y0 > int(y0))): for dx in range(1 + (x0 > int(x0))): ti_graphics.drawArc(x0 + dx, y0 + dy + screen_y0, 2 * rx, 2 * ry, 0, 3600) def poly_fill_circle(x, y, r, c): ti_graphics.setColor(c) ti_graphics.fillCircle(xx, y + screen_y0, r) def poly_draw_string(s, x, y, cf, cb): poly_fill_rect(x, y, font_w, font_h, cb) ti_graphics.setColor(cf) ti_graphics.drawString(s, x, y + screen_y0) return screen_w, screen_h, font_h, poly_set_pixel, poly_fill_rect, poly_draw_ellipse, poly_fill_circle, poly_draw_string, poly_get_key
true
true
f72a7fd3a97aca945537b27072920ef5265cb56e
6,666
py
Python
QUBEKit/GUI/gui.py
cole-group/QUBEK
50f8a9c06396f2222a6fe058bf764a6bd7021e38
[ "MIT" ]
14
2018-10-19T12:32:39.000Z
2022-01-07T05:06:06.000Z
QUBEKit/GUI/gui.py
cole-group/QUBEK
50f8a9c06396f2222a6fe058bf764a6bd7021e38
[ "MIT" ]
null
null
null
QUBEKit/GUI/gui.py
cole-group/QUBEK
50f8a9c06396f2222a6fe058bf764a6bd7021e38
[ "MIT" ]
6
2019-02-26T13:32:58.000Z
2021-06-01T15:11:27.000Z
from QUBEKit.ligand import Ligand import os import sys from PyQt5 import QtWidgets, QtGui from PyQt5.QtCore import QUrl from PyQt5.QtWebEngineWidgets import QWebEnginePage, QWebEngineView import qdarkstyle class MainWindow(QtWidgets.QMainWindow): def __init__(self, molecule=None, parent=None): super(MainWindow, self).__init__(parent) # get the current directory self.cwd = os.getcwd() self.layout = QtWidgets.QVBoxLayout() self.tabs = QtWidgets.QTabWidget() self.ligand_tab = LigandTab(molecule_file=molecule) self.tabs.addTab(self.ligand_tab, "Ligand") self.layout.addWidget(self.tabs) # Central widget central = QtWidgets.QWidget() central.setLayout(self.layout) self.setCentralWidget(central) class LigandTab(QtWidgets.QWidget): def __init__(self, molecule_file=None, parent=None): super(LigandTab, self).__init__(parent) # Try to load the molecule if we have been passed a name if molecule_file is not None: self.molecule = Ligand(molecule_file) else: self.molecule = None # Set the main layout self.layout = QtWidgets.QVBoxLayout() # Add the main label self.main_label = QtWidgets.QLabel("QUBEKit Ligand setup") self.main_label.setFont(QtGui.QFont("Aerial", 16, QtGui.QFont.Bold)) if self.molecule is None: self.ligand_name = QtWidgets.QLabel('Load molecule .pdb .mol2 file') else: self.ligand_name = QtWidgets.QLabel(f'{self.molecule.name}') # Add the file loader button self.file_button = QtWidgets.QPushButton('Load Molecule') self.file_button.clicked.connect(self.load_molecule) # Put the label and Button in there own box top_row = QtWidgets.QHBoxLayout() top_row.addWidget(self.ligand_name) top_row.addWidget(self.file_button) if molecule_file is not None: self.viewer = Viewer(self.molecule.filename) else: self.viewer = Viewer() # Add representation settings for the ligand self.representation_label = QtWidgets.QLabel('Representation') self.representation = QtWidgets.QComboBox() self.representation.addItems(['Licorice', 'hyperball', 'spheres', 'partialCharge', 'ball+stick', 'spacefill']) # Add text change logic self.representation.currentTextChanged.connect(self.change_rep) # Add own box for layout repersentation = QtWidgets.QHBoxLayout() repersentation.addWidget(self.representation_label) repersentation.addWidget(self.representation) # Add a surface control box self.surface_group = QtWidgets.QGroupBox('Surface Controls') self.surface_group.setCheckable(True) self.surface_label = QtWidgets.QLabel('Surface file') self.surface_file = QtWidgets.QPushButton('Load surface file') self.surface_file.clicked.connect(self.load_surface) # self.find # Set the master layout self.layout.addWidget(self.main_label) self.layout.addLayout(top_row) self.layout.addWidget(self.viewer.view) self.layout.addLayout(repersentation) self.setLayout(self.layout) def load_molecule(self): """Load the molecule into the gui and make an instance of the Ligand class.""" # Open up the file explorer filename = self.load_file(['pdb', 'mol2', 'mol', 'sdf']) if '.pdb' in filename or '.mol2' in filename or 'mol' in filename: # Instance the QUBEKit class self.molecule = Ligand(filename) self.viewer.load_molecule(filename) self.ligand_name.setText(f'{self.molecule.name}') def load_surface(self): """Check if we have a valid surface file then load it into the viewer.""" filename = self.load_file(['cube']) def load_file(self, types): """Load a file name through pyqt5""" options = QtWidgets.QFileDialog.Options() options |= QtWidgets.QFileDialog.DontUseNativeDialog # Make the file type selector string file_types = 'All Files (*);;' for file_type in types: file_types += f'{str(file_type).upper()} Files (*.{file_type});;' # Get the file name from the window filename, _ = QtWidgets.QFileDialog.getOpenFileName(None, "QUBEKit File Selector", "", file_types, options=options) return filename def change_rep(self, representation): """Change the representation of the ligand.""" # Pass the representation to the viewer self.viewer.change_view(representation) class Viewer: def __init__(self, molecule_file=None): self.molecule_file = molecule_file self.view = QWebEngineView() self.view.setPage(WebEnginePage(self.view)) self.view.loadFinished.connect(self.on_load_finish) self.html_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "view.html")) self.local_url = QUrl.fromLocalFile(self.html_path) self.view.load(self.local_url) def on_load_finish(self, ok): if ok and self.molecule_file is not None: file = os.path.abspath(self.molecule_file) self.load_molecule(file) def ready(self, return_value): print(return_value) def change_view(self, representation): print(representation) self.view.page().runJavaScript(f'ChangeView("{representation}")', self.ready) def load_molecule(self, file): self.view.page().runJavaScript(f'moleculeLoader("{file}")', self.ready) def main(): sys.argv.append("--disable-web-security") app = QtWidgets.QApplication(sys.argv) if '.pdb' in sys.argv[1] or '.mol2' in sys.argv[1]: molecule_name = sys.argv[1] gui = MainWindow(molecule=molecule_name) else: gui = MainWindow() gui.setWindowTitle('QUBEKit-gui') # TODO make sure this is the correct error try: app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5()) except ReferenceError: pass gui.show() sys.exit(app.exec_()) # The molecule file is the last sys argument # Now need to pass it into the web java script class WebEnginePage(QWebEnginePage): """Class to overwirte the java script console log so it prints to terminal for debugging""" def javaScriptConsoleMessage(self, level, message, lineNumber, sourceID): print("javaScriptConsoleMessage: ", level, message, lineNumber, sourceID)
34.360825
118
0.659466
from QUBEKit.ligand import Ligand import os import sys from PyQt5 import QtWidgets, QtGui from PyQt5.QtCore import QUrl from PyQt5.QtWebEngineWidgets import QWebEnginePage, QWebEngineView import qdarkstyle class MainWindow(QtWidgets.QMainWindow): def __init__(self, molecule=None, parent=None): super(MainWindow, self).__init__(parent) self.cwd = os.getcwd() self.layout = QtWidgets.QVBoxLayout() self.tabs = QtWidgets.QTabWidget() self.ligand_tab = LigandTab(molecule_file=molecule) self.tabs.addTab(self.ligand_tab, "Ligand") self.layout.addWidget(self.tabs) central = QtWidgets.QWidget() central.setLayout(self.layout) self.setCentralWidget(central) class LigandTab(QtWidgets.QWidget): def __init__(self, molecule_file=None, parent=None): super(LigandTab, self).__init__(parent) if molecule_file is not None: self.molecule = Ligand(molecule_file) else: self.molecule = None self.layout = QtWidgets.QVBoxLayout() self.main_label = QtWidgets.QLabel("QUBEKit Ligand setup") self.main_label.setFont(QtGui.QFont("Aerial", 16, QtGui.QFont.Bold)) if self.molecule is None: self.ligand_name = QtWidgets.QLabel('Load molecule .pdb .mol2 file') else: self.ligand_name = QtWidgets.QLabel(f'{self.molecule.name}') self.file_button = QtWidgets.QPushButton('Load Molecule') self.file_button.clicked.connect(self.load_molecule) top_row = QtWidgets.QHBoxLayout() top_row.addWidget(self.ligand_name) top_row.addWidget(self.file_button) if molecule_file is not None: self.viewer = Viewer(self.molecule.filename) else: self.viewer = Viewer() self.representation_label = QtWidgets.QLabel('Representation') self.representation = QtWidgets.QComboBox() self.representation.addItems(['Licorice', 'hyperball', 'spheres', 'partialCharge', 'ball+stick', 'spacefill']) self.representation.currentTextChanged.connect(self.change_rep) repersentation = QtWidgets.QHBoxLayout() repersentation.addWidget(self.representation_label) repersentation.addWidget(self.representation) self.surface_group = QtWidgets.QGroupBox('Surface Controls') self.surface_group.setCheckable(True) self.surface_label = QtWidgets.QLabel('Surface file') self.surface_file = QtWidgets.QPushButton('Load surface file') self.surface_file.clicked.connect(self.load_surface) self.layout.addWidget(self.main_label) self.layout.addLayout(top_row) self.layout.addWidget(self.viewer.view) self.layout.addLayout(repersentation) self.setLayout(self.layout) def load_molecule(self): filename = self.load_file(['pdb', 'mol2', 'mol', 'sdf']) if '.pdb' in filename or '.mol2' in filename or 'mol' in filename: self.molecule = Ligand(filename) self.viewer.load_molecule(filename) self.ligand_name.setText(f'{self.molecule.name}') def load_surface(self): filename = self.load_file(['cube']) def load_file(self, types): options = QtWidgets.QFileDialog.Options() options |= QtWidgets.QFileDialog.DontUseNativeDialog file_types = 'All Files (*);;' for file_type in types: file_types += f'{str(file_type).upper()} Files (*.{file_type});;' filename, _ = QtWidgets.QFileDialog.getOpenFileName(None, "QUBEKit File Selector", "", file_types, options=options) return filename def change_rep(self, representation): self.viewer.change_view(representation) class Viewer: def __init__(self, molecule_file=None): self.molecule_file = molecule_file self.view = QWebEngineView() self.view.setPage(WebEnginePage(self.view)) self.view.loadFinished.connect(self.on_load_finish) self.html_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "view.html")) self.local_url = QUrl.fromLocalFile(self.html_path) self.view.load(self.local_url) def on_load_finish(self, ok): if ok and self.molecule_file is not None: file = os.path.abspath(self.molecule_file) self.load_molecule(file) def ready(self, return_value): print(return_value) def change_view(self, representation): print(representation) self.view.page().runJavaScript(f'ChangeView("{representation}")', self.ready) def load_molecule(self, file): self.view.page().runJavaScript(f'moleculeLoader("{file}")', self.ready) def main(): sys.argv.append("--disable-web-security") app = QtWidgets.QApplication(sys.argv) if '.pdb' in sys.argv[1] or '.mol2' in sys.argv[1]: molecule_name = sys.argv[1] gui = MainWindow(molecule=molecule_name) else: gui = MainWindow() gui.setWindowTitle('QUBEKit-gui') try: app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5()) except ReferenceError: pass gui.show() sys.exit(app.exec_()) class WebEnginePage(QWebEnginePage): def javaScriptConsoleMessage(self, level, message, lineNumber, sourceID): print("javaScriptConsoleMessage: ", level, message, lineNumber, sourceID)
true
true
f72a8051d6d4870f84f6443fa5863030117e9922
12,663
py
Python
rmrb/rmrb_play_ctrl/core/dns/renderer.py
fjfhccfkuk/h_s_x_r_m_r_b_python
46fe249b1b71f1245296c8b2dbd6e7c29dadade4
[ "Unlicense" ]
null
null
null
rmrb/rmrb_play_ctrl/core/dns/renderer.py
fjfhccfkuk/h_s_x_r_m_r_b_python
46fe249b1b71f1245296c8b2dbd6e7c29dadade4
[ "Unlicense" ]
null
null
null
rmrb/rmrb_play_ctrl/core/dns/renderer.py
fjfhccfkuk/h_s_x_r_m_r_b_python
46fe249b1b71f1245296c8b2dbd6e7c29dadade4
[ "Unlicense" ]
null
null
null
# Copyright (C) 2001-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """Help for building DNS wire format messages""" from io import BytesIO import struct import random import time import rmrb_play_ctrl.core.dns.exception import rmrb_play_ctrl.core.dns.tsig from ._compat import long QUESTION = 0 ANSWER = 1 AUTHORITY = 2 ADDITIONAL = 3 class Renderer(object): """Helper class for building DNS wire-format messages. Most applications can use the higher-level L{rmrb_play_ctrl.core.dns.message.Message} class and its to_wire() method to generate wire-format messages. This class is for those applications which need finer control over the generation of messages. Typical use:: r = rmrb_play_ctrl.core.dns.renderer.Renderer(id=1, flags=0x80, max_size=512) r.add_question(qname, qtype, qclass) r.add_rrset(rmrb_play_ctrl.core.dns.renderer.ANSWER, rrset_1) r.add_rrset(rmrb_play_ctrl.core.dns.renderer.ANSWER, rrset_2) r.add_rrset(rmrb_play_ctrl.core.dns.renderer.AUTHORITY, ns_rrset) r.add_edns(0, 0, 4096) r.add_rrset(rmrb_play_ctrl.core.dns.renderer.ADDTIONAL, ad_rrset_1) r.add_rrset(rmrb_play_ctrl.core.dns.renderer.ADDTIONAL, ad_rrset_2) r.write_header() r.add_tsig(keyname, secret, 300, 1, 0, '', request_mac) wire = r.get_wire() @ivar output: where rendering is written @type output: BytesIO object @ivar id: the message id @type id: int @ivar flags: the message flags @type flags: int @ivar max_size: the maximum size of the message @type max_size: int @ivar origin: the origin to use when rendering relative names @type origin: rmrb_play_ctrl.core.dns.name.Name object @ivar compress: the compression table @type compress: dict @ivar section: the section currently being rendered @type section: int (rmrb_play_ctrl.core.dns.renderer.QUESTION, rmrb_play_ctrl.core.dns.renderer.ANSWER, rmrb_play_ctrl.core.dns.renderer.AUTHORITY, or rmrb_play_ctrl.core.dns.renderer.ADDITIONAL) @ivar counts: list of the number of RRs in each section @type counts: int list of length 4 @ivar mac: the MAC of the rendered message (if TSIG was used) @type mac: string """ def __init__(self, id=None, flags=0, max_size=65535, origin=None): """Initialize a new renderer. @param id: the message id @type id: int @param flags: the DNS message flags @type flags: int @param max_size: the maximum message size; the default is 65535. If rendering results in a message greater than I{max_size}, then L{rmrb_play_ctrl.core.dns.exception.TooBig} will be raised. @type max_size: int @param origin: the origin to use when rendering relative names @type origin: rmrb_play_ctrl.core.dns.name.Name or None. """ self.output = BytesIO() if id is None: self.id = random.randint(0, 65535) else: self.id = id self.flags = flags self.max_size = max_size self.origin = origin self.compress = {} self.section = QUESTION self.counts = [0, 0, 0, 0] self.output.write(b'\x00' * 12) self.mac = '' def _rollback(self, where): """Truncate the output buffer at offset I{where}, and remove any compression table entries that pointed beyond the truncation point. @param where: the offset @type where: int """ self.output.seek(where) self.output.truncate() keys_to_delete = [] for k, v in self.compress.items(): if v >= where: keys_to_delete.append(k) for k in keys_to_delete: del self.compress[k] def _set_section(self, section): """Set the renderer's current section. Sections must be rendered order: QUESTION, ANSWER, AUTHORITY, ADDITIONAL. Sections may be empty. @param section: the section @type section: int @raises rmrb_play_ctrl.core.dns.exception.FormError: an attempt was made to set a section value less than the current section. """ if self.section != section: if self.section > section: raise rmrb_play_ctrl.core.dns.exception.FormError self.section = section def add_question(self, qname, rdtype, rdclass=rmrb_play_ctrl.core.dns.rdataclass.IN): """Add a question to the message. @param qname: the question name @type qname: rmrb_play_ctrl.core.dns.name.Name @param rdtype: the question rdata type @type rdtype: int @param rdclass: the question rdata class @type rdclass: int """ self._set_section(QUESTION) before = self.output.tell() qname.to_wire(self.output, self.compress, self.origin) self.output.write(struct.pack("!HH", rdtype, rdclass)) after = self.output.tell() if after >= self.max_size: self._rollback(before) raise rmrb_play_ctrl.core.dns.exception.TooBig self.counts[QUESTION] += 1 def add_rrset(self, section, rrset, **kw): """Add the rrset to the specified section. Any keyword arguments are passed on to the rdataset's to_wire() routine. @param section: the section @type section: int @param rrset: the rrset @type rrset: rmrb_play_ctrl.core.dns.rrset.RRset object """ self._set_section(section) before = self.output.tell() n = rrset.to_wire(self.output, self.compress, self.origin, **kw) after = self.output.tell() if after >= self.max_size: self._rollback(before) raise rmrb_play_ctrl.core.dns.exception.TooBig self.counts[section] += n def add_rdataset(self, section, name, rdataset, **kw): """Add the rdataset to the specified section, using the specified name as the owner name. Any keyword arguments are passed on to the rdataset's to_wire() routine. @param section: the section @type section: int @param name: the owner name @type name: rmrb_play_ctrl.core.dns.name.Name object @param rdataset: the rdataset @type rdataset: rmrb_play_ctrl.core.dns.rdataset.Rdataset object """ self._set_section(section) before = self.output.tell() n = rdataset.to_wire(name, self.output, self.compress, self.origin, **kw) after = self.output.tell() if after >= self.max_size: self._rollback(before) raise rmrb_play_ctrl.core.dns.exception.TooBig self.counts[section] += n def add_edns(self, edns, ednsflags, payload, options=None): """Add an EDNS OPT record to the message. @param edns: The EDNS level to use. @type edns: int @param ednsflags: EDNS flag values. @type ednsflags: int @param payload: The EDNS sender's payload field, which is the maximum size of UDP datagram the sender can handle. @type payload: int @param options: The EDNS options list @type options: list of rmrb_play_ctrl.core.dns.ermrb_play_ctrl.core.dns.Option instances @see: RFC 2671 """ # make sure the EDNS version in ednsflags agrees with edns ednsflags &= long(0xFF00FFFF) ednsflags |= (edns << 16) self._set_section(ADDITIONAL) before = self.output.tell() self.output.write(struct.pack('!BHHIH', 0, rmrb_play_ctrl.core.dns.rdatatype.OPT, payload, ednsflags, 0)) if options is not None: lstart = self.output.tell() for opt in options: stuff = struct.pack("!HH", opt.otype, 0) self.output.write(stuff) start = self.output.tell() opt.to_wire(self.output) end = self.output.tell() assert end - start < 65536 self.output.seek(start - 2) stuff = struct.pack("!H", end - start) self.output.write(stuff) self.output.seek(0, 2) lend = self.output.tell() assert lend - lstart < 65536 self.output.seek(lstart - 2) stuff = struct.pack("!H", lend - lstart) self.output.write(stuff) self.output.seek(0, 2) after = self.output.tell() if after >= self.max_size: self._rollback(before) raise rmrb_play_ctrl.core.dns.exception.TooBig self.counts[ADDITIONAL] += 1 def add_tsig(self, keyname, secret, fudge, id, tsig_error, other_data, request_mac, algorithm=rmrb_play_ctrl.core.dns.tsig.default_algorithm): """Add a TSIG signature to the message. @param keyname: the TSIG key name @type keyname: rmrb_play_ctrl.core.dns.name.Name object @param secret: the secret to use @type secret: string @param fudge: TSIG time fudge @type fudge: int @param id: the message id to encode in the tsig signature @type id: int @param tsig_error: TSIG error code; default is 0. @type tsig_error: int @param other_data: TSIG other data. @type other_data: string @param request_mac: This message is a response to the request which had the specified MAC. @type request_mac: string @param algorithm: the TSIG algorithm to use @type algorithm: rmrb_play_ctrl.core.dns.name.Name object """ self._set_section(ADDITIONAL) before = self.output.tell() s = self.output.getvalue() (tsig_rdata, self.mac, ctx) = rmrb_play_ctrl.core.dns.tsig.sign(s, keyname, secret, int(time.time()), fudge, id, tsig_error, other_data, request_mac, algorithm=algorithm) keyname.to_wire(self.output, self.compress, self.origin) self.output.write(struct.pack('!HHIH', rmrb_play_ctrl.core.dns.rdatatype.TSIG, rmrb_play_ctrl.core.dns.rdataclass.ANY, 0, 0)) rdata_start = self.output.tell() self.output.write(tsig_rdata) after = self.output.tell() assert after - rdata_start < 65536 if after >= self.max_size: self._rollback(before) raise rmrb_play_ctrl.core.dns.exception.TooBig self.output.seek(rdata_start - 2) self.output.write(struct.pack('!H', after - rdata_start)) self.counts[ADDITIONAL] += 1 self.output.seek(10) self.output.write(struct.pack('!H', self.counts[ADDITIONAL])) self.output.seek(0, 2) def write_header(self): """Write the DNS message header. Writing the DNS message header is done after all sections have been rendered, but before the optional TSIG signature is added. """ self.output.seek(0) self.output.write(struct.pack('!HHHHHH', self.id, self.flags, self.counts[0], self.counts[1], self.counts[2], self.counts[3])) self.output.seek(0, 2) def get_wire(self): """Return the wire format message. @rtype: string """ return self.output.getvalue()
38.372727
107
0.60657
from io import BytesIO import struct import random import time import rmrb_play_ctrl.core.dns.exception import rmrb_play_ctrl.core.dns.tsig from ._compat import long QUESTION = 0 ANSWER = 1 AUTHORITY = 2 ADDITIONAL = 3 class Renderer(object): def __init__(self, id=None, flags=0, max_size=65535, origin=None): self.output = BytesIO() if id is None: self.id = random.randint(0, 65535) else: self.id = id self.flags = flags self.max_size = max_size self.origin = origin self.compress = {} self.section = QUESTION self.counts = [0, 0, 0, 0] self.output.write(b'\x00' * 12) self.mac = '' def _rollback(self, where): self.output.seek(where) self.output.truncate() keys_to_delete = [] for k, v in self.compress.items(): if v >= where: keys_to_delete.append(k) for k in keys_to_delete: del self.compress[k] def _set_section(self, section): if self.section != section: if self.section > section: raise rmrb_play_ctrl.core.dns.exception.FormError self.section = section def add_question(self, qname, rdtype, rdclass=rmrb_play_ctrl.core.dns.rdataclass.IN): self._set_section(QUESTION) before = self.output.tell() qname.to_wire(self.output, self.compress, self.origin) self.output.write(struct.pack("!HH", rdtype, rdclass)) after = self.output.tell() if after >= self.max_size: self._rollback(before) raise rmrb_play_ctrl.core.dns.exception.TooBig self.counts[QUESTION] += 1 def add_rrset(self, section, rrset, **kw): self._set_section(section) before = self.output.tell() n = rrset.to_wire(self.output, self.compress, self.origin, **kw) after = self.output.tell() if after >= self.max_size: self._rollback(before) raise rmrb_play_ctrl.core.dns.exception.TooBig self.counts[section] += n def add_rdataset(self, section, name, rdataset, **kw): self._set_section(section) before = self.output.tell() n = rdataset.to_wire(name, self.output, self.compress, self.origin, **kw) after = self.output.tell() if after >= self.max_size: self._rollback(before) raise rmrb_play_ctrl.core.dns.exception.TooBig self.counts[section] += n def add_edns(self, edns, ednsflags, payload, options=None): ednsflags &= long(0xFF00FFFF) ednsflags |= (edns << 16) self._set_section(ADDITIONAL) before = self.output.tell() self.output.write(struct.pack('!BHHIH', 0, rmrb_play_ctrl.core.dns.rdatatype.OPT, payload, ednsflags, 0)) if options is not None: lstart = self.output.tell() for opt in options: stuff = struct.pack("!HH", opt.otype, 0) self.output.write(stuff) start = self.output.tell() opt.to_wire(self.output) end = self.output.tell() assert end - start < 65536 self.output.seek(start - 2) stuff = struct.pack("!H", end - start) self.output.write(stuff) self.output.seek(0, 2) lend = self.output.tell() assert lend - lstart < 65536 self.output.seek(lstart - 2) stuff = struct.pack("!H", lend - lstart) self.output.write(stuff) self.output.seek(0, 2) after = self.output.tell() if after >= self.max_size: self._rollback(before) raise rmrb_play_ctrl.core.dns.exception.TooBig self.counts[ADDITIONAL] += 1 def add_tsig(self, keyname, secret, fudge, id, tsig_error, other_data, request_mac, algorithm=rmrb_play_ctrl.core.dns.tsig.default_algorithm): self._set_section(ADDITIONAL) before = self.output.tell() s = self.output.getvalue() (tsig_rdata, self.mac, ctx) = rmrb_play_ctrl.core.dns.tsig.sign(s, keyname, secret, int(time.time()), fudge, id, tsig_error, other_data, request_mac, algorithm=algorithm) keyname.to_wire(self.output, self.compress, self.origin) self.output.write(struct.pack('!HHIH', rmrb_play_ctrl.core.dns.rdatatype.TSIG, rmrb_play_ctrl.core.dns.rdataclass.ANY, 0, 0)) rdata_start = self.output.tell() self.output.write(tsig_rdata) after = self.output.tell() assert after - rdata_start < 65536 if after >= self.max_size: self._rollback(before) raise rmrb_play_ctrl.core.dns.exception.TooBig self.output.seek(rdata_start - 2) self.output.write(struct.pack('!H', after - rdata_start)) self.counts[ADDITIONAL] += 1 self.output.seek(10) self.output.write(struct.pack('!H', self.counts[ADDITIONAL])) self.output.seek(0, 2) def write_header(self): self.output.seek(0) self.output.write(struct.pack('!HHHHHH', self.id, self.flags, self.counts[0], self.counts[1], self.counts[2], self.counts[3])) self.output.seek(0, 2) def get_wire(self): return self.output.getvalue()
true
true
f72a80ec4e6d319a9bd40ffec2bbee1e64fbb6c7
16,207
py
Python
espei/datasets.py
jwsiegel2510/ESPEI
cb72f676138c96d560d8b83cea6b7ca2da100078
[ "MIT" ]
null
null
null
espei/datasets.py
jwsiegel2510/ESPEI
cb72f676138c96d560d8b83cea6b7ca2da100078
[ "MIT" ]
null
null
null
espei/datasets.py
jwsiegel2510/ESPEI
cb72f676138c96d560d8b83cea6b7ca2da100078
[ "MIT" ]
null
null
null
import fnmatch, warnings, json, os import numpy as np from six import string_types from tinydb.storages import MemoryStorage from tinydb import where from espei.utils import PickleableTinyDB from espei.core_utils import recursive_map class DatasetError(Exception): """Exception raised when datasets are invalid.""" pass def check_dataset(dataset): """Ensure that the dataset is valid and consistent. Currently supports the following validation checks: * data shape is valid * phases and components used match phases and components entered * individual shapes of keys, such as ZPF, sublattice configs and site ratios Planned validation checks: * all required keys are present Note that this follows some of the implicit assumptions in ESPEI at the time of writing, such that conditions are only P, T, configs for single phase and essentially only T for ZPF data. Parameters ---------- dataset : dict Dictionary of the standard ESPEI dataset. Returns ------- None Raises ------ DatasetError If an error is found in the dataset """ is_activity = dataset['output'].startswith('ACR') is_zpf = dataset['output'] == 'ZPF' is_single_phase = (not is_zpf) and (not is_activity) components = dataset['components'] conditions = dataset['conditions'] values = dataset['values'] phases = dataset['phases'] if is_single_phase: solver = dataset['solver'] sublattice_configurations = solver['sublattice_configurations'] sublattice_site_ratios = solver['sublattice_site_ratios'] sublattice_occupancies = solver.get('sublattice_occupancies', None) # check for mixing is_mixing = any([any([isinstance(subl, list) for subl in config]) for config in sublattice_configurations]) # pad the values of sublattice occupancies if there is no mixing if sublattice_occupancies is None and not is_mixing: sublattice_occupancies = [None]*len(sublattice_configurations) elif sublattice_occupancies is None: raise DatasetError('At least one sublattice in the following sublattice configurations is mixing, but the "sublattice_occupancies" key is empty: {}'.format(sublattice_configurations)) if is_activity: conditions = dataset['conditions'] ref_state = dataset['reference_state'] comp_conditions = {k: v for k, v in conditions.items() if k.startswith('X_')} # check that the shape of conditions match the values num_pressure = np.atleast_1d(conditions['P']).size num_temperature = np.atleast_1d(conditions['T']).size if is_activity: values_shape = np.array(values).shape # check each composition condition is the same shape num_x_conds = [len(v) for _, v in comp_conditions.items()] if num_x_conds.count(num_x_conds[0]) != len(num_x_conds): raise DatasetError('All compositions in conditions are not the same shape. Note that conditions cannot be broadcast. Composition conditions are {}'.format(comp_conditions)) conditions_shape = (num_pressure, num_temperature, num_x_conds[0]) if conditions_shape != values_shape: raise DatasetError('Shape of conditions (P, T, compositions): {} does not match the shape of the values {}.'.format(conditions_shape, values_shape)) elif is_single_phase: values_shape = np.array(values).shape num_configs = len(dataset['solver']['sublattice_configurations']) conditions_shape = (num_pressure, num_temperature, num_configs) if conditions_shape != values_shape: raise DatasetError('Shape of conditions (P, T, configs): {} does not match the shape of the values {}.'.format(conditions_shape, values_shape)) elif is_zpf: values_shape = (len(values)) conditions_shape = (num_temperature) if conditions_shape != values_shape: raise DatasetError('Shape of conditions (T): {} does not match the shape of the values {}.'.format(conditions_shape, values_shape)) # check that all of the correct phases are present if is_zpf: phases_entered = set(phases) phases_used = set() for zpf in values: for tieline in zpf: phases_used.add(tieline[0]) if len(phases_entered - phases_used) > 0: raise DatasetError('Phases entered {} do not match phases used {}.'.format(phases_entered, phases_used)) # check that all of the components used match the components entered components_entered = set(components) components_used = set() if is_single_phase: for config in sublattice_configurations: for sl in config: if isinstance(sl, list): components_used.update(set(sl)) else: components_used.add(sl) comp_dof = 0 elif is_activity: components_used.update({c.split('_')[1] for c in comp_conditions.keys()}) # mass balance of components comp_dof = len(comp_conditions.keys()) elif is_zpf: for zpf in values: for tieline in zpf: tieline_comps = set(tieline[1]) components_used.update(tieline_comps) if len(components_entered - tieline_comps - {'VA'}) != 1: raise DatasetError('Degree of freedom error for entered components {} in tieline {} of ZPF {}'.format(components_entered, tieline, zpf)) # handle special case of mass balance in ZPFs comp_dof = 1 if len(components_entered - components_used - {'VA'}) > comp_dof or len(components_used - components_entered) > 0: raise DatasetError('Components entered {} do not match components used {}.'.format(components_entered, components_used)) # check that the ZPF values are formatted properly if is_zpf: for zpf in values: for tieline in zpf: phase = tieline[0] component_list = tieline[1] mole_fraction_list = tieline[2] # check that the phase is a string, components a list of strings, # and the fractions are a list of float if not isinstance(phase, string_types): raise DatasetError('The first element in the tieline {} for the ZPF point {} should be a string. Instead it is a {} of value {}'.format(tieline, zpf, type(phase), phase)) if not all([isinstance(comp, string_types) for comp in component_list]): raise DatasetError('The second element in the tieline {} for the ZPF point {} should be a list of strings. Instead it is a {} of value {}'.format(tieline, zpf, type(component_list), component_list)) if not all([(isinstance(mole_frac, (int, float)) or mole_frac is None) for mole_frac in mole_fraction_list]): raise DatasetError('The last element in the tieline {} for the ZPF point {} should be a list of numbers. Instead it is a {} of value {}'.format(tieline, zpf, type(mole_fraction_list), mole_fraction_list)) # check that the shape of components list and mole fractions list is the same if len(component_list) != len(mole_fraction_list): raise DatasetError('The length of the components list and mole fractions list in tieline {} for the ZPF point {} should be the same.'.format(tieline, zpf)) # check that all mole fractions are less than one mf_sum = np.nansum(np.array(mole_fraction_list, dtype=np.float)) if any([mf is not None for mf in mole_fraction_list]) and mf_sum > 1.0: raise DatasetError('Mole fractions for tieline {} for the ZPF point {} sum to greater than one.'.format(tieline, zpf)) # check that the site ratios are valid as well as site occupancies, if applicable if is_single_phase: nconfigs = len(sublattice_configurations) noccupancies = len(sublattice_occupancies) if nconfigs != noccupancies: raise DatasetError('Number of sublattice configurations ({}) does not match the number of sublattice occupancies ({})'.format(nconfigs, noccupancies)) for configuration, occupancy in zip(sublattice_configurations, sublattice_occupancies): if len(configuration) != len(sublattice_site_ratios): raise DatasetError('Sublattice configuration {} and sublattice site ratio {} describe different numbers of sublattices ({} and {}).'.format(configuration, sublattice_site_ratios, len(configuration), len(sublattice_site_ratios))) if is_mixing: configuration_shape = tuple(len(sl) if isinstance(sl, list) else 1 for sl in configuration) occupancy_shape = tuple(len(sl) if isinstance(sl, list) else 1 for sl in occupancy) if configuration_shape != occupancy_shape: raise DatasetError('The shape of sublattice configuration {} ({}) does not match the shape of occupancies {} ({})'.format(configuration, configuration_shape, occupancy, occupancy_shape)) # check that sublattice interactions are in sorted. Related to sorting in espei.core_utils.get_samples for subl in configuration: if isinstance(subl, (list, tuple)) and sorted(subl) != subl: raise DatasetError('Sublattice {} in configuration {} is must be sorted in alphabetic order ({})'.format(subl, configuration, sorted(subl))) def clean_dataset(dataset): """ Clean an ESPEI dataset dictionary. Parameters ---------- dataset : dict Dictionary of the standard ESPEI dataset. dataset : dic Returns ------- dict Modified dataset that has been cleaned Notes ----- Assumes a valid, checked dataset. Currently handles * Converting expected numeric values to floats """ dataset["conditions"] = {k: recursive_map(float, v) for k, v in dataset["conditions"].items()} solver = dataset.get("solver") if solver is not None: solver["sublattice_site_ratios"] = recursive_map(float, solver["sublattice_site_ratios"]) occupancies = solver.get("sublattice_occupancies") if occupancies is not None: solver["sublattice_occupancies"] = recursive_map(float, occupancies) if dataset["output"] == "ZPF": values = dataset["values"] new_values = [] for tieline in values: new_tieline = [] for tieline_point in tieline: if all([comp is None for comp in tieline_point[2]]): # this is a null tieline point new_tieline.append(tieline_point) else: new_tieline.append([tieline_point[0], tieline_point[1], recursive_map(float, tieline_point[2])]) new_values.append(new_tieline) dataset["values"] = new_values else: # values should be all numerical dataset["values"] = recursive_map(float, dataset["values"]) return dataset def apply_tags(datasets, tags): """ Modify datasets using the tags system Parameters ---------- datasets : PickleableTinyDB Datasets to modify tags : dict Dictionary of {tag: update_dict} Returns ------- PickleableTinyDB Notes ----- In general, everything replaces or is additive. We use the following update rules: 1. If the update value is a list, extend the existing list (empty list if key does not exist) 2. If the update value is scalar, override the previous (deleting any old value, if present) 3. If the update value is a dict, update the exist dict (empty dict if dict does not exist) 4. Otherwise, the value is updated, overriding the previous Examples -------- >>> from espei.utils import PickleableTinyDB >>> from tinydb.storages import MemoryStorage >>> ds = PickleableTinyDB(storage=MemoryStorage) >>> doc_id = ds.insert({'tags': ['dft'], 'excluded_model_contributions': ['contrib']}) >>> my_tags = {'dft': {'excluded_model_contributions': ['idmix', 'mag'], 'weight': 5.0}} >>> from espei.datasets import apply_tags >>> apply_tags(ds, my_tags) >>> all_data = ds.all() >>> all(d['excluded_model_contributions'] == ['contrib', 'idmix', 'mag'] for d in all_data) True >>> all(d['weight'] == 5.0 for d in all_data) True """ for tag, update_dict in tags.items(): matching_datasets = datasets.search(where("tags").test(lambda x: tag in x)) for newkey, newval in update_dict.items(): for match in matching_datasets: if isinstance(newval, list): match[newkey] = match.get(newkey, []) + newval elif np.isscalar(newval): match[newkey] = newval elif isinstance(newval, dict): d = match.get(newkey, dict()) d.update(newval) match[newkey] = d else: match[newkey] = newval datasets.write_back(matching_datasets) def add_ideal_exclusions(datasets): """ If there are single phase datasets present and none of them have an `excluded_model_contributions` key, add ideal exclusions automatically and emit a DeprecationWarning that this feature will be going away. Parameters ---------- datasets : PickleableTinyDB Returns ------- PickleableTinyDB """ all_single_phase = datasets.search(where('solver').exists()) no_exclusions = datasets.search(where('solver').exists() & (~where('excluded_model_contributions').exists())) if len(all_single_phase) > 0 and len(all_single_phase) == len(no_exclusions): idmix_warning = "Single phase datasets are present, but there are no specified `excluded_model_contributions` keys present. " + \ "'idmix' exclusion will be added automatically for backwards compatibility, but this will go away in ESPEI v0.8. " + \ "If you want ideal mixing contributions to be excluded, see the documentation for building datasets: http://espei.org/en/latest/input_data.html" warnings.warn(idmix_warning, DeprecationWarning) print(idmix_warning) import espei if int(espei.__version__.split('.')[1]) >= 8 or int(espei.__version__.split('.')[0]) > 0: raise ValueError("ESPEI developer: remove the automatic addition of ideal mixing exclusions") for ds in all_single_phase: ds['excluded_model_contributions'] = ['idmix'] datasets.write_back(all_single_phase) return datasets def load_datasets(dataset_filenames): """ Create a PickelableTinyDB with the data from a list of filenames. Parameters ---------- dataset_filenames : [str] List of filenames to load as datasets Returns ------- PickleableTinyDB """ ds_database = PickleableTinyDB(storage=MemoryStorage) for fname in dataset_filenames: with open(fname) as file_: try: d = json.load(file_) check_dataset(d) ds_database.insert(clean_dataset(d)) except ValueError as e: raise ValueError('JSON Error in {}: {}'.format(fname, e)) except DatasetError as e: raise DatasetError('Dataset Error in {}: {}'.format(fname, e)) return ds_database def recursive_glob(start, pattern='*.json'): """ Recursively glob for the given pattern from the start directory. Parameters ---------- start : str Path of the directory to walk while for file globbing pattern : str Filename pattern to match in the glob. Returns ------- [str] List of matched filenames """ matches = [] for root, dirnames, filenames in os.walk(start): for filename in fnmatch.filter(filenames, pattern): matches.append(os.path.join(root, filename)) return sorted(matches)
45.144847
244
0.649596
import fnmatch, warnings, json, os import numpy as np from six import string_types from tinydb.storages import MemoryStorage from tinydb import where from espei.utils import PickleableTinyDB from espei.core_utils import recursive_map class DatasetError(Exception): pass def check_dataset(dataset): is_activity = dataset['output'].startswith('ACR') is_zpf = dataset['output'] == 'ZPF' is_single_phase = (not is_zpf) and (not is_activity) components = dataset['components'] conditions = dataset['conditions'] values = dataset['values'] phases = dataset['phases'] if is_single_phase: solver = dataset['solver'] sublattice_configurations = solver['sublattice_configurations'] sublattice_site_ratios = solver['sublattice_site_ratios'] sublattice_occupancies = solver.get('sublattice_occupancies', None) is_mixing = any([any([isinstance(subl, list) for subl in config]) for config in sublattice_configurations]) if sublattice_occupancies is None and not is_mixing: sublattice_occupancies = [None]*len(sublattice_configurations) elif sublattice_occupancies is None: raise DatasetError('At least one sublattice in the following sublattice configurations is mixing, but the "sublattice_occupancies" key is empty: {}'.format(sublattice_configurations)) if is_activity: conditions = dataset['conditions'] ref_state = dataset['reference_state'] comp_conditions = {k: v for k, v in conditions.items() if k.startswith('X_')} num_pressure = np.atleast_1d(conditions['P']).size num_temperature = np.atleast_1d(conditions['T']).size if is_activity: values_shape = np.array(values).shape num_x_conds = [len(v) for _, v in comp_conditions.items()] if num_x_conds.count(num_x_conds[0]) != len(num_x_conds): raise DatasetError('All compositions in conditions are not the same shape. Note that conditions cannot be broadcast. Composition conditions are {}'.format(comp_conditions)) conditions_shape = (num_pressure, num_temperature, num_x_conds[0]) if conditions_shape != values_shape: raise DatasetError('Shape of conditions (P, T, compositions): {} does not match the shape of the values {}.'.format(conditions_shape, values_shape)) elif is_single_phase: values_shape = np.array(values).shape num_configs = len(dataset['solver']['sublattice_configurations']) conditions_shape = (num_pressure, num_temperature, num_configs) if conditions_shape != values_shape: raise DatasetError('Shape of conditions (P, T, configs): {} does not match the shape of the values {}.'.format(conditions_shape, values_shape)) elif is_zpf: values_shape = (len(values)) conditions_shape = (num_temperature) if conditions_shape != values_shape: raise DatasetError('Shape of conditions (T): {} does not match the shape of the values {}.'.format(conditions_shape, values_shape)) if is_zpf: phases_entered = set(phases) phases_used = set() for zpf in values: for tieline in zpf: phases_used.add(tieline[0]) if len(phases_entered - phases_used) > 0: raise DatasetError('Phases entered {} do not match phases used {}.'.format(phases_entered, phases_used)) components_entered = set(components) components_used = set() if is_single_phase: for config in sublattice_configurations: for sl in config: if isinstance(sl, list): components_used.update(set(sl)) else: components_used.add(sl) comp_dof = 0 elif is_activity: components_used.update({c.split('_')[1] for c in comp_conditions.keys()}) comp_dof = len(comp_conditions.keys()) elif is_zpf: for zpf in values: for tieline in zpf: tieline_comps = set(tieline[1]) components_used.update(tieline_comps) if len(components_entered - tieline_comps - {'VA'}) != 1: raise DatasetError('Degree of freedom error for entered components {} in tieline {} of ZPF {}'.format(components_entered, tieline, zpf)) comp_dof = 1 if len(components_entered - components_used - {'VA'}) > comp_dof or len(components_used - components_entered) > 0: raise DatasetError('Components entered {} do not match components used {}.'.format(components_entered, components_used)) if is_zpf: for zpf in values: for tieline in zpf: phase = tieline[0] component_list = tieline[1] mole_fraction_list = tieline[2] if not isinstance(phase, string_types): raise DatasetError('The first element in the tieline {} for the ZPF point {} should be a string. Instead it is a {} of value {}'.format(tieline, zpf, type(phase), phase)) if not all([isinstance(comp, string_types) for comp in component_list]): raise DatasetError('The second element in the tieline {} for the ZPF point {} should be a list of strings. Instead it is a {} of value {}'.format(tieline, zpf, type(component_list), component_list)) if not all([(isinstance(mole_frac, (int, float)) or mole_frac is None) for mole_frac in mole_fraction_list]): raise DatasetError('The last element in the tieline {} for the ZPF point {} should be a list of numbers. Instead it is a {} of value {}'.format(tieline, zpf, type(mole_fraction_list), mole_fraction_list)) if len(component_list) != len(mole_fraction_list): raise DatasetError('The length of the components list and mole fractions list in tieline {} for the ZPF point {} should be the same.'.format(tieline, zpf)) mf_sum = np.nansum(np.array(mole_fraction_list, dtype=np.float)) if any([mf is not None for mf in mole_fraction_list]) and mf_sum > 1.0: raise DatasetError('Mole fractions for tieline {} for the ZPF point {} sum to greater than one.'.format(tieline, zpf)) if is_single_phase: nconfigs = len(sublattice_configurations) noccupancies = len(sublattice_occupancies) if nconfigs != noccupancies: raise DatasetError('Number of sublattice configurations ({}) does not match the number of sublattice occupancies ({})'.format(nconfigs, noccupancies)) for configuration, occupancy in zip(sublattice_configurations, sublattice_occupancies): if len(configuration) != len(sublattice_site_ratios): raise DatasetError('Sublattice configuration {} and sublattice site ratio {} describe different numbers of sublattices ({} and {}).'.format(configuration, sublattice_site_ratios, len(configuration), len(sublattice_site_ratios))) if is_mixing: configuration_shape = tuple(len(sl) if isinstance(sl, list) else 1 for sl in configuration) occupancy_shape = tuple(len(sl) if isinstance(sl, list) else 1 for sl in occupancy) if configuration_shape != occupancy_shape: raise DatasetError('The shape of sublattice configuration {} ({}) does not match the shape of occupancies {} ({})'.format(configuration, configuration_shape, occupancy, occupancy_shape)) for subl in configuration: if isinstance(subl, (list, tuple)) and sorted(subl) != subl: raise DatasetError('Sublattice {} in configuration {} is must be sorted in alphabetic order ({})'.format(subl, configuration, sorted(subl))) def clean_dataset(dataset): dataset["conditions"] = {k: recursive_map(float, v) for k, v in dataset["conditions"].items()} solver = dataset.get("solver") if solver is not None: solver["sublattice_site_ratios"] = recursive_map(float, solver["sublattice_site_ratios"]) occupancies = solver.get("sublattice_occupancies") if occupancies is not None: solver["sublattice_occupancies"] = recursive_map(float, occupancies) if dataset["output"] == "ZPF": values = dataset["values"] new_values = [] for tieline in values: new_tieline = [] for tieline_point in tieline: if all([comp is None for comp in tieline_point[2]]): new_tieline.append(tieline_point) else: new_tieline.append([tieline_point[0], tieline_point[1], recursive_map(float, tieline_point[2])]) new_values.append(new_tieline) dataset["values"] = new_values else: dataset["values"] = recursive_map(float, dataset["values"]) return dataset def apply_tags(datasets, tags): for tag, update_dict in tags.items(): matching_datasets = datasets.search(where("tags").test(lambda x: tag in x)) for newkey, newval in update_dict.items(): for match in matching_datasets: if isinstance(newval, list): match[newkey] = match.get(newkey, []) + newval elif np.isscalar(newval): match[newkey] = newval elif isinstance(newval, dict): d = match.get(newkey, dict()) d.update(newval) match[newkey] = d else: match[newkey] = newval datasets.write_back(matching_datasets) def add_ideal_exclusions(datasets): all_single_phase = datasets.search(where('solver').exists()) no_exclusions = datasets.search(where('solver').exists() & (~where('excluded_model_contributions').exists())) if len(all_single_phase) > 0 and len(all_single_phase) == len(no_exclusions): idmix_warning = "Single phase datasets are present, but there are no specified `excluded_model_contributions` keys present. " + \ "'idmix' exclusion will be added automatically for backwards compatibility, but this will go away in ESPEI v0.8. " + \ "If you want ideal mixing contributions to be excluded, see the documentation for building datasets: http://espei.org/en/latest/input_data.html" warnings.warn(idmix_warning, DeprecationWarning) print(idmix_warning) import espei if int(espei.__version__.split('.')[1]) >= 8 or int(espei.__version__.split('.')[0]) > 0: raise ValueError("ESPEI developer: remove the automatic addition of ideal mixing exclusions") for ds in all_single_phase: ds['excluded_model_contributions'] = ['idmix'] datasets.write_back(all_single_phase) return datasets def load_datasets(dataset_filenames): ds_database = PickleableTinyDB(storage=MemoryStorage) for fname in dataset_filenames: with open(fname) as file_: try: d = json.load(file_) check_dataset(d) ds_database.insert(clean_dataset(d)) except ValueError as e: raise ValueError('JSON Error in {}: {}'.format(fname, e)) except DatasetError as e: raise DatasetError('Dataset Error in {}: {}'.format(fname, e)) return ds_database def recursive_glob(start, pattern='*.json'): matches = [] for root, dirnames, filenames in os.walk(start): for filename in fnmatch.filter(filenames, pattern): matches.append(os.path.join(root, filename)) return sorted(matches)
true
true
f72a8175c066c50bcc168821cbcb8091f9cd439a
6,618
py
Python
Collections-a-installer/community-general-2.4.0/plugins/modules/ipa_service.py
d-amien-b/simple-getwordpress
da90d515a0aa837b633d50db4d91d22b031c04a2
[ "MIT" ]
22
2021-07-16T08:11:22.000Z
2022-03-31T07:15:34.000Z
Collections-a-installer/community-general-2.4.0/plugins/modules/ipa_service.py
d-amien-b/simple-getwordpress
da90d515a0aa837b633d50db4d91d22b031c04a2
[ "MIT" ]
1
2022-03-12T02:25:26.000Z
2022-03-12T02:25:26.000Z
Collections-a-installer/community-general-2.4.0/plugins/modules/ipa_service.py
d-amien-b/simple-getwordpress
da90d515a0aa837b633d50db4d91d22b031c04a2
[ "MIT" ]
39
2021-07-05T02:31:42.000Z
2022-03-31T02:46:03.000Z
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2018, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = r''' --- module: ipa_service author: Cédric Parent (@cprh) short_description: Manage FreeIPA service description: - Add and delete an IPA service using IPA API. options: krbcanonicalname: description: - Principal of the service. - Can not be changed as it is the unique identifier. required: true aliases: ["name"] type: str hosts: description: - Defines the list of 'ManagedBy' hosts. required: false type: list elements: str force: description: - Force principal name even if host is not in DNS. required: false type: bool state: description: State to ensure. required: false default: present choices: ["absent", "present"] type: str extends_documentation_fragment: - community.general.ipa.documentation ''' EXAMPLES = r''' - name: Ensure service is present community.general.ipa_service: name: http/host01.example.com state: present ipa_host: ipa.example.com ipa_user: admin ipa_pass: topsecret - name: Ensure service is absent community.general.ipa_service: name: http/host01.example.com state: absent ipa_host: ipa.example.com ipa_user: admin ipa_pass: topsecret - name: Changing Managing hosts list community.general.ipa_service: name: http/host01.example.com host: - host01.example.com - host02.example.com ipa_host: ipa.example.com ipa_user: admin ipa_pass: topsecret ''' RETURN = r''' service: description: Service as returned by IPA API. returned: always type: dict ''' import traceback from ansible.module_utils.basic import AnsibleModule from ansible_collections.community.general.plugins.module_utils.ipa import IPAClient, ipa_argument_spec from ansible.module_utils._text import to_native class ServiceIPAClient(IPAClient): def __init__(self, module, host, port, protocol): super(ServiceIPAClient, self).__init__(module, host, port, protocol) def service_find(self, name): return self._post_json(method='service_find', name=None, item={'all': True, 'krbcanonicalname': name}) def service_add(self, name, service): return self._post_json(method='service_add', name=name, item=service) def service_mod(self, name, service): return self._post_json(method='service_mod', name=name, item=service) def service_del(self, name): return self._post_json(method='service_del', name=name) def service_disable(self, name): return self._post_json(method='service_disable', name=name) def service_add_host(self, name, item): return self._post_json(method='service_add_host', name=name, item={'host': item}) def service_remove_host(self, name, item): return self._post_json(method='service_remove_host', name=name, item={'host': item}) def get_service_dict(force=None, krbcanonicalname=None): data = {} if force is not None: data['force'] = force if krbcanonicalname is not None: data['krbcanonicalname'] = krbcanonicalname return data def get_service_diff(client, ipa_host, module_service): non_updateable_keys = ['force', 'krbcanonicalname'] for key in non_updateable_keys: if key in module_service: del module_service[key] return client.get_diff(ipa_data=ipa_host, module_data=module_service) def ensure(module, client): name = module.params['krbcanonicalname'] state = module.params['state'] hosts = module.params['hosts'] ipa_service = client.service_find(name=name) module_service = get_service_dict(force=module.params['force']) changed = False if state in ['present', 'enabled', 'disabled']: if not ipa_service: changed = True if not module.check_mode: client.service_add(name=name, service=module_service) else: diff = get_service_diff(client, ipa_service, module_service) if len(diff) > 0: changed = True if not module.check_mode: data = {} for key in diff: data[key] = module_service.get(key) client.service_mod(name=name, service=data) if hosts is not None: if 'managedby_host' in ipa_service: for host in ipa_service['managedby_host']: if host not in hosts: if not module.check_mode: client.service_remove_host(name=name, item=host) changed = True for host in hosts: if host not in ipa_service['managedby_host']: if not module.check_mode: client.service_add_host(name=name, item=host) changed = True else: for host in hosts: if not module.check_mode: client.service_add_host(name=name, item=host) changed = True else: if ipa_service: changed = True if not module.check_mode: client.service_del(name=name) return changed, client.service_find(name=name) def main(): argument_spec = ipa_argument_spec() argument_spec.update( krbcanonicalname=dict(type='str', required=True, aliases=['name']), force=dict(type='bool', required=False), hosts=dict(type='list', required=False, elements='str'), state=dict(type='str', required=False, default='present', choices=['present', 'absent'])) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) client = ServiceIPAClient(module=module, host=module.params['ipa_host'], port=module.params['ipa_port'], protocol=module.params['ipa_prot']) try: client.login(username=module.params['ipa_user'], password=module.params['ipa_pass']) changed, host = ensure(module, client) module.exit_json(changed=changed, host=host) except Exception as e: module.fail_json(msg=to_native(e), exception=traceback.format_exc()) if __name__ == '__main__': main()
31.665072
110
0.636144
from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = r''' --- module: ipa_service author: Cédric Parent (@cprh) short_description: Manage FreeIPA service description: - Add and delete an IPA service using IPA API. options: krbcanonicalname: description: - Principal of the service. - Can not be changed as it is the unique identifier. required: true aliases: ["name"] type: str hosts: description: - Defines the list of 'ManagedBy' hosts. required: false type: list elements: str force: description: - Force principal name even if host is not in DNS. required: false type: bool state: description: State to ensure. required: false default: present choices: ["absent", "present"] type: str extends_documentation_fragment: - community.general.ipa.documentation ''' EXAMPLES = r''' - name: Ensure service is present community.general.ipa_service: name: http/host01.example.com state: present ipa_host: ipa.example.com ipa_user: admin ipa_pass: topsecret - name: Ensure service is absent community.general.ipa_service: name: http/host01.example.com state: absent ipa_host: ipa.example.com ipa_user: admin ipa_pass: topsecret - name: Changing Managing hosts list community.general.ipa_service: name: http/host01.example.com host: - host01.example.com - host02.example.com ipa_host: ipa.example.com ipa_user: admin ipa_pass: topsecret ''' RETURN = r''' service: description: Service as returned by IPA API. returned: always type: dict ''' import traceback from ansible.module_utils.basic import AnsibleModule from ansible_collections.community.general.plugins.module_utils.ipa import IPAClient, ipa_argument_spec from ansible.module_utils._text import to_native class ServiceIPAClient(IPAClient): def __init__(self, module, host, port, protocol): super(ServiceIPAClient, self).__init__(module, host, port, protocol) def service_find(self, name): return self._post_json(method='service_find', name=None, item={'all': True, 'krbcanonicalname': name}) def service_add(self, name, service): return self._post_json(method='service_add', name=name, item=service) def service_mod(self, name, service): return self._post_json(method='service_mod', name=name, item=service) def service_del(self, name): return self._post_json(method='service_del', name=name) def service_disable(self, name): return self._post_json(method='service_disable', name=name) def service_add_host(self, name, item): return self._post_json(method='service_add_host', name=name, item={'host': item}) def service_remove_host(self, name, item): return self._post_json(method='service_remove_host', name=name, item={'host': item}) def get_service_dict(force=None, krbcanonicalname=None): data = {} if force is not None: data['force'] = force if krbcanonicalname is not None: data['krbcanonicalname'] = krbcanonicalname return data def get_service_diff(client, ipa_host, module_service): non_updateable_keys = ['force', 'krbcanonicalname'] for key in non_updateable_keys: if key in module_service: del module_service[key] return client.get_diff(ipa_data=ipa_host, module_data=module_service) def ensure(module, client): name = module.params['krbcanonicalname'] state = module.params['state'] hosts = module.params['hosts'] ipa_service = client.service_find(name=name) module_service = get_service_dict(force=module.params['force']) changed = False if state in ['present', 'enabled', 'disabled']: if not ipa_service: changed = True if not module.check_mode: client.service_add(name=name, service=module_service) else: diff = get_service_diff(client, ipa_service, module_service) if len(diff) > 0: changed = True if not module.check_mode: data = {} for key in diff: data[key] = module_service.get(key) client.service_mod(name=name, service=data) if hosts is not None: if 'managedby_host' in ipa_service: for host in ipa_service['managedby_host']: if host not in hosts: if not module.check_mode: client.service_remove_host(name=name, item=host) changed = True for host in hosts: if host not in ipa_service['managedby_host']: if not module.check_mode: client.service_add_host(name=name, item=host) changed = True else: for host in hosts: if not module.check_mode: client.service_add_host(name=name, item=host) changed = True else: if ipa_service: changed = True if not module.check_mode: client.service_del(name=name) return changed, client.service_find(name=name) def main(): argument_spec = ipa_argument_spec() argument_spec.update( krbcanonicalname=dict(type='str', required=True, aliases=['name']), force=dict(type='bool', required=False), hosts=dict(type='list', required=False, elements='str'), state=dict(type='str', required=False, default='present', choices=['present', 'absent'])) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) client = ServiceIPAClient(module=module, host=module.params['ipa_host'], port=module.params['ipa_port'], protocol=module.params['ipa_prot']) try: client.login(username=module.params['ipa_user'], password=module.params['ipa_pass']) changed, host = ensure(module, client) module.exit_json(changed=changed, host=host) except Exception as e: module.fail_json(msg=to_native(e), exception=traceback.format_exc()) if __name__ == '__main__': main()
true
true
f72a82afacbfe8c4a9d386c3c67b25d21ca8d4cb
3,193
py
Python
var/spack/repos/builtin/packages/meson/package.py
jjellio/spack
1fa16c1b9b08119be429821fbd2f3251458d5063
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
1
2020-12-28T14:38:41.000Z
2020-12-28T14:38:41.000Z
var/spack/repos/builtin/packages/meson/package.py
jjellio/spack
1fa16c1b9b08119be429821fbd2f3251458d5063
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
11
2021-02-15T01:32:22.000Z
2022-03-31T06:06:05.000Z
var/spack/repos/builtin/packages/meson/package.py
karcaw/spack
2b3ca6c3e39f486c9cf277f2ca8fef12d54300c2
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
null
null
null
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Meson(PythonPackage): """Meson is a portable open source build system meant to be both extremely fast, and as user friendly as possible.""" homepage = "http://mesonbuild.com/" url = "https://github.com/mesonbuild/meson/archive/0.49.0.tar.gz" maintainers = ['michaelkuhn'] version('0.57.1', sha256='0c043c9b5350e9087cd4f6becf6c0d10b1d618ca3f919e0dcca2cdf342360d5d') version('0.57.0', sha256='fd26a27c1a509240c668ebd29d280649d9239cf8684ead51d5cb499d1e1188bd') version('0.56.2', sha256='aaae961c3413033789248ffe6762589e80b6cf487c334d0b808e31a32c48f35f') version('0.56.0', sha256='a9ca7adf66dc69fbb7e583f7c7aef16b9fe56ec2874a3d58747e69a3affdf300') version('0.55.3', sha256='2b276df50c5b13ccdbfb14d3333141e9e7985aca31b60400b3f3e0be2ee6897e') version('0.55.2', sha256='56244896e56c2b619f819d047b6de412ecc5250975ee8717f1e329113d178e06') version('0.55.1', sha256='c7ebf2fff5934a974c7edd1aebb5fc9c3e1da5ae3184a29581fde917638eea39') version('0.55.0', sha256='9034c943c8cf4d734c0e18e5ba038dd762fcdcc614c45b41703305da8382e90c') version('0.54.3', sha256='c25caff342b5368bfe33fab6108f454fcf12e2f2cef70817205872ddef669e8b') version('0.54.2', sha256='85cafdc70ae7d1d9d506e7356b917c649c4df2077bd6a0382db37648aa4ecbdb') version('0.54.1', sha256='854e8b94ab36e5aece813d2b2aee8a639bd52201dfea50890722ac9128e2f59e') version('0.54.0', sha256='95efdbaa7cb3e915ab9a7b26b1412475398fdc3e834842a780f1646c7764f2d9') version('0.53.2', sha256='eab4f5d5dde12d002b7ddd958a9a0658589b63622b6cea2715e0235b95917888') version('0.49.1', sha256='a944e7f25a2bc8e4ba3502ab5835d8a8b8f2530415c9d6fcffb53e0abaea2ced') version('0.49.0', sha256='11bc959e7173e714e4a4e85dd2bd9d0149b0a51c8ba82d5f44cc63735f603c74') version('0.42.0', sha256='6c318a2da3859326a37f8a380e3c50e97aaabff6990067218dffffea674ed76f') version('0.41.2', sha256='2daf448d3f2479d60e30617451f09bf02d26304dd1bd12ee1de936a53e42c7a4') version('0.41.1', sha256='a48901f02ffeb9ff5cf5361d71b1fca202f9cd72998043ad011fc5de0294cf8b') depends_on('python@3.6:', when='@0.57.0:', type=('build', 'run')) depends_on('python@3.5:', type=('build', 'run')) depends_on('py-setuptools', type=('build', 'run')) depends_on('ninja', type='run') # By default, Meson strips the rpath on installation. This patch disables # rpath modification completely to make sure that Spack's rpath changes # are not reverted. patch('rpath-0.49.patch', when='@0.49:0.53') patch('rpath-0.54.patch', when='@0.54:0.55') patch('rpath-0.56.patch', when='@0.56') executables = ['^meson$'] @classmethod def determine_version(cls, exe): return Executable(exe)('--version', output=str, error=str).rstrip() def setup_dependent_build_environment(self, env, dependent_spec): # https://github.com/pybind/pybind11/issues/595 if self.spec.satisfies('platform=darwin'): env.set('STRIP', 'strip -x')
53.216667
96
0.757282
from spack import * class Meson(PythonPackage): homepage = "http://mesonbuild.com/" url = "https://github.com/mesonbuild/meson/archive/0.49.0.tar.gz" maintainers = ['michaelkuhn'] version('0.57.1', sha256='0c043c9b5350e9087cd4f6becf6c0d10b1d618ca3f919e0dcca2cdf342360d5d') version('0.57.0', sha256='fd26a27c1a509240c668ebd29d280649d9239cf8684ead51d5cb499d1e1188bd') version('0.56.2', sha256='aaae961c3413033789248ffe6762589e80b6cf487c334d0b808e31a32c48f35f') version('0.56.0', sha256='a9ca7adf66dc69fbb7e583f7c7aef16b9fe56ec2874a3d58747e69a3affdf300') version('0.55.3', sha256='2b276df50c5b13ccdbfb14d3333141e9e7985aca31b60400b3f3e0be2ee6897e') version('0.55.2', sha256='56244896e56c2b619f819d047b6de412ecc5250975ee8717f1e329113d178e06') version('0.55.1', sha256='c7ebf2fff5934a974c7edd1aebb5fc9c3e1da5ae3184a29581fde917638eea39') version('0.55.0', sha256='9034c943c8cf4d734c0e18e5ba038dd762fcdcc614c45b41703305da8382e90c') version('0.54.3', sha256='c25caff342b5368bfe33fab6108f454fcf12e2f2cef70817205872ddef669e8b') version('0.54.2', sha256='85cafdc70ae7d1d9d506e7356b917c649c4df2077bd6a0382db37648aa4ecbdb') version('0.54.1', sha256='854e8b94ab36e5aece813d2b2aee8a639bd52201dfea50890722ac9128e2f59e') version('0.54.0', sha256='95efdbaa7cb3e915ab9a7b26b1412475398fdc3e834842a780f1646c7764f2d9') version('0.53.2', sha256='eab4f5d5dde12d002b7ddd958a9a0658589b63622b6cea2715e0235b95917888') version('0.49.1', sha256='a944e7f25a2bc8e4ba3502ab5835d8a8b8f2530415c9d6fcffb53e0abaea2ced') version('0.49.0', sha256='11bc959e7173e714e4a4e85dd2bd9d0149b0a51c8ba82d5f44cc63735f603c74') version('0.42.0', sha256='6c318a2da3859326a37f8a380e3c50e97aaabff6990067218dffffea674ed76f') version('0.41.2', sha256='2daf448d3f2479d60e30617451f09bf02d26304dd1bd12ee1de936a53e42c7a4') version('0.41.1', sha256='a48901f02ffeb9ff5cf5361d71b1fca202f9cd72998043ad011fc5de0294cf8b') depends_on('python@3.6:', when='@0.57.0:', type=('build', 'run')) depends_on('python@3.5:', type=('build', 'run')) depends_on('py-setuptools', type=('build', 'run')) depends_on('ninja', type='run') # are not reverted. patch('rpath-0.49.patch', when='@0.49:0.53') patch('rpath-0.54.patch', when='@0.54:0.55') patch('rpath-0.56.patch', when='@0.56') executables = ['^meson$'] @classmethod def determine_version(cls, exe): return Executable(exe)('--version', output=str, error=str).rstrip() def setup_dependent_build_environment(self, env, dependent_spec): # https://github.com/pybind/pybind11/issues/595 if self.spec.satisfies('platform=darwin'): env.set('STRIP', 'strip -x')
true
true
f72a82e3656b23a98910f3bc1d1712b42ddd274d
30,279
py
Python
neutron/plugins/openvswitch/ovs_neutron_plugin.py
ksshanam/neutron-vrrp
f9fb7f9b41adc0de401cc118a4d97026d3abb6e0
[ "Apache-2.0" ]
null
null
null
neutron/plugins/openvswitch/ovs_neutron_plugin.py
ksshanam/neutron-vrrp
f9fb7f9b41adc0de401cc118a4d97026d3abb6e0
[ "Apache-2.0" ]
null
null
null
neutron/plugins/openvswitch/ovs_neutron_plugin.py
ksshanam/neutron-vrrp
f9fb7f9b41adc0de401cc118a4d97026d3abb6e0
[ "Apache-2.0" ]
null
null
null
# Copyright 2011 VMware, 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. import sys from oslo.config import cfg from neutron.agent import securitygroups_rpc as sg_rpc from neutron.api.rpc.agentnotifiers import dhcp_rpc_agent_api from neutron.api.rpc.agentnotifiers import l3_rpc_agent_api from neutron.api.rpc.handlers import dhcp_rpc from neutron.api.rpc.handlers import l3_rpc from neutron.api.v2 import attributes from neutron.common import constants as q_const from neutron.common import exceptions as n_exc from neutron.common import rpc as n_rpc from neutron.common import topics from neutron.common import utils from neutron.db import agents_db from neutron.db import agentschedulers_db from neutron.db import allowedaddresspairs_db as addr_pair_db from neutron.db import db_base_plugin_v2 from neutron.db import external_net_db from neutron.db import extradhcpopt_db from neutron.db import extraroute_db from neutron.db import l3_agentschedulers_db from neutron.db import l3_gwmode_db from neutron.db import portbindings_db from neutron.db import quota_db # noqa from neutron.db import securitygroups_rpc_base as sg_db_rpc from neutron.extensions import allowedaddresspairs as addr_pair from neutron.extensions import extra_dhcp_opt as edo_ext from neutron.extensions import portbindings from neutron.extensions import providernet as provider from neutron.extensions import securitygroup as ext_sg from neutron import manager from neutron.openstack.common import importutils from neutron.openstack.common import log as logging from neutron.plugins.common import constants as svc_constants from neutron.plugins.common import utils as plugin_utils from neutron.plugins.openvswitch.common import config # noqa from neutron.plugins.openvswitch.common import constants from neutron.plugins.openvswitch import ovs_db_v2 LOG = logging.getLogger(__name__) class OVSRpcCallbacks(n_rpc.RpcCallback, sg_db_rpc.SecurityGroupServerRpcCallbackMixin): # history # 1.0 Initial version # 1.1 Support Security Group RPC # 1.2 Support get_devices_details_list RPC_API_VERSION = '1.2' def __init__(self, notifier, tunnel_type): super(OVSRpcCallbacks, self).__init__() self.notifier = notifier self.tunnel_type = tunnel_type @classmethod def get_port_from_device(cls, device): port = ovs_db_v2.get_port_from_device(device) if port: port['device'] = device return port def get_device_details(self, rpc_context, **kwargs): """Agent requests device details.""" agent_id = kwargs.get('agent_id') device = kwargs.get('device') LOG.debug(_("Device %(device)s details requested from %(agent_id)s"), {'device': device, 'agent_id': agent_id}) port = ovs_db_v2.get_port(device) if port: binding = ovs_db_v2.get_network_binding(None, port['network_id']) entry = {'device': device, 'network_id': port['network_id'], 'port_id': port['id'], 'admin_state_up': port['admin_state_up'], 'network_type': binding.network_type, 'segmentation_id': binding.segmentation_id, 'physical_network': binding.physical_network} new_status = (q_const.PORT_STATUS_ACTIVE if port['admin_state_up'] else q_const.PORT_STATUS_DOWN) if port['status'] != new_status: ovs_db_v2.set_port_status(port['id'], new_status) else: entry = {'device': device} LOG.debug(_("%s can not be found in database"), device) return entry def get_devices_details_list(self, rpc_context, **kwargs): return [ self.get_device_details( rpc_context, device=device, **kwargs ) for device in kwargs.pop('devices', []) ] def update_device_down(self, rpc_context, **kwargs): """Device no longer exists on agent.""" agent_id = kwargs.get('agent_id') device = kwargs.get('device') host = kwargs.get('host') port = ovs_db_v2.get_port(device) LOG.debug(_("Device %(device)s no longer exists on %(agent_id)s"), {'device': device, 'agent_id': agent_id}) if port: entry = {'device': device, 'exists': True} plugin = manager.NeutronManager.get_plugin() if (host and not plugin.get_port_host(rpc_context, port['id']) == host): LOG.debug(_("Device %(device)s not bound to the" " agent host %(host)s"), {'device': device, 'host': host}) elif port['status'] != q_const.PORT_STATUS_DOWN: # Set port status to DOWN ovs_db_v2.set_port_status(port['id'], q_const.PORT_STATUS_DOWN) else: entry = {'device': device, 'exists': False} LOG.debug(_("%s can not be found in database"), device) return entry def update_device_up(self, rpc_context, **kwargs): """Device is up on agent.""" agent_id = kwargs.get('agent_id') device = kwargs.get('device') host = kwargs.get('host') port = ovs_db_v2.get_port(device) LOG.debug(_("Device %(device)s up on %(agent_id)s"), {'device': device, 'agent_id': agent_id}) plugin = manager.NeutronManager.get_plugin() if port: if (host and not plugin.get_port_host(rpc_context, port['id']) == host): LOG.debug(_("Device %(device)s not bound to the" " agent host %(host)s"), {'device': device, 'host': host}) return elif port['status'] != q_const.PORT_STATUS_ACTIVE: ovs_db_v2.set_port_status(port['id'], q_const.PORT_STATUS_ACTIVE) else: LOG.debug(_("%s can not be found in database"), device) def tunnel_sync(self, rpc_context, **kwargs): """Update new tunnel. Updates the datbase with the tunnel IP. All listening agents will also be notified about the new tunnel IP. """ tunnel_ip = kwargs.get('tunnel_ip') # Update the database with the IP tunnel = ovs_db_v2.add_tunnel_endpoint(tunnel_ip) tunnels = ovs_db_v2.get_tunnel_endpoints() entry = dict() entry['tunnels'] = tunnels # Notify all other listening agents self.notifier.tunnel_update(rpc_context, tunnel.ip_address, tunnel.id, self.tunnel_type) # Return the list of tunnels IP's to the agent return entry class AgentNotifierApi(n_rpc.RpcProxy, sg_rpc.SecurityGroupAgentRpcApiMixin): '''Agent side of the openvswitch rpc API. API version history: 1.0 - Initial version. ''' BASE_RPC_API_VERSION = '1.0' def __init__(self, topic): super(AgentNotifierApi, self).__init__( topic=topic, default_version=self.BASE_RPC_API_VERSION) self.topic_network_delete = topics.get_topic_name(topic, topics.NETWORK, topics.DELETE) self.topic_port_update = topics.get_topic_name(topic, topics.PORT, topics.UPDATE) self.topic_tunnel_update = topics.get_topic_name(topic, constants.TUNNEL, topics.UPDATE) def network_delete(self, context, network_id): self.fanout_cast(context, self.make_msg('network_delete', network_id=network_id), topic=self.topic_network_delete) def port_update(self, context, port, network_type, segmentation_id, physical_network): self.fanout_cast(context, self.make_msg('port_update', port=port, network_type=network_type, segmentation_id=segmentation_id, physical_network=physical_network), topic=self.topic_port_update) def tunnel_update(self, context, tunnel_ip, tunnel_id, tunnel_type): self.fanout_cast(context, self.make_msg('tunnel_update', tunnel_ip=tunnel_ip, tunnel_id=tunnel_id, tunnel_type=tunnel_type), topic=self.topic_tunnel_update) class OVSNeutronPluginV2(db_base_plugin_v2.NeutronDbPluginV2, external_net_db.External_net_db_mixin, extraroute_db.ExtraRoute_db_mixin, l3_gwmode_db.L3_NAT_db_mixin, sg_db_rpc.SecurityGroupServerRpcMixin, l3_agentschedulers_db.L3AgentSchedulerDbMixin, agentschedulers_db.DhcpAgentSchedulerDbMixin, portbindings_db.PortBindingMixin, extradhcpopt_db.ExtraDhcpOptMixin, addr_pair_db.AllowedAddressPairsMixin): """Implement the Neutron abstractions using Open vSwitch. Depending on whether tunneling is enabled, either a GRE, VXLAN tunnel or a new VLAN is created for each network. An agent is relied upon to perform the actual OVS configuration on each host. The provider extension is also supported. As discussed in https://bugs.launchpad.net/neutron/+bug/1023156, this class could be simplified, and filtering on extended attributes could be handled, by adding support for extended attributes to the NeutronDbPluginV2 base class. When that occurs, this class should be updated to take advantage of it. The port binding extension enables an external application relay information to and from the plugin. """ # This attribute specifies whether the plugin supports or not # bulk/pagination/sorting operations. Name mangling is used in # order to ensure it is qualified by class __native_bulk_support = True __native_pagination_support = True __native_sorting_support = True _supported_extension_aliases = ["provider", "external-net", "router", "ext-gw-mode", "binding", "quotas", "security-group", "agent", "extraroute", "l3_agent_scheduler", "dhcp_agent_scheduler", "extra_dhcp_opt", "allowed-address-pairs"] @property def supported_extension_aliases(self): if not hasattr(self, '_aliases'): aliases = self._supported_extension_aliases[:] sg_rpc.disable_security_group_extension_by_config(aliases) self._aliases = aliases return self._aliases db_base_plugin_v2.NeutronDbPluginV2.register_dict_extend_funcs( attributes.NETWORKS, ['_extend_network_dict_provider_ovs']) def __init__(self, configfile=None): super(OVSNeutronPluginV2, self).__init__() self.base_binding_dict = { portbindings.VIF_TYPE: portbindings.VIF_TYPE_OVS, portbindings.VIF_DETAILS: { # TODO(rkukura): Replace with new VIF security details portbindings.CAP_PORT_FILTER: 'security-group' in self.supported_extension_aliases, portbindings.OVS_HYBRID_PLUG: True}} self._parse_network_vlan_ranges() ovs_db_v2.sync_vlan_allocations(self.network_vlan_ranges) self.tenant_network_type = cfg.CONF.OVS.tenant_network_type if self.tenant_network_type not in [svc_constants.TYPE_LOCAL, svc_constants.TYPE_VLAN, svc_constants.TYPE_GRE, svc_constants.TYPE_VXLAN, svc_constants.TYPE_NONE]: LOG.error(_("Invalid tenant_network_type: %s. " "Server terminated!"), self.tenant_network_type) sys.exit(1) self.enable_tunneling = cfg.CONF.OVS.enable_tunneling self.tunnel_type = None if self.enable_tunneling: self.tunnel_type = (cfg.CONF.OVS.tunnel_type or svc_constants.TYPE_GRE) elif cfg.CONF.OVS.tunnel_type: self.tunnel_type = cfg.CONF.OVS.tunnel_type self.enable_tunneling = True self.tunnel_id_ranges = [] if self.enable_tunneling: self._parse_tunnel_id_ranges() ovs_db_v2.sync_tunnel_allocations(self.tunnel_id_ranges) elif self.tenant_network_type in constants.TUNNEL_NETWORK_TYPES: LOG.error(_("Tunneling disabled but tenant_network_type is '%s'. " "Server terminated!"), self.tenant_network_type) sys.exit(1) self.setup_rpc() self.network_scheduler = importutils.import_object( cfg.CONF.network_scheduler_driver ) self.router_scheduler = importutils.import_object( cfg.CONF.router_scheduler_driver ) def setup_rpc(self): # RPC support self.service_topics = {svc_constants.CORE: topics.PLUGIN, svc_constants.L3_ROUTER_NAT: topics.L3PLUGIN} self.conn = n_rpc.create_connection(new=True) self.notifier = AgentNotifierApi(topics.AGENT) self.agent_notifiers[q_const.AGENT_TYPE_DHCP] = ( dhcp_rpc_agent_api.DhcpAgentNotifyAPI() ) self.agent_notifiers[q_const.AGENT_TYPE_L3] = ( l3_rpc_agent_api.L3AgentNotifyAPI() ) self.endpoints = [OVSRpcCallbacks(self.notifier, self.tunnel_type), dhcp_rpc.DhcpRpcCallback(), l3_rpc.L3RpcCallback(), agents_db.AgentExtRpcCallback()] for svc_topic in self.service_topics.values(): self.conn.create_consumer(svc_topic, self.endpoints, fanout=False) # Consume from all consumers in threads self.conn.consume_in_threads() def _parse_network_vlan_ranges(self): try: self.network_vlan_ranges = plugin_utils.parse_network_vlan_ranges( cfg.CONF.OVS.network_vlan_ranges) except Exception as ex: LOG.error(_("%s. Server terminated!"), ex) sys.exit(1) LOG.info(_("Network VLAN ranges: %s"), self.network_vlan_ranges) def _parse_tunnel_id_ranges(self): for entry in cfg.CONF.OVS.tunnel_id_ranges: entry = entry.strip() try: tun_min, tun_max = entry.split(':') self.tunnel_id_ranges.append((int(tun_min), int(tun_max))) except ValueError as ex: LOG.error(_("Invalid tunnel ID range: " "'%(range)s' - %(e)s. Server terminated!"), {'range': entry, 'e': ex}) sys.exit(1) LOG.info(_("Tunnel ID ranges: %s"), self.tunnel_id_ranges) def _extend_network_dict_provider_ovs(self, network, net_db, net_binding=None): # this method used in two cases: when binding is provided explicitly # and when it is a part of db model object binding = net_db.binding if net_db else net_binding network[provider.NETWORK_TYPE] = binding.network_type if binding.network_type in constants.TUNNEL_NETWORK_TYPES: network[provider.PHYSICAL_NETWORK] = None network[provider.SEGMENTATION_ID] = binding.segmentation_id elif binding.network_type == svc_constants.TYPE_FLAT: network[provider.PHYSICAL_NETWORK] = binding.physical_network network[provider.SEGMENTATION_ID] = None elif binding.network_type == svc_constants.TYPE_VLAN: network[provider.PHYSICAL_NETWORK] = binding.physical_network network[provider.SEGMENTATION_ID] = binding.segmentation_id elif binding.network_type == svc_constants.TYPE_LOCAL: network[provider.PHYSICAL_NETWORK] = None network[provider.SEGMENTATION_ID] = None def _process_provider_create(self, context, attrs): network_type = attrs.get(provider.NETWORK_TYPE) physical_network = attrs.get(provider.PHYSICAL_NETWORK) segmentation_id = attrs.get(provider.SEGMENTATION_ID) network_type_set = attributes.is_attr_set(network_type) physical_network_set = attributes.is_attr_set(physical_network) segmentation_id_set = attributes.is_attr_set(segmentation_id) if not (network_type_set or physical_network_set or segmentation_id_set): return (None, None, None) if not network_type_set: msg = _("provider:network_type required") raise n_exc.InvalidInput(error_message=msg) elif network_type == svc_constants.TYPE_FLAT: if segmentation_id_set: msg = _("provider:segmentation_id specified for flat network") raise n_exc.InvalidInput(error_message=msg) else: segmentation_id = constants.FLAT_VLAN_ID elif network_type == svc_constants.TYPE_VLAN: if not segmentation_id_set: msg = _("provider:segmentation_id required") raise n_exc.InvalidInput(error_message=msg) if not utils.is_valid_vlan_tag(segmentation_id): msg = (_("provider:segmentation_id out of range " "(%(min_id)s through %(max_id)s)") % {'min_id': q_const.MIN_VLAN_TAG, 'max_id': q_const.MAX_VLAN_TAG}) raise n_exc.InvalidInput(error_message=msg) elif network_type in constants.TUNNEL_NETWORK_TYPES: if not self.enable_tunneling: msg = _("%s networks are not enabled") % network_type raise n_exc.InvalidInput(error_message=msg) if physical_network_set: msg = _("provider:physical_network specified for %s " "network") % network_type raise n_exc.InvalidInput(error_message=msg) else: physical_network = None if not segmentation_id_set: msg = _("provider:segmentation_id required") raise n_exc.InvalidInput(error_message=msg) elif network_type == svc_constants.TYPE_LOCAL: if physical_network_set: msg = _("provider:physical_network specified for local " "network") raise n_exc.InvalidInput(error_message=msg) else: physical_network = None if segmentation_id_set: msg = _("provider:segmentation_id specified for local " "network") raise n_exc.InvalidInput(error_message=msg) else: segmentation_id = None else: msg = _("provider:network_type %s not supported") % network_type raise n_exc.InvalidInput(error_message=msg) if network_type in [svc_constants.TYPE_VLAN, svc_constants.TYPE_FLAT]: if physical_network_set: if physical_network not in self.network_vlan_ranges: msg = _("Unknown provider:physical_network " "%s") % physical_network raise n_exc.InvalidInput(error_message=msg) elif 'default' in self.network_vlan_ranges: physical_network = 'default' else: msg = _("provider:physical_network required") raise n_exc.InvalidInput(error_message=msg) return (network_type, physical_network, segmentation_id) def create_network(self, context, network): (network_type, physical_network, segmentation_id) = self._process_provider_create(context, network['network']) session = context.session #set up default security groups tenant_id = self._get_tenant_id_for_create( context, network['network']) self._ensure_default_security_group(context, tenant_id) with session.begin(subtransactions=True): if not network_type: # tenant network network_type = self.tenant_network_type if network_type == svc_constants.TYPE_NONE: raise n_exc.TenantNetworksDisabled() elif network_type == svc_constants.TYPE_VLAN: (physical_network, segmentation_id) = ovs_db_v2.reserve_vlan(session) elif network_type in constants.TUNNEL_NETWORK_TYPES: segmentation_id = ovs_db_v2.reserve_tunnel(session) # no reservation needed for TYPE_LOCAL else: # provider network if network_type in [svc_constants.TYPE_VLAN, svc_constants.TYPE_FLAT]: ovs_db_v2.reserve_specific_vlan(session, physical_network, segmentation_id) elif network_type in constants.TUNNEL_NETWORK_TYPES: ovs_db_v2.reserve_specific_tunnel(session, segmentation_id) # no reservation needed for TYPE_LOCAL net = super(OVSNeutronPluginV2, self).create_network(context, network) binding = ovs_db_v2.add_network_binding(session, net['id'], network_type, physical_network, segmentation_id) self._process_l3_create(context, net, network['network']) # passing None as db model to use binding object self._extend_network_dict_provider_ovs(net, None, binding) # note - exception will rollback entire transaction LOG.debug(_("Created network: %s"), net['id']) return net def update_network(self, context, id, network): provider._raise_if_updates_provider_attributes(network['network']) session = context.session with session.begin(subtransactions=True): net = super(OVSNeutronPluginV2, self).update_network(context, id, network) self._process_l3_update(context, net, network['network']) return net def delete_network(self, context, id): session = context.session with session.begin(subtransactions=True): binding = ovs_db_v2.get_network_binding(session, id) self._process_l3_delete(context, id) super(OVSNeutronPluginV2, self).delete_network(context, id) if binding.network_type in constants.TUNNEL_NETWORK_TYPES: ovs_db_v2.release_tunnel(session, binding.segmentation_id, self.tunnel_id_ranges) elif binding.network_type in [svc_constants.TYPE_VLAN, svc_constants.TYPE_FLAT]: ovs_db_v2.release_vlan(session, binding.physical_network, binding.segmentation_id, self.network_vlan_ranges) # the network_binding record is deleted via cascade from # the network record, so explicit removal is not necessary self.notifier.network_delete(context, id) def get_network(self, context, id, fields=None): session = context.session with session.begin(subtransactions=True): net = super(OVSNeutronPluginV2, self).get_network(context, id, None) return self._fields(net, fields) def get_networks(self, context, filters=None, fields=None, sorts=None, limit=None, marker=None, page_reverse=False): session = context.session with session.begin(subtransactions=True): nets = super(OVSNeutronPluginV2, self).get_networks(context, filters, None, sorts, limit, marker, page_reverse) return [self._fields(net, fields) for net in nets] def create_port(self, context, port): # Set port status as 'DOWN'. This will be updated by agent port['port']['status'] = q_const.PORT_STATUS_DOWN port_data = port['port'] session = context.session with session.begin(subtransactions=True): self._ensure_default_security_group_on_port(context, port) sgids = self._get_security_groups_on_port(context, port) dhcp_opts = port['port'].get(edo_ext.EXTRADHCPOPTS, []) port = super(OVSNeutronPluginV2, self).create_port(context, port) self._process_portbindings_create_and_update(context, port_data, port) self._process_port_create_security_group(context, port, sgids) self._process_port_create_extra_dhcp_opts(context, port, dhcp_opts) port[addr_pair.ADDRESS_PAIRS] = ( self._process_create_allowed_address_pairs( context, port, port_data.get(addr_pair.ADDRESS_PAIRS))) self.notify_security_groups_member_updated(context, port) return port def update_port(self, context, id, port): session = context.session need_port_update_notify = False with session.begin(subtransactions=True): original_port = super(OVSNeutronPluginV2, self).get_port( context, id) updated_port = super(OVSNeutronPluginV2, self).update_port( context, id, port) if addr_pair.ADDRESS_PAIRS in port['port']: need_port_update_notify |= ( self.update_address_pairs_on_port(context, id, port, original_port, updated_port)) need_port_update_notify |= self.update_security_group_on_port( context, id, port, original_port, updated_port) self._process_portbindings_create_and_update(context, port['port'], updated_port) need_port_update_notify |= self._update_extra_dhcp_opts_on_port( context, id, port, updated_port) secgrp_member_updated = self.is_security_group_member_updated( context, original_port, updated_port) need_port_update_notify |= secgrp_member_updated if original_port['admin_state_up'] != updated_port['admin_state_up']: need_port_update_notify = True if need_port_update_notify: binding = ovs_db_v2.get_network_binding(None, updated_port['network_id']) self.notifier.port_update(context, updated_port, binding.network_type, binding.segmentation_id, binding.physical_network) if secgrp_member_updated: old_set = set(original_port.get(ext_sg.SECURITYGROUPS)) new_set = set(updated_port.get(ext_sg.SECURITYGROUPS)) self.notifier.security_groups_member_updated( context, old_set ^ new_set) return updated_port def delete_port(self, context, id, l3_port_check=True): # if needed, check to see if this is a port owned by # and l3-router. If so, we should prevent deletion. if l3_port_check: self.prevent_l3_port_deletion(context, id) session = context.session with session.begin(subtransactions=True): router_ids = self.disassociate_floatingips( context, id, do_notify=False) port = self.get_port(context, id) self._delete_port_security_group_bindings(context, id) super(OVSNeutronPluginV2, self).delete_port(context, id) # now that we've left db transaction, we are safe to notify self.notify_routers_updated(context, router_ids) self.notify_security_groups_member_updated(context, port)
46.726852
79
0.597114
import sys from oslo.config import cfg from neutron.agent import securitygroups_rpc as sg_rpc from neutron.api.rpc.agentnotifiers import dhcp_rpc_agent_api from neutron.api.rpc.agentnotifiers import l3_rpc_agent_api from neutron.api.rpc.handlers import dhcp_rpc from neutron.api.rpc.handlers import l3_rpc from neutron.api.v2 import attributes from neutron.common import constants as q_const from neutron.common import exceptions as n_exc from neutron.common import rpc as n_rpc from neutron.common import topics from neutron.common import utils from neutron.db import agents_db from neutron.db import agentschedulers_db from neutron.db import allowedaddresspairs_db as addr_pair_db from neutron.db import db_base_plugin_v2 from neutron.db import external_net_db from neutron.db import extradhcpopt_db from neutron.db import extraroute_db from neutron.db import l3_agentschedulers_db from neutron.db import l3_gwmode_db from neutron.db import portbindings_db from neutron.db import quota_db from neutron.db import securitygroups_rpc_base as sg_db_rpc from neutron.extensions import allowedaddresspairs as addr_pair from neutron.extensions import extra_dhcp_opt as edo_ext from neutron.extensions import portbindings from neutron.extensions import providernet as provider from neutron.extensions import securitygroup as ext_sg from neutron import manager from neutron.openstack.common import importutils from neutron.openstack.common import log as logging from neutron.plugins.common import constants as svc_constants from neutron.plugins.common import utils as plugin_utils from neutron.plugins.openvswitch.common import config from neutron.plugins.openvswitch.common import constants from neutron.plugins.openvswitch import ovs_db_v2 LOG = logging.getLogger(__name__) class OVSRpcCallbacks(n_rpc.RpcCallback, sg_db_rpc.SecurityGroupServerRpcCallbackMixin): RPC_API_VERSION = '1.2' def __init__(self, notifier, tunnel_type): super(OVSRpcCallbacks, self).__init__() self.notifier = notifier self.tunnel_type = tunnel_type @classmethod def get_port_from_device(cls, device): port = ovs_db_v2.get_port_from_device(device) if port: port['device'] = device return port def get_device_details(self, rpc_context, **kwargs): agent_id = kwargs.get('agent_id') device = kwargs.get('device') LOG.debug(_("Device %(device)s details requested from %(agent_id)s"), {'device': device, 'agent_id': agent_id}) port = ovs_db_v2.get_port(device) if port: binding = ovs_db_v2.get_network_binding(None, port['network_id']) entry = {'device': device, 'network_id': port['network_id'], 'port_id': port['id'], 'admin_state_up': port['admin_state_up'], 'network_type': binding.network_type, 'segmentation_id': binding.segmentation_id, 'physical_network': binding.physical_network} new_status = (q_const.PORT_STATUS_ACTIVE if port['admin_state_up'] else q_const.PORT_STATUS_DOWN) if port['status'] != new_status: ovs_db_v2.set_port_status(port['id'], new_status) else: entry = {'device': device} LOG.debug(_("%s can not be found in database"), device) return entry def get_devices_details_list(self, rpc_context, **kwargs): return [ self.get_device_details( rpc_context, device=device, **kwargs ) for device in kwargs.pop('devices', []) ] def update_device_down(self, rpc_context, **kwargs): agent_id = kwargs.get('agent_id') device = kwargs.get('device') host = kwargs.get('host') port = ovs_db_v2.get_port(device) LOG.debug(_("Device %(device)s no longer exists on %(agent_id)s"), {'device': device, 'agent_id': agent_id}) if port: entry = {'device': device, 'exists': True} plugin = manager.NeutronManager.get_plugin() if (host and not plugin.get_port_host(rpc_context, port['id']) == host): LOG.debug(_("Device %(device)s not bound to the" " agent host %(host)s"), {'device': device, 'host': host}) elif port['status'] != q_const.PORT_STATUS_DOWN: ovs_db_v2.set_port_status(port['id'], q_const.PORT_STATUS_DOWN) else: entry = {'device': device, 'exists': False} LOG.debug(_("%s can not be found in database"), device) return entry def update_device_up(self, rpc_context, **kwargs): agent_id = kwargs.get('agent_id') device = kwargs.get('device') host = kwargs.get('host') port = ovs_db_v2.get_port(device) LOG.debug(_("Device %(device)s up on %(agent_id)s"), {'device': device, 'agent_id': agent_id}) plugin = manager.NeutronManager.get_plugin() if port: if (host and not plugin.get_port_host(rpc_context, port['id']) == host): LOG.debug(_("Device %(device)s not bound to the" " agent host %(host)s"), {'device': device, 'host': host}) return elif port['status'] != q_const.PORT_STATUS_ACTIVE: ovs_db_v2.set_port_status(port['id'], q_const.PORT_STATUS_ACTIVE) else: LOG.debug(_("%s can not be found in database"), device) def tunnel_sync(self, rpc_context, **kwargs): tunnel_ip = kwargs.get('tunnel_ip') tunnel = ovs_db_v2.add_tunnel_endpoint(tunnel_ip) tunnels = ovs_db_v2.get_tunnel_endpoints() entry = dict() entry['tunnels'] = tunnels self.notifier.tunnel_update(rpc_context, tunnel.ip_address, tunnel.id, self.tunnel_type) return entry class AgentNotifierApi(n_rpc.RpcProxy, sg_rpc.SecurityGroupAgentRpcApiMixin): BASE_RPC_API_VERSION = '1.0' def __init__(self, topic): super(AgentNotifierApi, self).__init__( topic=topic, default_version=self.BASE_RPC_API_VERSION) self.topic_network_delete = topics.get_topic_name(topic, topics.NETWORK, topics.DELETE) self.topic_port_update = topics.get_topic_name(topic, topics.PORT, topics.UPDATE) self.topic_tunnel_update = topics.get_topic_name(topic, constants.TUNNEL, topics.UPDATE) def network_delete(self, context, network_id): self.fanout_cast(context, self.make_msg('network_delete', network_id=network_id), topic=self.topic_network_delete) def port_update(self, context, port, network_type, segmentation_id, physical_network): self.fanout_cast(context, self.make_msg('port_update', port=port, network_type=network_type, segmentation_id=segmentation_id, physical_network=physical_network), topic=self.topic_port_update) def tunnel_update(self, context, tunnel_ip, tunnel_id, tunnel_type): self.fanout_cast(context, self.make_msg('tunnel_update', tunnel_ip=tunnel_ip, tunnel_id=tunnel_id, tunnel_type=tunnel_type), topic=self.topic_tunnel_update) class OVSNeutronPluginV2(db_base_plugin_v2.NeutronDbPluginV2, external_net_db.External_net_db_mixin, extraroute_db.ExtraRoute_db_mixin, l3_gwmode_db.L3_NAT_db_mixin, sg_db_rpc.SecurityGroupServerRpcMixin, l3_agentschedulers_db.L3AgentSchedulerDbMixin, agentschedulers_db.DhcpAgentSchedulerDbMixin, portbindings_db.PortBindingMixin, extradhcpopt_db.ExtraDhcpOptMixin, addr_pair_db.AllowedAddressPairsMixin): # This attribute specifies whether the plugin supports or not # bulk/pagination/sorting operations. Name mangling is used in # order to ensure it is qualified by class __native_bulk_support = True __native_pagination_support = True __native_sorting_support = True _supported_extension_aliases = ["provider", "external-net", "router", "ext-gw-mode", "binding", "quotas", "security-group", "agent", "extraroute", "l3_agent_scheduler", "dhcp_agent_scheduler", "extra_dhcp_opt", "allowed-address-pairs"] @property def supported_extension_aliases(self): if not hasattr(self, '_aliases'): aliases = self._supported_extension_aliases[:] sg_rpc.disable_security_group_extension_by_config(aliases) self._aliases = aliases return self._aliases db_base_plugin_v2.NeutronDbPluginV2.register_dict_extend_funcs( attributes.NETWORKS, ['_extend_network_dict_provider_ovs']) def __init__(self, configfile=None): super(OVSNeutronPluginV2, self).__init__() self.base_binding_dict = { portbindings.VIF_TYPE: portbindings.VIF_TYPE_OVS, portbindings.VIF_DETAILS: { # TODO(rkukura): Replace with new VIF security details portbindings.CAP_PORT_FILTER: 'security-group' in self.supported_extension_aliases, portbindings.OVS_HYBRID_PLUG: True}} self._parse_network_vlan_ranges() ovs_db_v2.sync_vlan_allocations(self.network_vlan_ranges) self.tenant_network_type = cfg.CONF.OVS.tenant_network_type if self.tenant_network_type not in [svc_constants.TYPE_LOCAL, svc_constants.TYPE_VLAN, svc_constants.TYPE_GRE, svc_constants.TYPE_VXLAN, svc_constants.TYPE_NONE]: LOG.error(_("Invalid tenant_network_type: %s. " "Server terminated!"), self.tenant_network_type) sys.exit(1) self.enable_tunneling = cfg.CONF.OVS.enable_tunneling self.tunnel_type = None if self.enable_tunneling: self.tunnel_type = (cfg.CONF.OVS.tunnel_type or svc_constants.TYPE_GRE) elif cfg.CONF.OVS.tunnel_type: self.tunnel_type = cfg.CONF.OVS.tunnel_type self.enable_tunneling = True self.tunnel_id_ranges = [] if self.enable_tunneling: self._parse_tunnel_id_ranges() ovs_db_v2.sync_tunnel_allocations(self.tunnel_id_ranges) elif self.tenant_network_type in constants.TUNNEL_NETWORK_TYPES: LOG.error(_("Tunneling disabled but tenant_network_type is '%s'. " "Server terminated!"), self.tenant_network_type) sys.exit(1) self.setup_rpc() self.network_scheduler = importutils.import_object( cfg.CONF.network_scheduler_driver ) self.router_scheduler = importutils.import_object( cfg.CONF.router_scheduler_driver ) def setup_rpc(self): # RPC support self.service_topics = {svc_constants.CORE: topics.PLUGIN, svc_constants.L3_ROUTER_NAT: topics.L3PLUGIN} self.conn = n_rpc.create_connection(new=True) self.notifier = AgentNotifierApi(topics.AGENT) self.agent_notifiers[q_const.AGENT_TYPE_DHCP] = ( dhcp_rpc_agent_api.DhcpAgentNotifyAPI() ) self.agent_notifiers[q_const.AGENT_TYPE_L3] = ( l3_rpc_agent_api.L3AgentNotifyAPI() ) self.endpoints = [OVSRpcCallbacks(self.notifier, self.tunnel_type), dhcp_rpc.DhcpRpcCallback(), l3_rpc.L3RpcCallback(), agents_db.AgentExtRpcCallback()] for svc_topic in self.service_topics.values(): self.conn.create_consumer(svc_topic, self.endpoints, fanout=False) # Consume from all consumers in threads self.conn.consume_in_threads() def _parse_network_vlan_ranges(self): try: self.network_vlan_ranges = plugin_utils.parse_network_vlan_ranges( cfg.CONF.OVS.network_vlan_ranges) except Exception as ex: LOG.error(_("%s. Server terminated!"), ex) sys.exit(1) LOG.info(_("Network VLAN ranges: %s"), self.network_vlan_ranges) def _parse_tunnel_id_ranges(self): for entry in cfg.CONF.OVS.tunnel_id_ranges: entry = entry.strip() try: tun_min, tun_max = entry.split(':') self.tunnel_id_ranges.append((int(tun_min), int(tun_max))) except ValueError as ex: LOG.error(_("Invalid tunnel ID range: " "'%(range)s' - %(e)s. Server terminated!"), {'range': entry, 'e': ex}) sys.exit(1) LOG.info(_("Tunnel ID ranges: %s"), self.tunnel_id_ranges) def _extend_network_dict_provider_ovs(self, network, net_db, net_binding=None): # this method used in two cases: when binding is provided explicitly # and when it is a part of db model object binding = net_db.binding if net_db else net_binding network[provider.NETWORK_TYPE] = binding.network_type if binding.network_type in constants.TUNNEL_NETWORK_TYPES: network[provider.PHYSICAL_NETWORK] = None network[provider.SEGMENTATION_ID] = binding.segmentation_id elif binding.network_type == svc_constants.TYPE_FLAT: network[provider.PHYSICAL_NETWORK] = binding.physical_network network[provider.SEGMENTATION_ID] = None elif binding.network_type == svc_constants.TYPE_VLAN: network[provider.PHYSICAL_NETWORK] = binding.physical_network network[provider.SEGMENTATION_ID] = binding.segmentation_id elif binding.network_type == svc_constants.TYPE_LOCAL: network[provider.PHYSICAL_NETWORK] = None network[provider.SEGMENTATION_ID] = None def _process_provider_create(self, context, attrs): network_type = attrs.get(provider.NETWORK_TYPE) physical_network = attrs.get(provider.PHYSICAL_NETWORK) segmentation_id = attrs.get(provider.SEGMENTATION_ID) network_type_set = attributes.is_attr_set(network_type) physical_network_set = attributes.is_attr_set(physical_network) segmentation_id_set = attributes.is_attr_set(segmentation_id) if not (network_type_set or physical_network_set or segmentation_id_set): return (None, None, None) if not network_type_set: msg = _("provider:network_type required") raise n_exc.InvalidInput(error_message=msg) elif network_type == svc_constants.TYPE_FLAT: if segmentation_id_set: msg = _("provider:segmentation_id specified for flat network") raise n_exc.InvalidInput(error_message=msg) else: segmentation_id = constants.FLAT_VLAN_ID elif network_type == svc_constants.TYPE_VLAN: if not segmentation_id_set: msg = _("provider:segmentation_id required") raise n_exc.InvalidInput(error_message=msg) if not utils.is_valid_vlan_tag(segmentation_id): msg = (_("provider:segmentation_id out of range " "(%(min_id)s through %(max_id)s)") % {'min_id': q_const.MIN_VLAN_TAG, 'max_id': q_const.MAX_VLAN_TAG}) raise n_exc.InvalidInput(error_message=msg) elif network_type in constants.TUNNEL_NETWORK_TYPES: if not self.enable_tunneling: msg = _("%s networks are not enabled") % network_type raise n_exc.InvalidInput(error_message=msg) if physical_network_set: msg = _("provider:physical_network specified for %s " "network") % network_type raise n_exc.InvalidInput(error_message=msg) else: physical_network = None if not segmentation_id_set: msg = _("provider:segmentation_id required") raise n_exc.InvalidInput(error_message=msg) elif network_type == svc_constants.TYPE_LOCAL: if physical_network_set: msg = _("provider:physical_network specified for local " "network") raise n_exc.InvalidInput(error_message=msg) else: physical_network = None if segmentation_id_set: msg = _("provider:segmentation_id specified for local " "network") raise n_exc.InvalidInput(error_message=msg) else: segmentation_id = None else: msg = _("provider:network_type %s not supported") % network_type raise n_exc.InvalidInput(error_message=msg) if network_type in [svc_constants.TYPE_VLAN, svc_constants.TYPE_FLAT]: if physical_network_set: if physical_network not in self.network_vlan_ranges: msg = _("Unknown provider:physical_network " "%s") % physical_network raise n_exc.InvalidInput(error_message=msg) elif 'default' in self.network_vlan_ranges: physical_network = 'default' else: msg = _("provider:physical_network required") raise n_exc.InvalidInput(error_message=msg) return (network_type, physical_network, segmentation_id) def create_network(self, context, network): (network_type, physical_network, segmentation_id) = self._process_provider_create(context, network['network']) session = context.session #set up default security groups tenant_id = self._get_tenant_id_for_create( context, network['network']) self._ensure_default_security_group(context, tenant_id) with session.begin(subtransactions=True): if not network_type: # tenant network network_type = self.tenant_network_type if network_type == svc_constants.TYPE_NONE: raise n_exc.TenantNetworksDisabled() elif network_type == svc_constants.TYPE_VLAN: (physical_network, segmentation_id) = ovs_db_v2.reserve_vlan(session) elif network_type in constants.TUNNEL_NETWORK_TYPES: segmentation_id = ovs_db_v2.reserve_tunnel(session) # no reservation needed for TYPE_LOCAL else: # provider network if network_type in [svc_constants.TYPE_VLAN, svc_constants.TYPE_FLAT]: ovs_db_v2.reserve_specific_vlan(session, physical_network, segmentation_id) elif network_type in constants.TUNNEL_NETWORK_TYPES: ovs_db_v2.reserve_specific_tunnel(session, segmentation_id) # no reservation needed for TYPE_LOCAL net = super(OVSNeutronPluginV2, self).create_network(context, network) binding = ovs_db_v2.add_network_binding(session, net['id'], network_type, physical_network, segmentation_id) self._process_l3_create(context, net, network['network']) # passing None as db model to use binding object self._extend_network_dict_provider_ovs(net, None, binding) # note - exception will rollback entire transaction LOG.debug(_("Created network: %s"), net['id']) return net def update_network(self, context, id, network): provider._raise_if_updates_provider_attributes(network['network']) session = context.session with session.begin(subtransactions=True): net = super(OVSNeutronPluginV2, self).update_network(context, id, network) self._process_l3_update(context, net, network['network']) return net def delete_network(self, context, id): session = context.session with session.begin(subtransactions=True): binding = ovs_db_v2.get_network_binding(session, id) self._process_l3_delete(context, id) super(OVSNeutronPluginV2, self).delete_network(context, id) if binding.network_type in constants.TUNNEL_NETWORK_TYPES: ovs_db_v2.release_tunnel(session, binding.segmentation_id, self.tunnel_id_ranges) elif binding.network_type in [svc_constants.TYPE_VLAN, svc_constants.TYPE_FLAT]: ovs_db_v2.release_vlan(session, binding.physical_network, binding.segmentation_id, self.network_vlan_ranges) # the network_binding record is deleted via cascade from # the network record, so explicit removal is not necessary self.notifier.network_delete(context, id) def get_network(self, context, id, fields=None): session = context.session with session.begin(subtransactions=True): net = super(OVSNeutronPluginV2, self).get_network(context, id, None) return self._fields(net, fields) def get_networks(self, context, filters=None, fields=None, sorts=None, limit=None, marker=None, page_reverse=False): session = context.session with session.begin(subtransactions=True): nets = super(OVSNeutronPluginV2, self).get_networks(context, filters, None, sorts, limit, marker, page_reverse) return [self._fields(net, fields) for net in nets] def create_port(self, context, port): # Set port status as 'DOWN'. This will be updated by agent port['port']['status'] = q_const.PORT_STATUS_DOWN port_data = port['port'] session = context.session with session.begin(subtransactions=True): self._ensure_default_security_group_on_port(context, port) sgids = self._get_security_groups_on_port(context, port) dhcp_opts = port['port'].get(edo_ext.EXTRADHCPOPTS, []) port = super(OVSNeutronPluginV2, self).create_port(context, port) self._process_portbindings_create_and_update(context, port_data, port) self._process_port_create_security_group(context, port, sgids) self._process_port_create_extra_dhcp_opts(context, port, dhcp_opts) port[addr_pair.ADDRESS_PAIRS] = ( self._process_create_allowed_address_pairs( context, port, port_data.get(addr_pair.ADDRESS_PAIRS))) self.notify_security_groups_member_updated(context, port) return port def update_port(self, context, id, port): session = context.session need_port_update_notify = False with session.begin(subtransactions=True): original_port = super(OVSNeutronPluginV2, self).get_port( context, id) updated_port = super(OVSNeutronPluginV2, self).update_port( context, id, port) if addr_pair.ADDRESS_PAIRS in port['port']: need_port_update_notify |= ( self.update_address_pairs_on_port(context, id, port, original_port, updated_port)) need_port_update_notify |= self.update_security_group_on_port( context, id, port, original_port, updated_port) self._process_portbindings_create_and_update(context, port['port'], updated_port) need_port_update_notify |= self._update_extra_dhcp_opts_on_port( context, id, port, updated_port) secgrp_member_updated = self.is_security_group_member_updated( context, original_port, updated_port) need_port_update_notify |= secgrp_member_updated if original_port['admin_state_up'] != updated_port['admin_state_up']: need_port_update_notify = True if need_port_update_notify: binding = ovs_db_v2.get_network_binding(None, updated_port['network_id']) self.notifier.port_update(context, updated_port, binding.network_type, binding.segmentation_id, binding.physical_network) if secgrp_member_updated: old_set = set(original_port.get(ext_sg.SECURITYGROUPS)) new_set = set(updated_port.get(ext_sg.SECURITYGROUPS)) self.notifier.security_groups_member_updated( context, old_set ^ new_set) return updated_port def delete_port(self, context, id, l3_port_check=True): # if needed, check to see if this is a port owned by # and l3-router. If so, we should prevent deletion. if l3_port_check: self.prevent_l3_port_deletion(context, id) session = context.session with session.begin(subtransactions=True): router_ids = self.disassociate_floatingips( context, id, do_notify=False) port = self.get_port(context, id) self._delete_port_security_group_bindings(context, id) super(OVSNeutronPluginV2, self).delete_port(context, id) # now that we've left db transaction, we are safe to notify self.notify_routers_updated(context, router_ids) self.notify_security_groups_member_updated(context, port)
true
true
f72a83c49b78622f2d47b7d505eed6ddffe2fe8d
6,547
py
Python
monero_glue/xmr/sub/mlsag_hasher.py
ph4r05/monero-agent
0bac0e6f33142b2bb885565bfd1ef8ac04559280
[ "MIT" ]
20
2018-04-05T22:06:10.000Z
2021-09-18T10:43:44.000Z
monero_glue/xmr/sub/mlsag_hasher.py
ph4r05/monero-agent
0bac0e6f33142b2bb885565bfd1ef8ac04559280
[ "MIT" ]
null
null
null
monero_glue/xmr/sub/mlsag_hasher.py
ph4r05/monero-agent
0bac0e6f33142b2bb885565bfd1ef8ac04559280
[ "MIT" ]
5
2018-08-06T15:06:04.000Z
2021-07-16T01:58:43.000Z
from monero_glue.xmr import crypto from monero_glue.xmr.sub.keccak_hasher import HashWrapper from monero_serialize import xmrserialize class PreMlsagHasher(object): """ Iterative construction of the pre_mlsag_hash """ def __init__(self, state=None): from monero_glue.xmr.sub.keccak_hasher import HashWrapper, KeccakXmrArchive self.is_simple = state[0] if state else None self.state = state[1] if state else 0 self.kc_master = HashWrapper(state[2] if state else crypto.get_keccak()) self.rsig_hasher = state[3] if state else crypto.get_keccak() self.rtcsig_hasher = None if state: self.rtcsig_hasher = KeccakXmrArchive(state[4]) if state[4] else None else: self.rtcsig_hasher = KeccakXmrArchive() def state_save(self): return ( self.is_simple, self.state, self.kc_master.ctx, self.rsig_hasher, self.rtcsig_hasher.ctx() if self.rtcsig_hasher else None, ) def state_load(self, x): from monero_glue.xmr.sub.keccak_hasher import HashWrapper, KeccakXmrArchive self.is_simple = x[0] self.state = x[1] self.kc_master = HashWrapper(x[2]) self.rsig_hasher = x[3] if x[4]: self.rtcsig_hasher = KeccakXmrArchive(x[4]) else: self.rtcsig_hasher = None def init(self, is_simple): if self.state != 0: raise ValueError("State error") self.state = 1 self.is_simple = is_simple async def set_message(self, message): self.kc_master.update(message) async def set_type_fee(self, rv_type, fee): if self.state != 1: raise ValueError("State error") self.state = 2 from monero_serialize.xmrtypes import RctSigBase rfields = RctSigBase.f_specs() await self.rtcsig_hasher.message_field(None, field=rfields[0], fvalue=rv_type) await self.rtcsig_hasher.message_field(None, field=rfields[1], fvalue=fee) async def set_pseudo_out(self, out): if self.state != 2 and self.state != 3: raise ValueError("State error") self.state = 3 from monero_serialize.xmrtypes import KeyV await self.rtcsig_hasher.field(out, KeyV.ELEM_TYPE) async def set_ecdh(self, ecdh, raw=True): if self.state != 2 and self.state != 3 and self.state != 4: raise ValueError("State error") self.state = 4 if raw: await self.rtcsig_hasher.buffer(ecdh) else: from monero_serialize.xmrtypes import EcdhInfo await self.rtcsig_hasher.field(ecdh, EcdhInfo.ELEM_TYPE) async def set_out_pk(self, out_pk, mask=None): if self.state != 4 and self.state != 5: raise ValueError("State error") self.state = 5 from monero_serialize.xmrtypes import ECKey await self.rtcsig_hasher.field(mask if mask else out_pk, ECKey) async def rctsig_base_done(self): if self.state != 5: raise ValueError("State error") self.state = 6 c_hash = self.rtcsig_hasher.get_digest() self.kc_master.update(c_hash) self.rtcsig_hasher = None async def rsig_val(self, p, bulletproof, raw=False): if self.state == 8: raise ValueError("State error") if raw: if isinstance(p, list): for x in p: self.rsig_hasher.update(x) else: self.rsig_hasher.update(p) return if bulletproof: self.rsig_hasher.update(p.A) self.rsig_hasher.update(p.S) self.rsig_hasher.update(p.T1) self.rsig_hasher.update(p.T2) self.rsig_hasher.update(p.taux) self.rsig_hasher.update(p.mu) for i in range(len(p.L)): self.rsig_hasher.update(p.L[i]) for i in range(len(p.R)): self.rsig_hasher.update(p.R[i]) self.rsig_hasher.update(p.a) self.rsig_hasher.update(p.b) self.rsig_hasher.update(p.t) else: for i in range(64): self.rsig_hasher.update(p.asig.s0[i]) for i in range(64): self.rsig_hasher.update(p.asig.s1[i]) self.rsig_hasher.update(p.asig.ee) for i in range(64): self.rsig_hasher.update(p.Ci[i]) async def get_digest(self): if self.state != 6: raise ValueError("State error") self.state = 8 c_hash = self.rsig_hasher.digest() self.rsig_hasher = None self.kc_master.update(c_hash) return self.kc_master.digest() async def get_pre_mlsag_hash(rv): """ Generates final message for the Ring CT signature :param rv: :type rv: RctSig :return: """ from monero_glue.xmr.sub.keccak_hasher import get_keccak_writer from monero_serialize.xmrtypes import RctType kc_master = HashWrapper(crypto.get_keccak()) kc_master.update(rv.message) is_simple = rv.type in [RctType.Simple, RctType.Bulletproof, RctType.Bulletproof2] outputs = len(rv.ecdhInfo) inputs = 0 if rv.type == RctType.Simple: inputs = len(rv.pseudoOuts) elif rv.type in [RctType.Bulletproof, RctType.Bulletproof2]: inputs = len(rv.p.pseudoOuts) kwriter = get_keccak_writer() ar = xmrserialize.Archive(kwriter, True) await rv.serialize_rctsig_base(ar, inputs, outputs) c_hash = kwriter.get_digest() kc_master.update(c_hash) kc = crypto.get_keccak() if rv.type in [RctType.Bulletproof, RctType.Bulletproof2]: for p in rv.p.bulletproofs: kc.update(p.A) kc.update(p.S) kc.update(p.T1) kc.update(p.T2) kc.update(p.taux) kc.update(p.mu) for i in range(len(p.L)): kc.update(p.L[i]) for i in range(len(p.R)): kc.update(p.R[i]) kc.update(p.a) kc.update(p.b) kc.update(p.t) else: for r in rv.p.rangeSigs: for i in range(64): kc.update(r.asig.s0[i]) for i in range(64): kc.update(r.asig.s1[i]) kc.update(r.asig.ee) for i in range(64): kc.update(r.Ci[i]) c_hash = kc.digest() kc_master.update(c_hash) return kc_master.digest()
30.882075
86
0.590805
from monero_glue.xmr import crypto from monero_glue.xmr.sub.keccak_hasher import HashWrapper from monero_serialize import xmrserialize class PreMlsagHasher(object): def __init__(self, state=None): from monero_glue.xmr.sub.keccak_hasher import HashWrapper, KeccakXmrArchive self.is_simple = state[0] if state else None self.state = state[1] if state else 0 self.kc_master = HashWrapper(state[2] if state else crypto.get_keccak()) self.rsig_hasher = state[3] if state else crypto.get_keccak() self.rtcsig_hasher = None if state: self.rtcsig_hasher = KeccakXmrArchive(state[4]) if state[4] else None else: self.rtcsig_hasher = KeccakXmrArchive() def state_save(self): return ( self.is_simple, self.state, self.kc_master.ctx, self.rsig_hasher, self.rtcsig_hasher.ctx() if self.rtcsig_hasher else None, ) def state_load(self, x): from monero_glue.xmr.sub.keccak_hasher import HashWrapper, KeccakXmrArchive self.is_simple = x[0] self.state = x[1] self.kc_master = HashWrapper(x[2]) self.rsig_hasher = x[3] if x[4]: self.rtcsig_hasher = KeccakXmrArchive(x[4]) else: self.rtcsig_hasher = None def init(self, is_simple): if self.state != 0: raise ValueError("State error") self.state = 1 self.is_simple = is_simple async def set_message(self, message): self.kc_master.update(message) async def set_type_fee(self, rv_type, fee): if self.state != 1: raise ValueError("State error") self.state = 2 from monero_serialize.xmrtypes import RctSigBase rfields = RctSigBase.f_specs() await self.rtcsig_hasher.message_field(None, field=rfields[0], fvalue=rv_type) await self.rtcsig_hasher.message_field(None, field=rfields[1], fvalue=fee) async def set_pseudo_out(self, out): if self.state != 2 and self.state != 3: raise ValueError("State error") self.state = 3 from monero_serialize.xmrtypes import KeyV await self.rtcsig_hasher.field(out, KeyV.ELEM_TYPE) async def set_ecdh(self, ecdh, raw=True): if self.state != 2 and self.state != 3 and self.state != 4: raise ValueError("State error") self.state = 4 if raw: await self.rtcsig_hasher.buffer(ecdh) else: from monero_serialize.xmrtypes import EcdhInfo await self.rtcsig_hasher.field(ecdh, EcdhInfo.ELEM_TYPE) async def set_out_pk(self, out_pk, mask=None): if self.state != 4 and self.state != 5: raise ValueError("State error") self.state = 5 from monero_serialize.xmrtypes import ECKey await self.rtcsig_hasher.field(mask if mask else out_pk, ECKey) async def rctsig_base_done(self): if self.state != 5: raise ValueError("State error") self.state = 6 c_hash = self.rtcsig_hasher.get_digest() self.kc_master.update(c_hash) self.rtcsig_hasher = None async def rsig_val(self, p, bulletproof, raw=False): if self.state == 8: raise ValueError("State error") if raw: if isinstance(p, list): for x in p: self.rsig_hasher.update(x) else: self.rsig_hasher.update(p) return if bulletproof: self.rsig_hasher.update(p.A) self.rsig_hasher.update(p.S) self.rsig_hasher.update(p.T1) self.rsig_hasher.update(p.T2) self.rsig_hasher.update(p.taux) self.rsig_hasher.update(p.mu) for i in range(len(p.L)): self.rsig_hasher.update(p.L[i]) for i in range(len(p.R)): self.rsig_hasher.update(p.R[i]) self.rsig_hasher.update(p.a) self.rsig_hasher.update(p.b) self.rsig_hasher.update(p.t) else: for i in range(64): self.rsig_hasher.update(p.asig.s0[i]) for i in range(64): self.rsig_hasher.update(p.asig.s1[i]) self.rsig_hasher.update(p.asig.ee) for i in range(64): self.rsig_hasher.update(p.Ci[i]) async def get_digest(self): if self.state != 6: raise ValueError("State error") self.state = 8 c_hash = self.rsig_hasher.digest() self.rsig_hasher = None self.kc_master.update(c_hash) return self.kc_master.digest() async def get_pre_mlsag_hash(rv): from monero_glue.xmr.sub.keccak_hasher import get_keccak_writer from monero_serialize.xmrtypes import RctType kc_master = HashWrapper(crypto.get_keccak()) kc_master.update(rv.message) is_simple = rv.type in [RctType.Simple, RctType.Bulletproof, RctType.Bulletproof2] outputs = len(rv.ecdhInfo) inputs = 0 if rv.type == RctType.Simple: inputs = len(rv.pseudoOuts) elif rv.type in [RctType.Bulletproof, RctType.Bulletproof2]: inputs = len(rv.p.pseudoOuts) kwriter = get_keccak_writer() ar = xmrserialize.Archive(kwriter, True) await rv.serialize_rctsig_base(ar, inputs, outputs) c_hash = kwriter.get_digest() kc_master.update(c_hash) kc = crypto.get_keccak() if rv.type in [RctType.Bulletproof, RctType.Bulletproof2]: for p in rv.p.bulletproofs: kc.update(p.A) kc.update(p.S) kc.update(p.T1) kc.update(p.T2) kc.update(p.taux) kc.update(p.mu) for i in range(len(p.L)): kc.update(p.L[i]) for i in range(len(p.R)): kc.update(p.R[i]) kc.update(p.a) kc.update(p.b) kc.update(p.t) else: for r in rv.p.rangeSigs: for i in range(64): kc.update(r.asig.s0[i]) for i in range(64): kc.update(r.asig.s1[i]) kc.update(r.asig.ee) for i in range(64): kc.update(r.Ci[i]) c_hash = kc.digest() kc_master.update(c_hash) return kc_master.digest()
true
true