body_hash
stringlengths
64
64
body
stringlengths
23
109k
docstring
stringlengths
1
57k
path
stringlengths
4
198
name
stringlengths
1
115
repository_name
stringlengths
7
111
repository_stars
float64
0
191k
lang
stringclasses
1 value
body_without_docstring
stringlengths
14
108k
unified
stringlengths
45
133k
b33bd605a0ce5181924654b7325418997565754cf8af00e97f29fa17fd4e8b5d
@pytest.mark.parametrize('data', [cast(Dict[(str, Any)], {}), {'arn': 'aws:arn:lambda:us-east-1:function:test'}, {'type': 'origin-request'}]) def test_init_required(self, data: Dict[(str, Any)]) -> None: 'Test init required.' with pytest.raises(ValidationError): RunwayStaticSiteLambdaFunctionAssociationDataModel.parse_obj(data)
Test init required.
tests/unit/module/staticsite/parameters/test_models.py
test_init_required
blade2005/runway
134
python
@pytest.mark.parametrize('data', [cast(Dict[(str, Any)], {}), {'arn': 'aws:arn:lambda:us-east-1:function:test'}, {'type': 'origin-request'}]) def test_init_required(self, data: Dict[(str, Any)]) -> None: with pytest.raises(ValidationError): RunwayStaticSiteLambdaFunctionAssociationDataModel.parse_obj(data)
@pytest.mark.parametrize('data', [cast(Dict[(str, Any)], {}), {'arn': 'aws:arn:lambda:us-east-1:function:test'}, {'type': 'origin-request'}]) def test_init_required(self, data: Dict[(str, Any)]) -> None: with pytest.raises(ValidationError): RunwayStaticSiteLambdaFunctionAssociationDataModel.parse_obj(data)<|docstring|>Test init required.<|endoftext|>
a8f5348f096600643cb0450f753a6d3abbf339c55b26cac3d8400b70d9891cf2
def test_init(self) -> None: 'Test init.' data = {'arn': 'aws:arn:lambda:us-east-1:function:test', 'type': 'origin-request'} obj = RunwayStaticSiteLambdaFunctionAssociationDataModel(**data) assert (obj.arn == data['arn']) assert (obj.type == data['type'])
Test init.
tests/unit/module/staticsite/parameters/test_models.py
test_init
blade2005/runway
134
python
def test_init(self) -> None: data = {'arn': 'aws:arn:lambda:us-east-1:function:test', 'type': 'origin-request'} obj = RunwayStaticSiteLambdaFunctionAssociationDataModel(**data) assert (obj.arn == data['arn']) assert (obj.type == data['type'])
def test_init(self) -> None: data = {'arn': 'aws:arn:lambda:us-east-1:function:test', 'type': 'origin-request'} obj = RunwayStaticSiteLambdaFunctionAssociationDataModel(**data) assert (obj.arn == data['arn']) assert (obj.type == data['type'])<|docstring|>Test init.<|endoftext|>
dbdba291c74a9fd0cce98aab35d3571e2f2d2570a3875a182c3e9e2f39769083
def test_convert_comma_delimited_list(self) -> None: 'Test _convert_comma_delimited_list.' obj = RunwayStaticSiteModuleParametersDataModel(namespace='test', staticsite_additional_redirect_domains='redirect0,redirect1', staticsite_aliases='test-alias', staticsite_supported_identity_providers='id0, id1') assert (obj.additional_redirect_domains == ['redirect0', 'redirect1']) assert (obj.aliases == ['test-alias']) assert (obj.supported_identity_providers == ['id0', 'id1'])
Test _convert_comma_delimited_list.
tests/unit/module/staticsite/parameters/test_models.py
test_convert_comma_delimited_list
blade2005/runway
134
python
def test_convert_comma_delimited_list(self) -> None: obj = RunwayStaticSiteModuleParametersDataModel(namespace='test', staticsite_additional_redirect_domains='redirect0,redirect1', staticsite_aliases='test-alias', staticsite_supported_identity_providers='id0, id1') assert (obj.additional_redirect_domains == ['redirect0', 'redirect1']) assert (obj.aliases == ['test-alias']) assert (obj.supported_identity_providers == ['id0', 'id1'])
def test_convert_comma_delimited_list(self) -> None: obj = RunwayStaticSiteModuleParametersDataModel(namespace='test', staticsite_additional_redirect_domains='redirect0,redirect1', staticsite_aliases='test-alias', staticsite_supported_identity_providers='id0, id1') assert (obj.additional_redirect_domains == ['redirect0', 'redirect1']) assert (obj.aliases == ['test-alias']) assert (obj.supported_identity_providers == ['id0', 'id1'])<|docstring|>Test _convert_comma_delimited_list.<|endoftext|>
20d97295d81142578cc67aedf604dc33e6577d44a53128ce1ae1f7e8785c59b7
def test_init_default(self) -> None: 'Test init default.' obj = RunwayStaticSiteModuleParametersDataModel(namespace='test') assert (not obj.acmcert_arn) assert (obj.additional_redirect_domains == []) assert (obj.aliases == []) assert (obj.auth_at_edge is False) assert (obj.cf_disable is False) assert (obj.cookie_settings == {'idToken': 'Path=/; Secure; SameSite=Lax', 'accessToken': 'Path=/; Secure; SameSite=Lax', 'refreshToken': 'Path=/; Secure; SameSite=Lax', 'nonce': 'Path=/; Secure; HttpOnly; Max-Age=1800; SameSite=Lax'}) assert (obj.create_user_pool is False) assert (obj.custom_error_responses == []) assert (obj.enable_cf_logging is True) assert (obj.http_headers == {'Content-Security-Policy': "default-src https: 'unsafe-eval' 'unsafe-inline'; font-src 'self' 'unsafe-inline' 'unsafe-eval' data: https:; object-src 'none'; connect-src 'self' https://*.amazonaws.com https://*.amazoncognito.com", 'Strict-Transport-Security': 'max-age=31536000; includeSubdomains; preload', 'Referrer-Policy': 'same-origin', 'X-XSS-Protection': '1; mode=block', 'X-Frame-Options': 'DENY', 'X-Content-Type-Options': 'nosniff'}) assert (obj.lambda_function_associations == []) assert (obj.namespace == 'test') assert (obj.non_spa is False) assert (obj.oauth_scopes == ['phone', 'email', 'profile', 'openid', 'aws.cognito.signin.user.admin']) assert (obj.redirect_path_auth_refresh == '/refreshauth') assert (obj.redirect_path_sign_in == '/parseauth') assert (obj.redirect_path_sign_out == '/') assert (not obj.required_group) assert (not obj.rewrite_directory_index) assert (not obj.role_boundary_arn) assert (not obj.service_role) assert (obj.sign_out_url == '/signout') assert (obj.supported_identity_providers == ['COGNITO']) assert (not obj.user_pool_arn) assert (not obj.web_acl)
Test init default.
tests/unit/module/staticsite/parameters/test_models.py
test_init_default
blade2005/runway
134
python
def test_init_default(self) -> None: obj = RunwayStaticSiteModuleParametersDataModel(namespace='test') assert (not obj.acmcert_arn) assert (obj.additional_redirect_domains == []) assert (obj.aliases == []) assert (obj.auth_at_edge is False) assert (obj.cf_disable is False) assert (obj.cookie_settings == {'idToken': 'Path=/; Secure; SameSite=Lax', 'accessToken': 'Path=/; Secure; SameSite=Lax', 'refreshToken': 'Path=/; Secure; SameSite=Lax', 'nonce': 'Path=/; Secure; HttpOnly; Max-Age=1800; SameSite=Lax'}) assert (obj.create_user_pool is False) assert (obj.custom_error_responses == []) assert (obj.enable_cf_logging is True) assert (obj.http_headers == {'Content-Security-Policy': "default-src https: 'unsafe-eval' 'unsafe-inline'; font-src 'self' 'unsafe-inline' 'unsafe-eval' data: https:; object-src 'none'; connect-src 'self' https://*.amazonaws.com https://*.amazoncognito.com", 'Strict-Transport-Security': 'max-age=31536000; includeSubdomains; preload', 'Referrer-Policy': 'same-origin', 'X-XSS-Protection': '1; mode=block', 'X-Frame-Options': 'DENY', 'X-Content-Type-Options': 'nosniff'}) assert (obj.lambda_function_associations == []) assert (obj.namespace == 'test') assert (obj.non_spa is False) assert (obj.oauth_scopes == ['phone', 'email', 'profile', 'openid', 'aws.cognito.signin.user.admin']) assert (obj.redirect_path_auth_refresh == '/refreshauth') assert (obj.redirect_path_sign_in == '/parseauth') assert (obj.redirect_path_sign_out == '/') assert (not obj.required_group) assert (not obj.rewrite_directory_index) assert (not obj.role_boundary_arn) assert (not obj.service_role) assert (obj.sign_out_url == '/signout') assert (obj.supported_identity_providers == ['COGNITO']) assert (not obj.user_pool_arn) assert (not obj.web_acl)
def test_init_default(self) -> None: obj = RunwayStaticSiteModuleParametersDataModel(namespace='test') assert (not obj.acmcert_arn) assert (obj.additional_redirect_domains == []) assert (obj.aliases == []) assert (obj.auth_at_edge is False) assert (obj.cf_disable is False) assert (obj.cookie_settings == {'idToken': 'Path=/; Secure; SameSite=Lax', 'accessToken': 'Path=/; Secure; SameSite=Lax', 'refreshToken': 'Path=/; Secure; SameSite=Lax', 'nonce': 'Path=/; Secure; HttpOnly; Max-Age=1800; SameSite=Lax'}) assert (obj.create_user_pool is False) assert (obj.custom_error_responses == []) assert (obj.enable_cf_logging is True) assert (obj.http_headers == {'Content-Security-Policy': "default-src https: 'unsafe-eval' 'unsafe-inline'; font-src 'self' 'unsafe-inline' 'unsafe-eval' data: https:; object-src 'none'; connect-src 'self' https://*.amazonaws.com https://*.amazoncognito.com", 'Strict-Transport-Security': 'max-age=31536000; includeSubdomains; preload', 'Referrer-Policy': 'same-origin', 'X-XSS-Protection': '1; mode=block', 'X-Frame-Options': 'DENY', 'X-Content-Type-Options': 'nosniff'}) assert (obj.lambda_function_associations == []) assert (obj.namespace == 'test') assert (obj.non_spa is False) assert (obj.oauth_scopes == ['phone', 'email', 'profile', 'openid', 'aws.cognito.signin.user.admin']) assert (obj.redirect_path_auth_refresh == '/refreshauth') assert (obj.redirect_path_sign_in == '/parseauth') assert (obj.redirect_path_sign_out == '/') assert (not obj.required_group) assert (not obj.rewrite_directory_index) assert (not obj.role_boundary_arn) assert (not obj.service_role) assert (obj.sign_out_url == '/signout') assert (obj.supported_identity_providers == ['COGNITO']) assert (not obj.user_pool_arn) assert (not obj.web_acl)<|docstring|>Test init default.<|endoftext|>
1b136c1287882a8356af5e62afb290c3db731b3d0d8be6495236796996772463
def test_init_extra(self) -> None: 'Test init extra.' obj = RunwayStaticSiteModuleParametersDataModel(namespace='test', invalid='val') assert ('invalid' not in obj.dict())
Test init extra.
tests/unit/module/staticsite/parameters/test_models.py
test_init_extra
blade2005/runway
134
python
def test_init_extra(self) -> None: obj = RunwayStaticSiteModuleParametersDataModel(namespace='test', invalid='val') assert ('invalid' not in obj.dict())
def test_init_extra(self) -> None: obj = RunwayStaticSiteModuleParametersDataModel(namespace='test', invalid='val') assert ('invalid' not in obj.dict())<|docstring|>Test init extra.<|endoftext|>
5652cd264922f7a4a7268079999abf1803e8df852ffb55bc9196be754a8e559a
def test_init_required(self) -> None: 'Test init required.' with pytest.raises(ValidationError): RunwayStaticSiteModuleParametersDataModel.parse_obj({})
Test init required.
tests/unit/module/staticsite/parameters/test_models.py
test_init_required
blade2005/runway
134
python
def test_init_required(self) -> None: with pytest.raises(ValidationError): RunwayStaticSiteModuleParametersDataModel.parse_obj({})
def test_init_required(self) -> None: with pytest.raises(ValidationError): RunwayStaticSiteModuleParametersDataModel.parse_obj({})<|docstring|>Test init required.<|endoftext|>
fd91152b1c64cf363223feeafc7910fd7a2c91af3d96b78761a889ce1b741cc9
def test_init(self) -> None: 'Test init.' data = {'cloudformation_service_role': 'aws:arn:iam:123456789012:role/name', 'staticsite_acmcert_arn': 'aws:arn:acm:us-east-1:cert:test', 'staticsite_additional_redirect_domains': ['github.com'], 'staticsite_aliases': ['test-alias'], 'staticsite_auth_at_edge': True, 'staticsite_cf_disable': True, 'staticsite_cookie_settings': {'test-cookie': 'val'}, 'staticsite_create_user_pool': True, 'staticsite_custom_error_responses': [{'ErrorCode': 404}], 'staticsite_enable_cf_logging': False, 'staticsite_http_headers': {'test-header': 'val'}, 'staticsite_lambda_function_associations': [{'arn': 'aws:arn:lambda:us-east-1:function:test', 'type': 'origin-request'}], 'namespace': 'test', 'staticsite_non_spa': True, 'staticsite_oauth_scopes': ['email'], 'staticsite_redirect_path_auth_refresh': '/test-refresh', 'staticsite_redirect_path_sign_in': '/test-sign-in', 'staticsite_redirect_path_sign_out': '/test-sign-out-redirect', 'staticsite_required_group': 'any', 'staticsite_rewrite_directory_index': 'test-rewrite-index', 'staticsite_role_boundary_arn': 'arn:aws:iam:::role/test', 'staticsite_sign_out_url': '/test-sign-out', 'staticsite_supported_identity_providers': ['google'], 'staticsite_user_pool_arn': 'arn:aws:cognito:::pool/test', 'staticsite_web_acl': 'arn:aws::::acl/test'} obj = RunwayStaticSiteModuleParametersDataModel(**data) assert (obj.acmcert_arn == data['staticsite_acmcert_arn']) assert (obj.additional_redirect_domains == data['staticsite_additional_redirect_domains']) assert (obj.aliases == data['staticsite_aliases']) assert (obj.auth_at_edge is data['staticsite_auth_at_edge']) assert (obj.cf_disable is data['staticsite_cf_disable']) assert (obj.cookie_settings == data['staticsite_cookie_settings']) assert (obj.create_user_pool is data['staticsite_create_user_pool']) assert (len(obj.custom_error_responses) == len(data['staticsite_custom_error_responses'])) assert (obj.custom_error_responses[0].dict(exclude_none=True) == data['staticsite_custom_error_responses'][0]) assert (obj.enable_cf_logging is data['staticsite_enable_cf_logging']) assert (obj.http_headers == data['staticsite_http_headers']) assert (len(obj.lambda_function_associations) == len(data['staticsite_lambda_function_associations'])) assert (obj.lambda_function_associations[0].dict() == data['staticsite_lambda_function_associations'][0]) assert (obj.namespace == data['namespace']) assert (obj.non_spa is data['staticsite_non_spa']) assert (obj.oauth_scopes == data['staticsite_oauth_scopes']) assert (obj.redirect_path_auth_refresh == data['staticsite_redirect_path_auth_refresh']) assert (obj.redirect_path_sign_in == data['staticsite_redirect_path_sign_in']) assert (obj.redirect_path_sign_out == data['staticsite_redirect_path_sign_out']) assert (obj.required_group == data['staticsite_required_group']) assert (obj.rewrite_directory_index == data['staticsite_rewrite_directory_index']) assert (obj.role_boundary_arn == data['staticsite_role_boundary_arn']) assert (obj.service_role == data['cloudformation_service_role']) assert (obj.sign_out_url == data['staticsite_sign_out_url']) assert (obj.supported_identity_providers == data['staticsite_supported_identity_providers']) assert (obj.user_pool_arn == data['staticsite_user_pool_arn']) assert (obj.web_acl == data['staticsite_web_acl'])
Test init.
tests/unit/module/staticsite/parameters/test_models.py
test_init
blade2005/runway
134
python
def test_init(self) -> None: data = {'cloudformation_service_role': 'aws:arn:iam:123456789012:role/name', 'staticsite_acmcert_arn': 'aws:arn:acm:us-east-1:cert:test', 'staticsite_additional_redirect_domains': ['github.com'], 'staticsite_aliases': ['test-alias'], 'staticsite_auth_at_edge': True, 'staticsite_cf_disable': True, 'staticsite_cookie_settings': {'test-cookie': 'val'}, 'staticsite_create_user_pool': True, 'staticsite_custom_error_responses': [{'ErrorCode': 404}], 'staticsite_enable_cf_logging': False, 'staticsite_http_headers': {'test-header': 'val'}, 'staticsite_lambda_function_associations': [{'arn': 'aws:arn:lambda:us-east-1:function:test', 'type': 'origin-request'}], 'namespace': 'test', 'staticsite_non_spa': True, 'staticsite_oauth_scopes': ['email'], 'staticsite_redirect_path_auth_refresh': '/test-refresh', 'staticsite_redirect_path_sign_in': '/test-sign-in', 'staticsite_redirect_path_sign_out': '/test-sign-out-redirect', 'staticsite_required_group': 'any', 'staticsite_rewrite_directory_index': 'test-rewrite-index', 'staticsite_role_boundary_arn': 'arn:aws:iam:::role/test', 'staticsite_sign_out_url': '/test-sign-out', 'staticsite_supported_identity_providers': ['google'], 'staticsite_user_pool_arn': 'arn:aws:cognito:::pool/test', 'staticsite_web_acl': 'arn:aws::::acl/test'} obj = RunwayStaticSiteModuleParametersDataModel(**data) assert (obj.acmcert_arn == data['staticsite_acmcert_arn']) assert (obj.additional_redirect_domains == data['staticsite_additional_redirect_domains']) assert (obj.aliases == data['staticsite_aliases']) assert (obj.auth_at_edge is data['staticsite_auth_at_edge']) assert (obj.cf_disable is data['staticsite_cf_disable']) assert (obj.cookie_settings == data['staticsite_cookie_settings']) assert (obj.create_user_pool is data['staticsite_create_user_pool']) assert (len(obj.custom_error_responses) == len(data['staticsite_custom_error_responses'])) assert (obj.custom_error_responses[0].dict(exclude_none=True) == data['staticsite_custom_error_responses'][0]) assert (obj.enable_cf_logging is data['staticsite_enable_cf_logging']) assert (obj.http_headers == data['staticsite_http_headers']) assert (len(obj.lambda_function_associations) == len(data['staticsite_lambda_function_associations'])) assert (obj.lambda_function_associations[0].dict() == data['staticsite_lambda_function_associations'][0]) assert (obj.namespace == data['namespace']) assert (obj.non_spa is data['staticsite_non_spa']) assert (obj.oauth_scopes == data['staticsite_oauth_scopes']) assert (obj.redirect_path_auth_refresh == data['staticsite_redirect_path_auth_refresh']) assert (obj.redirect_path_sign_in == data['staticsite_redirect_path_sign_in']) assert (obj.redirect_path_sign_out == data['staticsite_redirect_path_sign_out']) assert (obj.required_group == data['staticsite_required_group']) assert (obj.rewrite_directory_index == data['staticsite_rewrite_directory_index']) assert (obj.role_boundary_arn == data['staticsite_role_boundary_arn']) assert (obj.service_role == data['cloudformation_service_role']) assert (obj.sign_out_url == data['staticsite_sign_out_url']) assert (obj.supported_identity_providers == data['staticsite_supported_identity_providers']) assert (obj.user_pool_arn == data['staticsite_user_pool_arn']) assert (obj.web_acl == data['staticsite_web_acl'])
def test_init(self) -> None: data = {'cloudformation_service_role': 'aws:arn:iam:123456789012:role/name', 'staticsite_acmcert_arn': 'aws:arn:acm:us-east-1:cert:test', 'staticsite_additional_redirect_domains': ['github.com'], 'staticsite_aliases': ['test-alias'], 'staticsite_auth_at_edge': True, 'staticsite_cf_disable': True, 'staticsite_cookie_settings': {'test-cookie': 'val'}, 'staticsite_create_user_pool': True, 'staticsite_custom_error_responses': [{'ErrorCode': 404}], 'staticsite_enable_cf_logging': False, 'staticsite_http_headers': {'test-header': 'val'}, 'staticsite_lambda_function_associations': [{'arn': 'aws:arn:lambda:us-east-1:function:test', 'type': 'origin-request'}], 'namespace': 'test', 'staticsite_non_spa': True, 'staticsite_oauth_scopes': ['email'], 'staticsite_redirect_path_auth_refresh': '/test-refresh', 'staticsite_redirect_path_sign_in': '/test-sign-in', 'staticsite_redirect_path_sign_out': '/test-sign-out-redirect', 'staticsite_required_group': 'any', 'staticsite_rewrite_directory_index': 'test-rewrite-index', 'staticsite_role_boundary_arn': 'arn:aws:iam:::role/test', 'staticsite_sign_out_url': '/test-sign-out', 'staticsite_supported_identity_providers': ['google'], 'staticsite_user_pool_arn': 'arn:aws:cognito:::pool/test', 'staticsite_web_acl': 'arn:aws::::acl/test'} obj = RunwayStaticSiteModuleParametersDataModel(**data) assert (obj.acmcert_arn == data['staticsite_acmcert_arn']) assert (obj.additional_redirect_domains == data['staticsite_additional_redirect_domains']) assert (obj.aliases == data['staticsite_aliases']) assert (obj.auth_at_edge is data['staticsite_auth_at_edge']) assert (obj.cf_disable is data['staticsite_cf_disable']) assert (obj.cookie_settings == data['staticsite_cookie_settings']) assert (obj.create_user_pool is data['staticsite_create_user_pool']) assert (len(obj.custom_error_responses) == len(data['staticsite_custom_error_responses'])) assert (obj.custom_error_responses[0].dict(exclude_none=True) == data['staticsite_custom_error_responses'][0]) assert (obj.enable_cf_logging is data['staticsite_enable_cf_logging']) assert (obj.http_headers == data['staticsite_http_headers']) assert (len(obj.lambda_function_associations) == len(data['staticsite_lambda_function_associations'])) assert (obj.lambda_function_associations[0].dict() == data['staticsite_lambda_function_associations'][0]) assert (obj.namespace == data['namespace']) assert (obj.non_spa is data['staticsite_non_spa']) assert (obj.oauth_scopes == data['staticsite_oauth_scopes']) assert (obj.redirect_path_auth_refresh == data['staticsite_redirect_path_auth_refresh']) assert (obj.redirect_path_sign_in == data['staticsite_redirect_path_sign_in']) assert (obj.redirect_path_sign_out == data['staticsite_redirect_path_sign_out']) assert (obj.required_group == data['staticsite_required_group']) assert (obj.rewrite_directory_index == data['staticsite_rewrite_directory_index']) assert (obj.role_boundary_arn == data['staticsite_role_boundary_arn']) assert (obj.service_role == data['cloudformation_service_role']) assert (obj.sign_out_url == data['staticsite_sign_out_url']) assert (obj.supported_identity_providers == data['staticsite_supported_identity_providers']) assert (obj.user_pool_arn == data['staticsite_user_pool_arn']) assert (obj.web_acl == data['staticsite_web_acl'])<|docstring|>Test init.<|endoftext|>
ee9b7caaabd516267515dccdcd6a68d541bb39f187384c29def9053a2631b879
def main(): 'main entry point for module execution\n ' argument_spec = dict(lines=dict(type='list', aliases=['commands'], required=True), save_when=dict(choices=['always', 'never', 'modified', 'changed'], default='never')) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) lines = module.params['lines'] result = {'changed': False} if (lines and (not module.check_mode)): r = edit_config(module, lines) result['changed'] = True result['commands'] = lines result['updates'] = lines result['result'] = r commit_resp = r.get('commit_response') if commit_resp: result['warnings'] = commit_resp if (module.params['save_when'] == 'modified'): output = run_commands(module, ['show running-config', 'show startup-config']) diff_ignore_lines = module.params['diff_ignore_lines'] running_config = NetworkConfig(indent=1, contents=output[0], ignore_lines=diff_ignore_lines) startup_config = NetworkConfig(indent=1, contents=output[1], ignore_lines=diff_ignore_lines) if (running_config.sha1 != startup_config.sha1): save_config(module, result) module.exit_json(**result)
main entry point for module execution
plugins/modules/fujitsu_ipcom_config.py
main
takamitsu-iida/ansible-fujitsu-devices
1
python
def main(): '\n ' argument_spec = dict(lines=dict(type='list', aliases=['commands'], required=True), save_when=dict(choices=['always', 'never', 'modified', 'changed'], default='never')) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) lines = module.params['lines'] result = {'changed': False} if (lines and (not module.check_mode)): r = edit_config(module, lines) result['changed'] = True result['commands'] = lines result['updates'] = lines result['result'] = r commit_resp = r.get('commit_response') if commit_resp: result['warnings'] = commit_resp if (module.params['save_when'] == 'modified'): output = run_commands(module, ['show running-config', 'show startup-config']) diff_ignore_lines = module.params['diff_ignore_lines'] running_config = NetworkConfig(indent=1, contents=output[0], ignore_lines=diff_ignore_lines) startup_config = NetworkConfig(indent=1, contents=output[1], ignore_lines=diff_ignore_lines) if (running_config.sha1 != startup_config.sha1): save_config(module, result) module.exit_json(**result)
def main(): '\n ' argument_spec = dict(lines=dict(type='list', aliases=['commands'], required=True), save_when=dict(choices=['always', 'never', 'modified', 'changed'], default='never')) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) lines = module.params['lines'] result = {'changed': False} if (lines and (not module.check_mode)): r = edit_config(module, lines) result['changed'] = True result['commands'] = lines result['updates'] = lines result['result'] = r commit_resp = r.get('commit_response') if commit_resp: result['warnings'] = commit_resp if (module.params['save_when'] == 'modified'): output = run_commands(module, ['show running-config', 'show startup-config']) diff_ignore_lines = module.params['diff_ignore_lines'] running_config = NetworkConfig(indent=1, contents=output[0], ignore_lines=diff_ignore_lines) startup_config = NetworkConfig(indent=1, contents=output[1], ignore_lines=diff_ignore_lines) if (running_config.sha1 != startup_config.sha1): save_config(module, result) module.exit_json(**result)<|docstring|>main entry point for module execution<|endoftext|>
9efbe534438b749d70bd910c347a9f9d805dd487086285f2656da3fefdfe39c6
@app.route('/predict') def predict_note_authentication(): "\n Let's Authenticate the Bank Note\n Using Docstring for specifications.\n ---\n ---\n parameters:\n - name: variance\n in: query\n type: number\n required: true\n - name: skewness\n in: query\n type: number\n required: true\n - name: curtosis\n in: query\n type: number\n required: true\n - name: entropy\n in: query\n type: number\n required: true\n responses:\n 200:\n description: The output values\n\n " variance = request.args.get('variance') skewness = request.args.get('skewness') curtosis = request.args.get('curtosis') entropy = request.args.get('entropy') prediction = classifier.predict([[variance, skewness, curtosis, entropy]]) return ('The predicted value is ' + str(prediction))
Let's Authenticate the Bank Note Using Docstring for specifications. --- --- parameters: - name: variance in: query type: number required: true - name: skewness in: query type: number required: true - name: curtosis in: query type: number required: true - name: entropy in: query type: number required: true responses: 200: description: The output values
app.py
predict_note_authentication
devangi2000/money-authenticator
0
python
@app.route('/predict') def predict_note_authentication(): "\n Let's Authenticate the Bank Note\n Using Docstring for specifications.\n ---\n ---\n parameters:\n - name: variance\n in: query\n type: number\n required: true\n - name: skewness\n in: query\n type: number\n required: true\n - name: curtosis\n in: query\n type: number\n required: true\n - name: entropy\n in: query\n type: number\n required: true\n responses:\n 200:\n description: The output values\n\n " variance = request.args.get('variance') skewness = request.args.get('skewness') curtosis = request.args.get('curtosis') entropy = request.args.get('entropy') prediction = classifier.predict([[variance, skewness, curtosis, entropy]]) return ('The predicted value is ' + str(prediction))
@app.route('/predict') def predict_note_authentication(): "\n Let's Authenticate the Bank Note\n Using Docstring for specifications.\n ---\n ---\n parameters:\n - name: variance\n in: query\n type: number\n required: true\n - name: skewness\n in: query\n type: number\n required: true\n - name: curtosis\n in: query\n type: number\n required: true\n - name: entropy\n in: query\n type: number\n required: true\n responses:\n 200:\n description: The output values\n\n " variance = request.args.get('variance') skewness = request.args.get('skewness') curtosis = request.args.get('curtosis') entropy = request.args.get('entropy') prediction = classifier.predict([[variance, skewness, curtosis, entropy]]) return ('The predicted value is ' + str(prediction))<|docstring|>Let's Authenticate the Bank Note Using Docstring for specifications. --- --- parameters: - name: variance in: query type: number required: true - name: skewness in: query type: number required: true - name: curtosis in: query type: number required: true - name: entropy in: query type: number required: true responses: 200: description: The output values<|endoftext|>
c817b4178680146d89a570d6c6548ab13c9eadd89032a6e950b712359c460e35
@app.route('/predict_file', methods=['POST']) def predict_note_file(): "Let's Authenticate the Banks Note\n This is using docstrings for specifications.\n ---\n parameters:\n - name: file\n in: formData\n type: file\n required: true\n\n responses:\n 200:\n description: The output values\n\n " df_test = pd.read_csv(request.files.get('file')) prediction = classifier.predict(df_test) return ('The predicted value is ' + str(list(prediction)))
Let's Authenticate the Banks Note This is using docstrings for specifications. --- parameters: - name: file in: formData type: file required: true responses: 200: description: The output values
app.py
predict_note_file
devangi2000/money-authenticator
0
python
@app.route('/predict_file', methods=['POST']) def predict_note_file(): "Let's Authenticate the Banks Note\n This is using docstrings for specifications.\n ---\n parameters:\n - name: file\n in: formData\n type: file\n required: true\n\n responses:\n 200:\n description: The output values\n\n " df_test = pd.read_csv(request.files.get('file')) prediction = classifier.predict(df_test) return ('The predicted value is ' + str(list(prediction)))
@app.route('/predict_file', methods=['POST']) def predict_note_file(): "Let's Authenticate the Banks Note\n This is using docstrings for specifications.\n ---\n parameters:\n - name: file\n in: formData\n type: file\n required: true\n\n responses:\n 200:\n description: The output values\n\n " df_test = pd.read_csv(request.files.get('file')) prediction = classifier.predict(df_test) return ('The predicted value is ' + str(list(prediction)))<|docstring|>Let's Authenticate the Banks Note This is using docstrings for specifications. --- parameters: - name: file in: formData type: file required: true responses: 200: description: The output values<|endoftext|>
9fa6d1f5c63e03420f8e4fa9c78b246e8246b5b064926ea2d424ee4b1d116a2b
def maybe_model(arg: Any) -> Any: 'Convert argument to model if possible.' try: model = registry[arg['__faust']['ns']] except (KeyError, TypeError): return arg else: return model.from_data(arg)
Convert argument to model if possible.
consumers/venv/lib/python3.7/site-packages/faust/models/base.py
maybe_model
spencerpomme/Public-Transit-Status-with-Apache-Kafka
0
python
def maybe_model(arg: Any) -> Any: try: model = registry[arg['__faust']['ns']] except (KeyError, TypeError): return arg else: return model.from_data(arg)
def maybe_model(arg: Any) -> Any: try: model = registry[arg['__faust']['ns']] except (KeyError, TypeError): return arg else: return model.from_data(arg)<|docstring|>Convert argument to model if possible.<|endoftext|>
648dc791b7d3378225bcb3b01704c5feee1f165d6fc9195013a2625010e39cff
@classmethod def loads(cls, s: bytes, *, default_serializer: CodecArg=None, serializer: CodecArg=None) -> ModelT: 'Deserialize model object from bytes.\n\n Keyword Arguments:\n serializer (CodecArg): Default serializer to use\n if no custom serializer was set for this model subclass.\n ' if (default_serializer is not None): warnings.warn(DeprecationWarning('default_serializer deprecated, use: serializer')) ser = (cls._options.serializer or serializer or default_serializer) data = loads(ser, s) return cls.from_data(data)
Deserialize model object from bytes. Keyword Arguments: serializer (CodecArg): Default serializer to use if no custom serializer was set for this model subclass.
consumers/venv/lib/python3.7/site-packages/faust/models/base.py
loads
spencerpomme/Public-Transit-Status-with-Apache-Kafka
0
python
@classmethod def loads(cls, s: bytes, *, default_serializer: CodecArg=None, serializer: CodecArg=None) -> ModelT: 'Deserialize model object from bytes.\n\n Keyword Arguments:\n serializer (CodecArg): Default serializer to use\n if no custom serializer was set for this model subclass.\n ' if (default_serializer is not None): warnings.warn(DeprecationWarning('default_serializer deprecated, use: serializer')) ser = (cls._options.serializer or serializer or default_serializer) data = loads(ser, s) return cls.from_data(data)
@classmethod def loads(cls, s: bytes, *, default_serializer: CodecArg=None, serializer: CodecArg=None) -> ModelT: 'Deserialize model object from bytes.\n\n Keyword Arguments:\n serializer (CodecArg): Default serializer to use\n if no custom serializer was set for this model subclass.\n ' if (default_serializer is not None): warnings.warn(DeprecationWarning('default_serializer deprecated, use: serializer')) ser = (cls._options.serializer or serializer or default_serializer) data = loads(ser, s) return cls.from_data(data)<|docstring|>Deserialize model object from bytes. Keyword Arguments: serializer (CodecArg): Default serializer to use if no custom serializer was set for this model subclass.<|endoftext|>
5589f3919ac7fc755650236ac30d5537c10f1475279dac3a056bf649298d5792
@abc.abstractmethod def to_representation(self) -> Any: 'Convert object to JSON serializable object.'
Convert object to JSON serializable object.
consumers/venv/lib/python3.7/site-packages/faust/models/base.py
to_representation
spencerpomme/Public-Transit-Status-with-Apache-Kafka
0
python
@abc.abstractmethod def to_representation(self) -> Any:
@abc.abstractmethod def to_representation(self) -> Any: <|docstring|>Convert object to JSON serializable object.<|endoftext|>
e337e25cde31ca9d446764b5f6bb1dd1c7943d149fafc57cf3b52cfe008ba1ba
@abc.abstractmethod def _humanize(self) -> str: 'Return string representation of object for debugging purposes.' ...
Return string representation of object for debugging purposes.
consumers/venv/lib/python3.7/site-packages/faust/models/base.py
_humanize
spencerpomme/Public-Transit-Status-with-Apache-Kafka
0
python
@abc.abstractmethod def _humanize(self) -> str: ...
@abc.abstractmethod def _humanize(self) -> str: ...<|docstring|>Return string representation of object for debugging purposes.<|endoftext|>
0671577ba6bfbee2cea16486f3e346d2647d99c750e5587a619f497d1c4ef3db
def derive(self, *objects: ModelT, **fields: Any) -> ModelT: 'Derive new model with certain fields changed.' return self._derive(*objects, **fields)
Derive new model with certain fields changed.
consumers/venv/lib/python3.7/site-packages/faust/models/base.py
derive
spencerpomme/Public-Transit-Status-with-Apache-Kafka
0
python
def derive(self, *objects: ModelT, **fields: Any) -> ModelT: return self._derive(*objects, **fields)
def derive(self, *objects: ModelT, **fields: Any) -> ModelT: return self._derive(*objects, **fields)<|docstring|>Derive new model with certain fields changed.<|endoftext|>
f80c07acad5b782350c8a4686c7ac019a5e5baee879e286e89ea3753a4736e15
def dumps(self, *, serializer: CodecArg=None) -> bytes: 'Serialize object to the target serialization format.' return dumps((serializer or self._options.serializer), self.to_representation())
Serialize object to the target serialization format.
consumers/venv/lib/python3.7/site-packages/faust/models/base.py
dumps
spencerpomme/Public-Transit-Status-with-Apache-Kafka
0
python
def dumps(self, *, serializer: CodecArg=None) -> bytes: return dumps((serializer or self._options.serializer), self.to_representation())
def dumps(self, *, serializer: CodecArg=None) -> bytes: return dumps((serializer or self._options.serializer), self.to_representation())<|docstring|>Serialize object to the target serialization format.<|endoftext|>
0ab238e9a7021370a2c11b8ca218bdeae2d7ffe33f1a67aa27bdb2523ad11b0c
def generate_divider(token='*', count=72, pre='\n', post='\n', **kwargs): "Generate divider string.\n\n Method generates a divider string.\n\n Keyword Arguments:\n token {str} -- token used to generate\n (default: {'*'})\n count {number} -- divider length\n (default: {72})\n pre {str} -- token to generate before message\n (default: {'\\n'})\n post {str} -- token to generate after message\n (default: {'\\n'})\n " msg = (token * count) kwargs['stamped'] = False return _generate(msg=msg, tags=[], pre=pre, post=post, **kwargs)
Generate divider string. Method generates a divider string. Keyword Arguments: token {str} -- token used to generate (default: {'*'}) count {number} -- divider length (default: {72}) pre {str} -- token to generate before message (default: {'\n'}) post {str} -- token to generate after message (default: {'\n'})
gkit_utils/message_generator.py
generate_divider
gannon93/gkit_utils
0
python
def generate_divider(token='*', count=72, pre='\n', post='\n', **kwargs): "Generate divider string.\n\n Method generates a divider string.\n\n Keyword Arguments:\n token {str} -- token used to generate\n (default: {'*'})\n count {number} -- divider length\n (default: {72})\n pre {str} -- token to generate before message\n (default: {'\\n'})\n post {str} -- token to generate after message\n (default: {'\\n'})\n " msg = (token * count) kwargs['stamped'] = False return _generate(msg=msg, tags=[], pre=pre, post=post, **kwargs)
def generate_divider(token='*', count=72, pre='\n', post='\n', **kwargs): "Generate divider string.\n\n Method generates a divider string.\n\n Keyword Arguments:\n token {str} -- token used to generate\n (default: {'*'})\n count {number} -- divider length\n (default: {72})\n pre {str} -- token to generate before message\n (default: {'\\n'})\n post {str} -- token to generate after message\n (default: {'\\n'})\n " msg = (token * count) kwargs['stamped'] = False return _generate(msg=msg, tags=[], pre=pre, post=post, **kwargs)<|docstring|>Generate divider string. Method generates a divider string. Keyword Arguments: token {str} -- token used to generate (default: {'*'}) count {number} -- divider length (default: {72}) pre {str} -- token to generate before message (default: {'\n'}) post {str} -- token to generate after message (default: {'\n'})<|endoftext|>
b75af258929b99b6b07fecb98bc7fcdbf69f7d3de5ed29c792f8057fbfd81629
def generate_error(msg, tags=['ERROR'], pre='', post='', **kwargs): "Generate an error message.\n\n Method generates an error message.\n\n Arguments:\n msg {str} -- message to generate\n\n Keyword Arguments:\n tag {str} -- tag to denote type of message\n (default: {'ERROR'})\n pre {str} -- token to generate before message\n (default: {'\\n'})\n post {str} -- token to generate after message\n (default: {'\\n'})\n " return _generate(msg=msg, tags=tags, pre=pre, post=post, **kwargs)
Generate an error message. Method generates an error message. Arguments: msg {str} -- message to generate Keyword Arguments: tag {str} -- tag to denote type of message (default: {'ERROR'}) pre {str} -- token to generate before message (default: {'\n'}) post {str} -- token to generate after message (default: {'\n'})
gkit_utils/message_generator.py
generate_error
gannon93/gkit_utils
0
python
def generate_error(msg, tags=['ERROR'], pre=, post=, **kwargs): "Generate an error message.\n\n Method generates an error message.\n\n Arguments:\n msg {str} -- message to generate\n\n Keyword Arguments:\n tag {str} -- tag to denote type of message\n (default: {'ERROR'})\n pre {str} -- token to generate before message\n (default: {'\\n'})\n post {str} -- token to generate after message\n (default: {'\\n'})\n " return _generate(msg=msg, tags=tags, pre=pre, post=post, **kwargs)
def generate_error(msg, tags=['ERROR'], pre=, post=, **kwargs): "Generate an error message.\n\n Method generates an error message.\n\n Arguments:\n msg {str} -- message to generate\n\n Keyword Arguments:\n tag {str} -- tag to denote type of message\n (default: {'ERROR'})\n pre {str} -- token to generate before message\n (default: {'\\n'})\n post {str} -- token to generate after message\n (default: {'\\n'})\n " return _generate(msg=msg, tags=tags, pre=pre, post=post, **kwargs)<|docstring|>Generate an error message. Method generates an error message. Arguments: msg {str} -- message to generate Keyword Arguments: tag {str} -- tag to denote type of message (default: {'ERROR'}) pre {str} -- token to generate before message (default: {'\n'}) post {str} -- token to generate after message (default: {'\n'})<|endoftext|>
2c433d4674a2160d0cc9c76f9e1489a8453bf962571c308afdcd3d86421f205f
def generate_event(msg, tags=['EVENT'], pre='', post='', **kwargs): "Generate an event message.\n\n Method generates an event message.\n\n Arguments:\n msg {str} -- message to generate\n\n Keyword Arguments:\n tag {str} -- tag to denote type of message\n (default: {'EVENT'})\n pre {str} -- token to generate before message\n (default: {'\\n'})\n post {str} -- token to generate after message\n (default: {'\\n'})\n " return _generate(msg=msg, tags=tags, pre=pre, post=post, **kwargs)
Generate an event message. Method generates an event message. Arguments: msg {str} -- message to generate Keyword Arguments: tag {str} -- tag to denote type of message (default: {'EVENT'}) pre {str} -- token to generate before message (default: {'\n'}) post {str} -- token to generate after message (default: {'\n'})
gkit_utils/message_generator.py
generate_event
gannon93/gkit_utils
0
python
def generate_event(msg, tags=['EVENT'], pre=, post=, **kwargs): "Generate an event message.\n\n Method generates an event message.\n\n Arguments:\n msg {str} -- message to generate\n\n Keyword Arguments:\n tag {str} -- tag to denote type of message\n (default: {'EVENT'})\n pre {str} -- token to generate before message\n (default: {'\\n'})\n post {str} -- token to generate after message\n (default: {'\\n'})\n " return _generate(msg=msg, tags=tags, pre=pre, post=post, **kwargs)
def generate_event(msg, tags=['EVENT'], pre=, post=, **kwargs): "Generate an event message.\n\n Method generates an event message.\n\n Arguments:\n msg {str} -- message to generate\n\n Keyword Arguments:\n tag {str} -- tag to denote type of message\n (default: {'EVENT'})\n pre {str} -- token to generate before message\n (default: {'\\n'})\n post {str} -- token to generate after message\n (default: {'\\n'})\n " return _generate(msg=msg, tags=tags, pre=pre, post=post, **kwargs)<|docstring|>Generate an event message. Method generates an event message. Arguments: msg {str} -- message to generate Keyword Arguments: tag {str} -- tag to denote type of message (default: {'EVENT'}) pre {str} -- token to generate before message (default: {'\n'}) post {str} -- token to generate after message (default: {'\n'})<|endoftext|>
ff47280e8510ea440a685ac2efcb63b23bf58953828dc87fd03956133c06f187
def generate_success(msg, tags=['SUCCESS'], pre='', post='\n', **kwargs): "Generate a success message.\n\n Method generates a success message.\n\n Arguments:\n msg {str} -- message to generate\n\n Keyword Arguments:\n tag {str} -- tag to denote type of message\n (default: {'SUCCESS'})\n pre {str} -- token to generate before message\n (default: {'\\n'})\n post {str} -- token to generate after message\n (default: {'\\n'})\n " return _generate(msg=msg, tags=tags, pre=pre, post=post, **kwargs)
Generate a success message. Method generates a success message. Arguments: msg {str} -- message to generate Keyword Arguments: tag {str} -- tag to denote type of message (default: {'SUCCESS'}) pre {str} -- token to generate before message (default: {'\n'}) post {str} -- token to generate after message (default: {'\n'})
gkit_utils/message_generator.py
generate_success
gannon93/gkit_utils
0
python
def generate_success(msg, tags=['SUCCESS'], pre=, post='\n', **kwargs): "Generate a success message.\n\n Method generates a success message.\n\n Arguments:\n msg {str} -- message to generate\n\n Keyword Arguments:\n tag {str} -- tag to denote type of message\n (default: {'SUCCESS'})\n pre {str} -- token to generate before message\n (default: {'\\n'})\n post {str} -- token to generate after message\n (default: {'\\n'})\n " return _generate(msg=msg, tags=tags, pre=pre, post=post, **kwargs)
def generate_success(msg, tags=['SUCCESS'], pre=, post='\n', **kwargs): "Generate a success message.\n\n Method generates a success message.\n\n Arguments:\n msg {str} -- message to generate\n\n Keyword Arguments:\n tag {str} -- tag to denote type of message\n (default: {'SUCCESS'})\n pre {str} -- token to generate before message\n (default: {'\\n'})\n post {str} -- token to generate after message\n (default: {'\\n'})\n " return _generate(msg=msg, tags=tags, pre=pre, post=post, **kwargs)<|docstring|>Generate a success message. Method generates a success message. Arguments: msg {str} -- message to generate Keyword Arguments: tag {str} -- tag to denote type of message (default: {'SUCCESS'}) pre {str} -- token to generate before message (default: {'\n'}) post {str} -- token to generate after message (default: {'\n'})<|endoftext|>
e90583e8c7dbbadf1b790af33d521b6ba55de3c14ca66156bec377823d1ce42a
def generate_startup(msg, tags=['STARTUP'], pre='', post='', **kwargs): "Generate a success message.\n\n Method generates a success message.\n\n Arguments:\n msg {str} -- message to generate\n\n Keyword Arguments:\n tag {str} -- tag to denote type of message\n (default: {'STARTUP'})\n pre {str} -- token to generate before message\n (default: {'\\n'})\n post {str} -- token to generate after message\n (default: {'\\n'})\n " return _generate(msg=msg, tags=tags, pre=pre, post=post, **kwargs)
Generate a success message. Method generates a success message. Arguments: msg {str} -- message to generate Keyword Arguments: tag {str} -- tag to denote type of message (default: {'STARTUP'}) pre {str} -- token to generate before message (default: {'\n'}) post {str} -- token to generate after message (default: {'\n'})
gkit_utils/message_generator.py
generate_startup
gannon93/gkit_utils
0
python
def generate_startup(msg, tags=['STARTUP'], pre=, post=, **kwargs): "Generate a success message.\n\n Method generates a success message.\n\n Arguments:\n msg {str} -- message to generate\n\n Keyword Arguments:\n tag {str} -- tag to denote type of message\n (default: {'STARTUP'})\n pre {str} -- token to generate before message\n (default: {'\\n'})\n post {str} -- token to generate after message\n (default: {'\\n'})\n " return _generate(msg=msg, tags=tags, pre=pre, post=post, **kwargs)
def generate_startup(msg, tags=['STARTUP'], pre=, post=, **kwargs): "Generate a success message.\n\n Method generates a success message.\n\n Arguments:\n msg {str} -- message to generate\n\n Keyword Arguments:\n tag {str} -- tag to denote type of message\n (default: {'STARTUP'})\n pre {str} -- token to generate before message\n (default: {'\\n'})\n post {str} -- token to generate after message\n (default: {'\\n'})\n " return _generate(msg=msg, tags=tags, pre=pre, post=post, **kwargs)<|docstring|>Generate a success message. Method generates a success message. Arguments: msg {str} -- message to generate Keyword Arguments: tag {str} -- tag to denote type of message (default: {'STARTUP'}) pre {str} -- token to generate before message (default: {'\n'}) post {str} -- token to generate after message (default: {'\n'})<|endoftext|>
f871f3a01d536ef163173da7d31ad0de16e66a79b7b4bbb391621c683478b281
def generate_message(msg, tags=[], pre='', post='', **kwargs): "Generate a generic message.\n\n Method generates a generic message.\n\n Arguments:\n msg {str} -- message to generate\n\n Keyword Arguments:\n tag {str} -- tag to denote type of message\n (default: {''})\n pre {str} -- token to generate before message\n (default: {'\\n'})\n post {str} -- token to generate after message\n (default: {'\\n'})\n " return _generate(msg=msg, tags=tags, pre=pre, post=post, **kwargs)
Generate a generic message. Method generates a generic message. Arguments: msg {str} -- message to generate Keyword Arguments: tag {str} -- tag to denote type of message (default: {''}) pre {str} -- token to generate before message (default: {'\n'}) post {str} -- token to generate after message (default: {'\n'})
gkit_utils/message_generator.py
generate_message
gannon93/gkit_utils
0
python
def generate_message(msg, tags=[], pre=, post=, **kwargs): "Generate a generic message.\n\n Method generates a generic message.\n\n Arguments:\n msg {str} -- message to generate\n\n Keyword Arguments:\n tag {str} -- tag to denote type of message\n (default: {})\n pre {str} -- token to generate before message\n (default: {'\\n'})\n post {str} -- token to generate after message\n (default: {'\\n'})\n " return _generate(msg=msg, tags=tags, pre=pre, post=post, **kwargs)
def generate_message(msg, tags=[], pre=, post=, **kwargs): "Generate a generic message.\n\n Method generates a generic message.\n\n Arguments:\n msg {str} -- message to generate\n\n Keyword Arguments:\n tag {str} -- tag to denote type of message\n (default: {})\n pre {str} -- token to generate before message\n (default: {'\\n'})\n post {str} -- token to generate after message\n (default: {'\\n'})\n " return _generate(msg=msg, tags=tags, pre=pre, post=post, **kwargs)<|docstring|>Generate a generic message. Method generates a generic message. Arguments: msg {str} -- message to generate Keyword Arguments: tag {str} -- tag to denote type of message (default: {''}) pre {str} -- token to generate before message (default: {'\n'}) post {str} -- token to generate after message (default: {'\n'})<|endoftext|>
527ed02fa5ef478de3e2587a6501c859e0815a8cb82a4e6834b9b77e95ccaddb
def generate_tag_head(msgs, sep=': ', pre='[', post=']'): "Generate a tag head string.\n\n Method formats a tag string as a header.\n\n Arguments:\n msg {str} -- tag to format\n\n Keyword Arguments:\n sep {str} -- separator token for tag and rest of message\n (default: {':'})\n pre {str} -- left bounding token for tag item\n (default: {'['})\n post {str} -- right bounding token for tag item\n (default: {']'})\n " if isinstance(msgs, str): msgs = [msgs] tags = [generate_tag_string(msg, pre, post) for msg in msgs] return ((''.join(tags) + str(sep)) if len(tags) else '')
Generate a tag head string. Method formats a tag string as a header. Arguments: msg {str} -- tag to format Keyword Arguments: sep {str} -- separator token for tag and rest of message (default: {':'}) pre {str} -- left bounding token for tag item (default: {'['}) post {str} -- right bounding token for tag item (default: {']'})
gkit_utils/message_generator.py
generate_tag_head
gannon93/gkit_utils
0
python
def generate_tag_head(msgs, sep=': ', pre='[', post=']'): "Generate a tag head string.\n\n Method formats a tag string as a header.\n\n Arguments:\n msg {str} -- tag to format\n\n Keyword Arguments:\n sep {str} -- separator token for tag and rest of message\n (default: {':'})\n pre {str} -- left bounding token for tag item\n (default: {'['})\n post {str} -- right bounding token for tag item\n (default: {']'})\n " if isinstance(msgs, str): msgs = [msgs] tags = [generate_tag_string(msg, pre, post) for msg in msgs] return ((.join(tags) + str(sep)) if len(tags) else )
def generate_tag_head(msgs, sep=': ', pre='[', post=']'): "Generate a tag head string.\n\n Method formats a tag string as a header.\n\n Arguments:\n msg {str} -- tag to format\n\n Keyword Arguments:\n sep {str} -- separator token for tag and rest of message\n (default: {':'})\n pre {str} -- left bounding token for tag item\n (default: {'['})\n post {str} -- right bounding token for tag item\n (default: {']'})\n " if isinstance(msgs, str): msgs = [msgs] tags = [generate_tag_string(msg, pre, post) for msg in msgs] return ((.join(tags) + str(sep)) if len(tags) else )<|docstring|>Generate a tag head string. Method formats a tag string as a header. Arguments: msg {str} -- tag to format Keyword Arguments: sep {str} -- separator token for tag and rest of message (default: {':'}) pre {str} -- left bounding token for tag item (default: {'['}) post {str} -- right bounding token for tag item (default: {']'})<|endoftext|>
09a1e0f8ce529ba5d121da2258292f4ca9d1ed6405286db8f10e9df6f07dc4fa
def generate_tag_string(msg, pre='[', post=']'): "Generate a tag string.\n\n Method formats a tag string.\n\n Arguments:\n msg {str} -- tag to format\n\n Keyword Arguments:\n pre {str} -- left bounding token for tag item\n (default: {'['})\n post {str} -- right bounding token for tag item\n (default: {']'})\n " return ((str(pre) + str(msg)) + str(post))
Generate a tag string. Method formats a tag string. Arguments: msg {str} -- tag to format Keyword Arguments: pre {str} -- left bounding token for tag item (default: {'['}) post {str} -- right bounding token for tag item (default: {']'})
gkit_utils/message_generator.py
generate_tag_string
gannon93/gkit_utils
0
python
def generate_tag_string(msg, pre='[', post=']'): "Generate a tag string.\n\n Method formats a tag string.\n\n Arguments:\n msg {str} -- tag to format\n\n Keyword Arguments:\n pre {str} -- left bounding token for tag item\n (default: {'['})\n post {str} -- right bounding token for tag item\n (default: {']'})\n " return ((str(pre) + str(msg)) + str(post))
def generate_tag_string(msg, pre='[', post=']'): "Generate a tag string.\n\n Method formats a tag string.\n\n Arguments:\n msg {str} -- tag to format\n\n Keyword Arguments:\n pre {str} -- left bounding token for tag item\n (default: {'['})\n post {str} -- right bounding token for tag item\n (default: {']'})\n " return ((str(pre) + str(msg)) + str(post))<|docstring|>Generate a tag string. Method formats a tag string. Arguments: msg {str} -- tag to format Keyword Arguments: pre {str} -- left bounding token for tag item (default: {'['}) post {str} -- right bounding token for tag item (default: {']'})<|endoftext|>
b50d4982b284904bb85fe3566978513a53f1df31d26d40985140a0aaf8c75e56
def addInputsResearchObject(crate, inputs): "\n Add the input's provenance data to a Research Object.\n\n :param crate: Research Object\n :type crate: ROCrate object\n :param inputs: List of inputs to add\n :type inputs: Sequence[MaterializedInput]\n " for in_item in inputs: if isinstance(in_item, MaterializedInput): itemInValues = in_item.values[0] if isinstance(itemInValues, MaterializedContent): itemInLocalSource = itemInValues.local itemInURISource = itemInValues.licensed_uri.uri if os.path.isfile(itemInLocalSource): properties = {'name': in_item.name} crate.add_file(source=itemInURISource, fetch_remote=False, validate_url=False, properties=properties) elif os.path.isdir(itemInLocalSource): errmsg = 'FIXME: input directory / dataset handling in RO-Crate' logger.error(errmsg) else: pass
Add the input's provenance data to a Research Object. :param crate: Research Object :type crate: ROCrate object :param inputs: List of inputs to add :type inputs: Sequence[MaterializedInput]
wfexs_backend/ro_crate.py
addInputsResearchObject
inab/WES-backend
0
python
def addInputsResearchObject(crate, inputs): "\n Add the input's provenance data to a Research Object.\n\n :param crate: Research Object\n :type crate: ROCrate object\n :param inputs: List of inputs to add\n :type inputs: Sequence[MaterializedInput]\n " for in_item in inputs: if isinstance(in_item, MaterializedInput): itemInValues = in_item.values[0] if isinstance(itemInValues, MaterializedContent): itemInLocalSource = itemInValues.local itemInURISource = itemInValues.licensed_uri.uri if os.path.isfile(itemInLocalSource): properties = {'name': in_item.name} crate.add_file(source=itemInURISource, fetch_remote=False, validate_url=False, properties=properties) elif os.path.isdir(itemInLocalSource): errmsg = 'FIXME: input directory / dataset handling in RO-Crate' logger.error(errmsg) else: pass
def addInputsResearchObject(crate, inputs): "\n Add the input's provenance data to a Research Object.\n\n :param crate: Research Object\n :type crate: ROCrate object\n :param inputs: List of inputs to add\n :type inputs: Sequence[MaterializedInput]\n " for in_item in inputs: if isinstance(in_item, MaterializedInput): itemInValues = in_item.values[0] if isinstance(itemInValues, MaterializedContent): itemInLocalSource = itemInValues.local itemInURISource = itemInValues.licensed_uri.uri if os.path.isfile(itemInLocalSource): properties = {'name': in_item.name} crate.add_file(source=itemInURISource, fetch_remote=False, validate_url=False, properties=properties) elif os.path.isdir(itemInLocalSource): errmsg = 'FIXME: input directory / dataset handling in RO-Crate' logger.error(errmsg) else: pass<|docstring|>Add the input's provenance data to a Research Object. :param crate: Research Object :type crate: ROCrate object :param inputs: List of inputs to add :type inputs: Sequence[MaterializedInput]<|endoftext|>
5886f246b5a3aeb3971a4a28106ad19661d0c8385c2138b224849d7dfe8802c3
def addOutputsResearchObject(crate, outputs): "\n Add the output's provenance data to a Research Object.\n\n :param crate: Research Object\n :type crate: ROCrate object\n :param outputs: List of outputs to add\n :type outputs: Sequence[MaterializedOutput]\n " for out_item in outputs: if isinstance(out_item, MaterializedOutput): itemOutValues = out_item.values[0] assert isinstance(itemOutValues, (GeneratedContent, GeneratedDirectoryContent)) itemOutSource = itemOutValues.local itemOutName = out_item.name properties = {'name': itemOutName} if isinstance(itemOutValues, GeneratedDirectoryContent): if os.path.isdir(itemOutSource): generatedDirectoryContentURI = ComputeDigestFromDirectory(itemOutSource, repMethod=nihDigester) dirProperties = dict.fromkeys(['hasPart']) generatedContentList = [] generatedDirectoryContentList = [] for item in itemOutValues.values: if isinstance(item, GeneratedContent): fileID = item.signature if (fileID is None): fileID = ComputeDigestFromFile(item.local, repMethod=nihDigester) fileProperties = {'name': ((itemOutName + '::/') + os.path.basename(item.local)), 'isPartOf': {'@id': generatedDirectoryContentURI}} generatedContentList.append({'@id': fileID}) crate.add_file(source=fileID, fetch_remote=False, properties=fileProperties) elif isinstance(item, GeneratedDirectoryContent): def search_new_content(content_list): tempList = [] for content in content_list: if isinstance(content, GeneratedContent): fileID = content.signature if (fileID is None): fileID = ComputeDigestFromFile(content.local, repMethod=nihDigester) fileProperties = {'name': ((itemOutName + '::/') + os.path.basename(content.local)), 'isPartOf': {'@id': generatedDirectoryContentURI}} tempList.append({'@id': fileID}) crate.add_file(source=fileID, fetch_remote=False, properties=fileProperties) if isinstance(content, GeneratedDirectoryContent): tempList.extend(search_new_content(content.values)) return tempList generatedDirectoryContentList.append(search_new_content(item.values)) else: pass dirProperties['hasPart'] = (sum(generatedDirectoryContentList, []) + generatedContentList) properties.update(dirProperties) crate.add_directory(source=generatedDirectoryContentURI, fetch_remote=False, properties=properties) else: errmsg = ('ERROR: The output directory %s does not exist' % itemOutSource) logger.error(errmsg) elif isinstance(itemOutValues, GeneratedContent): if os.path.isfile(itemOutSource): fileID = itemOutValues.signature if (fileID is None): fileID = ComputeDigestFromFile(itemOutSource, repMethod=nihDigester) crate.add_file(source=fileID, fetch_remote=False, properties=properties) else: errmsg = ('ERROR: The output file %s does not exist' % itemOutSource) logger.error(errmsg) else: pass
Add the output's provenance data to a Research Object. :param crate: Research Object :type crate: ROCrate object :param outputs: List of outputs to add :type outputs: Sequence[MaterializedOutput]
wfexs_backend/ro_crate.py
addOutputsResearchObject
inab/WES-backend
0
python
def addOutputsResearchObject(crate, outputs): "\n Add the output's provenance data to a Research Object.\n\n :param crate: Research Object\n :type crate: ROCrate object\n :param outputs: List of outputs to add\n :type outputs: Sequence[MaterializedOutput]\n " for out_item in outputs: if isinstance(out_item, MaterializedOutput): itemOutValues = out_item.values[0] assert isinstance(itemOutValues, (GeneratedContent, GeneratedDirectoryContent)) itemOutSource = itemOutValues.local itemOutName = out_item.name properties = {'name': itemOutName} if isinstance(itemOutValues, GeneratedDirectoryContent): if os.path.isdir(itemOutSource): generatedDirectoryContentURI = ComputeDigestFromDirectory(itemOutSource, repMethod=nihDigester) dirProperties = dict.fromkeys(['hasPart']) generatedContentList = [] generatedDirectoryContentList = [] for item in itemOutValues.values: if isinstance(item, GeneratedContent): fileID = item.signature if (fileID is None): fileID = ComputeDigestFromFile(item.local, repMethod=nihDigester) fileProperties = {'name': ((itemOutName + '::/') + os.path.basename(item.local)), 'isPartOf': {'@id': generatedDirectoryContentURI}} generatedContentList.append({'@id': fileID}) crate.add_file(source=fileID, fetch_remote=False, properties=fileProperties) elif isinstance(item, GeneratedDirectoryContent): def search_new_content(content_list): tempList = [] for content in content_list: if isinstance(content, GeneratedContent): fileID = content.signature if (fileID is None): fileID = ComputeDigestFromFile(content.local, repMethod=nihDigester) fileProperties = {'name': ((itemOutName + '::/') + os.path.basename(content.local)), 'isPartOf': {'@id': generatedDirectoryContentURI}} tempList.append({'@id': fileID}) crate.add_file(source=fileID, fetch_remote=False, properties=fileProperties) if isinstance(content, GeneratedDirectoryContent): tempList.extend(search_new_content(content.values)) return tempList generatedDirectoryContentList.append(search_new_content(item.values)) else: pass dirProperties['hasPart'] = (sum(generatedDirectoryContentList, []) + generatedContentList) properties.update(dirProperties) crate.add_directory(source=generatedDirectoryContentURI, fetch_remote=False, properties=properties) else: errmsg = ('ERROR: The output directory %s does not exist' % itemOutSource) logger.error(errmsg) elif isinstance(itemOutValues, GeneratedContent): if os.path.isfile(itemOutSource): fileID = itemOutValues.signature if (fileID is None): fileID = ComputeDigestFromFile(itemOutSource, repMethod=nihDigester) crate.add_file(source=fileID, fetch_remote=False, properties=properties) else: errmsg = ('ERROR: The output file %s does not exist' % itemOutSource) logger.error(errmsg) else: pass
def addOutputsResearchObject(crate, outputs): "\n Add the output's provenance data to a Research Object.\n\n :param crate: Research Object\n :type crate: ROCrate object\n :param outputs: List of outputs to add\n :type outputs: Sequence[MaterializedOutput]\n " for out_item in outputs: if isinstance(out_item, MaterializedOutput): itemOutValues = out_item.values[0] assert isinstance(itemOutValues, (GeneratedContent, GeneratedDirectoryContent)) itemOutSource = itemOutValues.local itemOutName = out_item.name properties = {'name': itemOutName} if isinstance(itemOutValues, GeneratedDirectoryContent): if os.path.isdir(itemOutSource): generatedDirectoryContentURI = ComputeDigestFromDirectory(itemOutSource, repMethod=nihDigester) dirProperties = dict.fromkeys(['hasPart']) generatedContentList = [] generatedDirectoryContentList = [] for item in itemOutValues.values: if isinstance(item, GeneratedContent): fileID = item.signature if (fileID is None): fileID = ComputeDigestFromFile(item.local, repMethod=nihDigester) fileProperties = {'name': ((itemOutName + '::/') + os.path.basename(item.local)), 'isPartOf': {'@id': generatedDirectoryContentURI}} generatedContentList.append({'@id': fileID}) crate.add_file(source=fileID, fetch_remote=False, properties=fileProperties) elif isinstance(item, GeneratedDirectoryContent): def search_new_content(content_list): tempList = [] for content in content_list: if isinstance(content, GeneratedContent): fileID = content.signature if (fileID is None): fileID = ComputeDigestFromFile(content.local, repMethod=nihDigester) fileProperties = {'name': ((itemOutName + '::/') + os.path.basename(content.local)), 'isPartOf': {'@id': generatedDirectoryContentURI}} tempList.append({'@id': fileID}) crate.add_file(source=fileID, fetch_remote=False, properties=fileProperties) if isinstance(content, GeneratedDirectoryContent): tempList.extend(search_new_content(content.values)) return tempList generatedDirectoryContentList.append(search_new_content(item.values)) else: pass dirProperties['hasPart'] = (sum(generatedDirectoryContentList, []) + generatedContentList) properties.update(dirProperties) crate.add_directory(source=generatedDirectoryContentURI, fetch_remote=False, properties=properties) else: errmsg = ('ERROR: The output directory %s does not exist' % itemOutSource) logger.error(errmsg) elif isinstance(itemOutValues, GeneratedContent): if os.path.isfile(itemOutSource): fileID = itemOutValues.signature if (fileID is None): fileID = ComputeDigestFromFile(itemOutSource, repMethod=nihDigester) crate.add_file(source=fileID, fetch_remote=False, properties=properties) else: errmsg = ('ERROR: The output file %s does not exist' % itemOutSource) logger.error(errmsg) else: pass<|docstring|>Add the output's provenance data to a Research Object. :param crate: Research Object :type crate: ROCrate object :param outputs: List of outputs to add :type outputs: Sequence[MaterializedOutput]<|endoftext|>
eedeaba10005c4887b684da8805030f25ee7c1952a43adedf112d7de05015196
@contextmanager def working_directory(path): '\n Temporarily change the current working directory.\n\n Usage:\n with working_directory(path):\n do_things() # working in the given path\n do_other_things() # back to original path\n ' current_directory = os.getcwd() os.chdir(path) try: (yield) finally: os.chdir(current_directory)
Temporarily change the current working directory. Usage: with working_directory(path): do_things() # working in the given path do_other_things() # back to original path
pretext/utils.py
working_directory
StevenClontz/ptxtikzjaxtest
0
python
@contextmanager def working_directory(path): '\n Temporarily change the current working directory.\n\n Usage:\n with working_directory(path):\n do_things() # working in the given path\n do_other_things() # back to original path\n ' current_directory = os.getcwd() os.chdir(path) try: (yield) finally: os.chdir(current_directory)
@contextmanager def working_directory(path): '\n Temporarily change the current working directory.\n\n Usage:\n with working_directory(path):\n do_things() # working in the given path\n do_other_things() # back to original path\n ' current_directory = os.getcwd() os.chdir(path) try: (yield) finally: os.chdir(current_directory)<|docstring|>Temporarily change the current working directory. Usage: with working_directory(path): do_things() # working in the given path do_other_things() # back to original path<|endoftext|>
c58679ae923700d414dfda684eb8352adbd1f2e7ddcc9b4da735b1470ac65301
def ensure_directory(path): "\n If the directory doesn't exist yet, create it.\n " try: os.makedirs(path) except FileExistsError: pass
If the directory doesn't exist yet, create it.
pretext/utils.py
ensure_directory
StevenClontz/ptxtikzjaxtest
0
python
def ensure_directory(path): "\n \n " try: os.makedirs(path) except FileExistsError: pass
def ensure_directory(path): "\n \n " try: os.makedirs(path) except FileExistsError: pass<|docstring|>If the directory doesn't exist yet, create it.<|endoftext|>
aaf7c43dbbf316522829b1cb243cebef35fae7aa5106e4c8222351a0ee23854d
def directory_exists(path): '\n Checks if the directory exists.\n ' return os.path.exists(path)
Checks if the directory exists.
pretext/utils.py
directory_exists
StevenClontz/ptxtikzjaxtest
0
python
def directory_exists(path): '\n \n ' return os.path.exists(path)
def directory_exists(path): '\n \n ' return os.path.exists(path)<|docstring|>Checks if the directory exists.<|endoftext|>
569a4f9a44c357a206c825e0516b7b4c465c29c5dd7af05132667a07bdb799ac
def warn_ignore(*args, **kwargs): 'Function used to ignore all warnings' pass
Function used to ignore all warnings
bananas/utils/misc.py
warn_ignore
owahltinez/bananas
0
python
def warn_ignore(*args, **kwargs): pass
def warn_ignore(*args, **kwargs): pass<|docstring|>Function used to ignore all warnings<|endoftext|>
186375ac7e0ab250a73e60ef4d7abf7112cad4ddd69f582525151bbdf8b357eb
def warn_with_traceback(message, category, filename, lineno, file=None, line=None): 'Function used to print callstack of warnings' log = (file if hasattr(file, 'write') else sys.stderr) traceback.print_stack(file=log) log.write(warnings.formatwarning(message, category, filename, lineno, line))
Function used to print callstack of warnings
bananas/utils/misc.py
warn_with_traceback
owahltinez/bananas
0
python
def warn_with_traceback(message, category, filename, lineno, file=None, line=None): log = (file if hasattr(file, 'write') else sys.stderr) traceback.print_stack(file=log) log.write(warnings.formatwarning(message, category, filename, lineno, line))
def warn_with_traceback(message, category, filename, lineno, file=None, line=None): log = (file if hasattr(file, 'write') else sys.stderr) traceback.print_stack(file=log) log.write(warnings.formatwarning(message, category, filename, lineno, line))<|docstring|>Function used to print callstack of warnings<|endoftext|>
459f05f7a491eeef89abc60e957c033938174bb8112559a5b9c9ac206ebcb745
def valid_parameters(func: Callable, params: Dict[(str, Any)]): ' Returns the subset of `params` that can be applied to `func` ' func_params = signature(func).parameters if ('kwargs' in func_params): return params return {key: val for (key, val) in params.items() if (key in func_params)}
Returns the subset of `params` that can be applied to `func`
bananas/utils/misc.py
valid_parameters
owahltinez/bananas
0
python
def valid_parameters(func: Callable, params: Dict[(str, Any)]): ' ' func_params = signature(func).parameters if ('kwargs' in func_params): return params return {key: val for (key, val) in params.items() if (key in func_params)}
def valid_parameters(func: Callable, params: Dict[(str, Any)]): ' ' func_params = signature(func).parameters if ('kwargs' in func_params): return params return {key: val for (key, val) in params.items() if (key in func_params)}<|docstring|>Returns the subset of `params` that can be applied to `func`<|endoftext|>
0991c8395594471805c8a066eef48481c81c33f55a2bde9d0059e2b2f1d04163
def stream_data(self): 'Reads the raw red, green, blue and clear channel values' color = {} colors = self.tcs.getRawDataList() return colors
Reads the raw red, green, blue and clear channel values
src/main/python/raspberrypidrivers/SensorReader.py
stream_data
bu-vip/UROP_SinglePixelLocalization
2
python
def stream_data(self): color = {} colors = self.tcs.getRawDataList() return colors
def stream_data(self): color = {} colors = self.tcs.getRawDataList() return colors<|docstring|>Reads the raw red, green, blue and clear channel values<|endoftext|>
dad76b9eaddaa4b68d457f1774df1fac63d4d39576fc74becd702f773c904955
def _normalize_reading(self, value): 'Normalizes a sensor value to range [0, 1]' return (value / float(self.max_sensor_val))
Normalizes a sensor value to range [0, 1]
src/main/python/raspberrypidrivers/SensorReader.py
_normalize_reading
bu-vip/UROP_SinglePixelLocalization
2
python
def _normalize_reading(self, value): return (value / float(self.max_sensor_val))
def _normalize_reading(self, value): return (value / float(self.max_sensor_val))<|docstring|>Normalizes a sensor value to range [0, 1]<|endoftext|>
2737dfdac78ce186ecacb04e445bdf2f05f21b3b9691f389038989c78bde2cbb
def read_sensors(self): "Reads sensor data. Returns a list of lists of sensor readings. Empty lists / readings mean there aren't \n any sensors or multiplexers for that index. " data = [] for u in range(0, 8): mux = self.muxes[u] mux_data = [] data.append(mux_data) if ((mux != '--') and self.mux_present[u]): mux = ('0x' + mux) mux = int(mux, 16) x2 = 1 for s2 in range(0, 8): sensor_data = None self.bus.write_byte_data(mux, SensorReader.DEVICE_REG_MODE1, x2) if self.sensor_present[u][s2]: rgb = self.stream_data() sensor_data = singlepixel_pb2.SinglePixelSensorReading() sensor_data.red = self._normalize_reading(rgb['r']) sensor_data.green = self._normalize_reading(rgb['g']) sensor_data.blue = self._normalize_reading(rgb['b']) sensor_data.clear = self._normalize_reading(rgb['c']) sensor_data.ntp_capture_time.GetCurrentTime() x2 = (x2 * 2) mux_data.append(sensor_data) self.bus.write_byte_data(mux, SensorReader.DEVICE_REG_MODE1, 0) return data
Reads sensor data. Returns a list of lists of sensor readings. Empty lists / readings mean there aren't any sensors or multiplexers for that index.
src/main/python/raspberrypidrivers/SensorReader.py
read_sensors
bu-vip/UROP_SinglePixelLocalization
2
python
def read_sensors(self): "Reads sensor data. Returns a list of lists of sensor readings. Empty lists / readings mean there aren't \n any sensors or multiplexers for that index. " data = [] for u in range(0, 8): mux = self.muxes[u] mux_data = [] data.append(mux_data) if ((mux != '--') and self.mux_present[u]): mux = ('0x' + mux) mux = int(mux, 16) x2 = 1 for s2 in range(0, 8): sensor_data = None self.bus.write_byte_data(mux, SensorReader.DEVICE_REG_MODE1, x2) if self.sensor_present[u][s2]: rgb = self.stream_data() sensor_data = singlepixel_pb2.SinglePixelSensorReading() sensor_data.red = self._normalize_reading(rgb['r']) sensor_data.green = self._normalize_reading(rgb['g']) sensor_data.blue = self._normalize_reading(rgb['b']) sensor_data.clear = self._normalize_reading(rgb['c']) sensor_data.ntp_capture_time.GetCurrentTime() x2 = (x2 * 2) mux_data.append(sensor_data) self.bus.write_byte_data(mux, SensorReader.DEVICE_REG_MODE1, 0) return data
def read_sensors(self): "Reads sensor data. Returns a list of lists of sensor readings. Empty lists / readings mean there aren't \n any sensors or multiplexers for that index. " data = [] for u in range(0, 8): mux = self.muxes[u] mux_data = [] data.append(mux_data) if ((mux != '--') and self.mux_present[u]): mux = ('0x' + mux) mux = int(mux, 16) x2 = 1 for s2 in range(0, 8): sensor_data = None self.bus.write_byte_data(mux, SensorReader.DEVICE_REG_MODE1, x2) if self.sensor_present[u][s2]: rgb = self.stream_data() sensor_data = singlepixel_pb2.SinglePixelSensorReading() sensor_data.red = self._normalize_reading(rgb['r']) sensor_data.green = self._normalize_reading(rgb['g']) sensor_data.blue = self._normalize_reading(rgb['b']) sensor_data.clear = self._normalize_reading(rgb['c']) sensor_data.ntp_capture_time.GetCurrentTime() x2 = (x2 * 2) mux_data.append(sensor_data) self.bus.write_byte_data(mux, SensorReader.DEVICE_REG_MODE1, 0) return data<|docstring|>Reads sensor data. Returns a list of lists of sensor readings. Empty lists / readings mean there aren't any sensors or multiplexers for that index.<|endoftext|>
e8052b9d6af67071d38492ed422e40dfb0c1c8186a73a209788eb7a6dd15ca30
def __init__(self, graph_conv, attn=None, mlp=None, symmetric=None): 'Initializes the graph convolution predictor.\n\n Args:\n graph_conv: The graph convolution network required to obtain\n molecule feature representation.\n mlp: Multi layer perceptron; used as the final fully connected\n layer. Set it to `None` if no operation is necessary\n after the `graph_conv` calculation.\n ' super(GraphConvPredictorForPair, self).__init__() with self.init_scope(): self.graph_conv = graph_conv if isinstance(mlp, chainer.Link): self.mlp = mlp if isinstance(attn, chainer.Link): self.attn = attn if (not isinstance(mlp, chainer.Link)): self.mlp = mlp if (not isinstance(attn, chainer.Link)): self.attn = attn self.symmetric = symmetric
Initializes the graph convolution predictor. Args: graph_conv: The graph convolution network required to obtain molecule feature representation. mlp: Multi layer perceptron; used as the final fully connected layer. Set it to `None` if no operation is necessary after the `graph_conv` calculation.
train_binary.py
__init__
Minys233/GCN-BMP
0
python
def __init__(self, graph_conv, attn=None, mlp=None, symmetric=None): 'Initializes the graph convolution predictor.\n\n Args:\n graph_conv: The graph convolution network required to obtain\n molecule feature representation.\n mlp: Multi layer perceptron; used as the final fully connected\n layer. Set it to `None` if no operation is necessary\n after the `graph_conv` calculation.\n ' super(GraphConvPredictorForPair, self).__init__() with self.init_scope(): self.graph_conv = graph_conv if isinstance(mlp, chainer.Link): self.mlp = mlp if isinstance(attn, chainer.Link): self.attn = attn if (not isinstance(mlp, chainer.Link)): self.mlp = mlp if (not isinstance(attn, chainer.Link)): self.attn = attn self.symmetric = symmetric
def __init__(self, graph_conv, attn=None, mlp=None, symmetric=None): 'Initializes the graph convolution predictor.\n\n Args:\n graph_conv: The graph convolution network required to obtain\n molecule feature representation.\n mlp: Multi layer perceptron; used as the final fully connected\n layer. Set it to `None` if no operation is necessary\n after the `graph_conv` calculation.\n ' super(GraphConvPredictorForPair, self).__init__() with self.init_scope(): self.graph_conv = graph_conv if isinstance(mlp, chainer.Link): self.mlp = mlp if isinstance(attn, chainer.Link): self.attn = attn if (not isinstance(mlp, chainer.Link)): self.mlp = mlp if (not isinstance(attn, chainer.Link)): self.attn = attn self.symmetric = symmetric<|docstring|>Initializes the graph convolution predictor. Args: graph_conv: The graph convolution network required to obtain molecule feature representation. mlp: Multi layer perceptron; used as the final fully connected layer. Set it to `None` if no operation is necessary after the `graph_conv` calculation.<|endoftext|>
6647ad6ecbab9ae59d88bc621bfd394b66b5020552cffb72bfafd887fb848174
def initialize(): '\n Loads model parameters into cuda.\n\n Returns\n -------\n model : object\n The convolutional neural network to be trained.\n ' model = Dexpression() model = model.to(device) return model
Loads model parameters into cuda. Returns ------- model : object The convolutional neural network to be trained.
dexpression_pytorch/pipelines/network.py
initialize
rdgozum/dexpression-pytorch
4
python
def initialize(): '\n Loads model parameters into cuda.\n\n Returns\n -------\n model : object\n The convolutional neural network to be trained.\n ' model = Dexpression() model = model.to(device) return model
def initialize(): '\n Loads model parameters into cuda.\n\n Returns\n -------\n model : object\n The convolutional neural network to be trained.\n ' model = Dexpression() model = model.to(device) return model<|docstring|>Loads model parameters into cuda. Returns ------- model : object The convolutional neural network to be trained.<|endoftext|>
7e69315de7451ce72b28b260b6843d264244664d6eb3b85958f257fb45b1398e
def process(self, instance): "Process all the nodes in the instance 'objectSet'" invalid = self.get_invalid(instance) if invalid: raise ValueError('Meshes found with face that is more than 4 sides: {0}'.format(invalid))
Process all the nodes in the instance 'objectSet'
plugins/maya/publish/validate_mesh_no_more_than_4_sides.py
process
davidlatwe/reveries-config
3
python
def process(self, instance): invalid = self.get_invalid(instance) if invalid: raise ValueError('Meshes found with face that is more than 4 sides: {0}'.format(invalid))
def process(self, instance): invalid = self.get_invalid(instance) if invalid: raise ValueError('Meshes found with face that is more than 4 sides: {0}'.format(invalid))<|docstring|>Process all the nodes in the instance 'objectSet'<|endoftext|>
e49fa23cbfc66b46c508301660e69982168dd61d7962a85088a5b7d7e873c73f
def __init__(self, *, host: str=DEFAULT_HOST, credentials: ga_credentials.Credentials=None, credentials_file: Optional[str]=None, scopes: Optional[Sequence[str]]=None, quota_project_id: Optional[str]=None, client_info: gapic_v1.client_info.ClientInfo=DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool]=False, **kwargs) -> None: "Instantiate the transport.\n\n Args:\n host (Optional[str]):\n The hostname to connect to.\n credentials (Optional[google.auth.credentials.Credentials]): The\n authorization credentials to attach to requests. These\n credentials identify the application to the service; if none\n are specified, the client will attempt to ascertain the\n credentials from the environment.\n credentials_file (Optional[str]): A file with credentials that can\n be loaded with :func:`google.auth.load_credentials_from_file`.\n This argument is mutually exclusive with credentials.\n scopes (Optional[Sequence[str]]): A list of scopes.\n quota_project_id (Optional[str]): An optional project to use for billing\n and quota.\n client_info (google.api_core.gapic_v1.client_info.ClientInfo):\n The client info used to send a user-agent string along with\n API requests. If ``None``, then default info will be used.\n Generally, you only need to set this if you're developing\n your own client library.\n always_use_jwt_access (Optional[bool]): Whether self signed JWT should\n be used for service account credentials.\n " if (':' not in host): host += ':443' self._host = host scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) self._scopes = scopes if (credentials and credentials_file): raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") if (credentials_file is not None): (credentials, _) = google.auth.load_credentials_from_file(credentials_file, **scopes_kwargs, quota_project_id=quota_project_id) elif (credentials is None): (credentials, _) = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) if (always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, 'with_always_use_jwt_access')): credentials = credentials.with_always_use_jwt_access(True) self._credentials = credentials
Instantiate the transport. Args: host (Optional[str]): The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. always_use_jwt_access (Optional[bool]): Whether self signed JWT should be used for service account credentials.
google/cloud/dialogflow_v2/services/agents/transports/base.py
__init__
galz10/python-dialogflow
80
python
def __init__(self, *, host: str=DEFAULT_HOST, credentials: ga_credentials.Credentials=None, credentials_file: Optional[str]=None, scopes: Optional[Sequence[str]]=None, quota_project_id: Optional[str]=None, client_info: gapic_v1.client_info.ClientInfo=DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool]=False, **kwargs) -> None: "Instantiate the transport.\n\n Args:\n host (Optional[str]):\n The hostname to connect to.\n credentials (Optional[google.auth.credentials.Credentials]): The\n authorization credentials to attach to requests. These\n credentials identify the application to the service; if none\n are specified, the client will attempt to ascertain the\n credentials from the environment.\n credentials_file (Optional[str]): A file with credentials that can\n be loaded with :func:`google.auth.load_credentials_from_file`.\n This argument is mutually exclusive with credentials.\n scopes (Optional[Sequence[str]]): A list of scopes.\n quota_project_id (Optional[str]): An optional project to use for billing\n and quota.\n client_info (google.api_core.gapic_v1.client_info.ClientInfo):\n The client info used to send a user-agent string along with\n API requests. If ``None``, then default info will be used.\n Generally, you only need to set this if you're developing\n your own client library.\n always_use_jwt_access (Optional[bool]): Whether self signed JWT should\n be used for service account credentials.\n " if (':' not in host): host += ':443' self._host = host scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) self._scopes = scopes if (credentials and credentials_file): raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") if (credentials_file is not None): (credentials, _) = google.auth.load_credentials_from_file(credentials_file, **scopes_kwargs, quota_project_id=quota_project_id) elif (credentials is None): (credentials, _) = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) if (always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, 'with_always_use_jwt_access')): credentials = credentials.with_always_use_jwt_access(True) self._credentials = credentials
def __init__(self, *, host: str=DEFAULT_HOST, credentials: ga_credentials.Credentials=None, credentials_file: Optional[str]=None, scopes: Optional[Sequence[str]]=None, quota_project_id: Optional[str]=None, client_info: gapic_v1.client_info.ClientInfo=DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool]=False, **kwargs) -> None: "Instantiate the transport.\n\n Args:\n host (Optional[str]):\n The hostname to connect to.\n credentials (Optional[google.auth.credentials.Credentials]): The\n authorization credentials to attach to requests. These\n credentials identify the application to the service; if none\n are specified, the client will attempt to ascertain the\n credentials from the environment.\n credentials_file (Optional[str]): A file with credentials that can\n be loaded with :func:`google.auth.load_credentials_from_file`.\n This argument is mutually exclusive with credentials.\n scopes (Optional[Sequence[str]]): A list of scopes.\n quota_project_id (Optional[str]): An optional project to use for billing\n and quota.\n client_info (google.api_core.gapic_v1.client_info.ClientInfo):\n The client info used to send a user-agent string along with\n API requests. If ``None``, then default info will be used.\n Generally, you only need to set this if you're developing\n your own client library.\n always_use_jwt_access (Optional[bool]): Whether self signed JWT should\n be used for service account credentials.\n " if (':' not in host): host += ':443' self._host = host scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) self._scopes = scopes if (credentials and credentials_file): raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") if (credentials_file is not None): (credentials, _) = google.auth.load_credentials_from_file(credentials_file, **scopes_kwargs, quota_project_id=quota_project_id) elif (credentials is None): (credentials, _) = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) if (always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, 'with_always_use_jwt_access')): credentials = credentials.with_always_use_jwt_access(True) self._credentials = credentials<|docstring|>Instantiate the transport. Args: host (Optional[str]): The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. scopes (Optional[Sequence[str]]): A list of scopes. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. always_use_jwt_access (Optional[bool]): Whether self signed JWT should be used for service account credentials.<|endoftext|>
330f4442de604aea7052c50b660d3278cc79e265ab8323aab6876e755fe82454
@classmethod def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[(str, Optional[Sequence[str]])]: 'Returns scopes kwargs to pass to google-auth methods depending on the google-auth version' scopes_kwargs = {} if (_GOOGLE_AUTH_VERSION and (packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse('1.25.0'))): scopes_kwargs = {'scopes': scopes, 'default_scopes': cls.AUTH_SCOPES} else: scopes_kwargs = {'scopes': (scopes or cls.AUTH_SCOPES)} return scopes_kwargs
Returns scopes kwargs to pass to google-auth methods depending on the google-auth version
google/cloud/dialogflow_v2/services/agents/transports/base.py
_get_scopes_kwargs
galz10/python-dialogflow
80
python
@classmethod def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[(str, Optional[Sequence[str]])]: scopes_kwargs = {} if (_GOOGLE_AUTH_VERSION and (packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse('1.25.0'))): scopes_kwargs = {'scopes': scopes, 'default_scopes': cls.AUTH_SCOPES} else: scopes_kwargs = {'scopes': (scopes or cls.AUTH_SCOPES)} return scopes_kwargs
@classmethod def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[(str, Optional[Sequence[str]])]: scopes_kwargs = {} if (_GOOGLE_AUTH_VERSION and (packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse('1.25.0'))): scopes_kwargs = {'scopes': scopes, 'default_scopes': cls.AUTH_SCOPES} else: scopes_kwargs = {'scopes': (scopes or cls.AUTH_SCOPES)} return scopes_kwargs<|docstring|>Returns scopes kwargs to pass to google-auth methods depending on the google-auth version<|endoftext|>
2403757566f62cddad81d30ea6aee2e4058c6d90797d7fa01d57f9e00a790dcf
def close(self): 'Closes resources associated with the transport.\n\n .. warning::\n Only call this method if the transport is NOT shared\n with other clients - this may cause errors in other clients!\n ' raise NotImplementedError()
Closes resources associated with the transport. .. warning:: Only call this method if the transport is NOT shared with other clients - this may cause errors in other clients!
google/cloud/dialogflow_v2/services/agents/transports/base.py
close
galz10/python-dialogflow
80
python
def close(self): 'Closes resources associated with the transport.\n\n .. warning::\n Only call this method if the transport is NOT shared\n with other clients - this may cause errors in other clients!\n ' raise NotImplementedError()
def close(self): 'Closes resources associated with the transport.\n\n .. warning::\n Only call this method if the transport is NOT shared\n with other clients - this may cause errors in other clients!\n ' raise NotImplementedError()<|docstring|>Closes resources associated with the transport. .. warning:: Only call this method if the transport is NOT shared with other clients - this may cause errors in other clients!<|endoftext|>
fe75c0714dfc16aa5208601be5a4f7ef8fa50bb985b9301d19fd9105054cc46b
@property def operations_client(self) -> operations_v1.OperationsClient: 'Return the client designed to process long-running operations.' raise NotImplementedError()
Return the client designed to process long-running operations.
google/cloud/dialogflow_v2/services/agents/transports/base.py
operations_client
galz10/python-dialogflow
80
python
@property def operations_client(self) -> operations_v1.OperationsClient: raise NotImplementedError()
@property def operations_client(self) -> operations_v1.OperationsClient: raise NotImplementedError()<|docstring|>Return the client designed to process long-running operations.<|endoftext|>
56c347526280d931ab01ee08c2afad88c4879b48a2ccb3f77a8fd01771a86793
def cli_main(): 'Main loop of program in basic CLI mode.\n\n Runs the game until exit requested.' signal.signal(signal.SIGINT, signal.default_int_handler) while True: try: game = Game() while (not game.round()): pass key = input('Press Enter to play again or q to exit. ') if ((key == 'q') or (key == 'Q')): exit_game() except KeyboardInterrupt: print() exit_game()
Main loop of program in basic CLI mode. Runs the game until exit requested.
beetle_gui.py
cli_main
PR3x/beetle
0
python
def cli_main(): 'Main loop of program in basic CLI mode.\n\n Runs the game until exit requested.' signal.signal(signal.SIGINT, signal.default_int_handler) while True: try: game = Game() while (not game.round()): pass key = input('Press Enter to play again or q to exit. ') if ((key == 'q') or (key == 'Q')): exit_game() except KeyboardInterrupt: print() exit_game()
def cli_main(): 'Main loop of program in basic CLI mode.\n\n Runs the game until exit requested.' signal.signal(signal.SIGINT, signal.default_int_handler) while True: try: game = Game() while (not game.round()): pass key = input('Press Enter to play again or q to exit. ') if ((key == 'q') or (key == 'Q')): exit_game() except KeyboardInterrupt: print() exit_game()<|docstring|>Main loop of program in basic CLI mode. Runs the game until exit requested.<|endoftext|>
f2f67a563e8be63682287b8e31c72ea1eefa9c34f43791d64921e61a050a0d6b
def exit_game(): 'Prints goodbye and quits the program' print('Goodbye.') sys.exit(0)
Prints goodbye and quits the program
beetle_gui.py
exit_game
PR3x/beetle
0
python
def exit_game(): print('Goodbye.') sys.exit(0)
def exit_game(): print('Goodbye.') sys.exit(0)<|docstring|>Prints goodbye and quits the program<|endoftext|>
50ac5380c33b4440a4f2bebf5a9bae457bc37a0ec338551a046ace0e30257b0b
def main(): 'Sets up and runs the Tk GUI' root = Tk() root.title('Beetle by Jacob Rigby') app = Application(parent=root) app.mainloop()
Sets up and runs the Tk GUI
beetle_gui.py
main
PR3x/beetle
0
python
def main(): root = Tk() root.title('Beetle by Jacob Rigby') app = Application(parent=root) app.mainloop()
def main(): root = Tk() root.title('Beetle by Jacob Rigby') app = Application(parent=root) app.mainloop()<|docstring|>Sets up and runs the Tk GUI<|endoftext|>
44a09e7690c0ab86434346634da967c284b4d9778cf791ad433b47214c436236
def __init__(self, num_sides=6): 'Default number of sides is 6' self.__num_sides = num_sides
Default number of sides is 6
beetle_gui.py
__init__
PR3x/beetle
0
python
def __init__(self, num_sides=6): self.__num_sides = num_sides
def __init__(self, num_sides=6): self.__num_sides = num_sides<|docstring|>Default number of sides is 6<|endoftext|>
8c7821ee6f0d9599bd6fd81a5cbce4b7ed9ee487763f98e9e5e912b459f2df1b
def roll(self) -> int: 'Generates a random number' return randint(1, self.__num_sides)
Generates a random number
beetle_gui.py
roll
PR3x/beetle
0
python
def roll(self) -> int: return randint(1, self.__num_sides)
def roll(self) -> int: return randint(1, self.__num_sides)<|docstring|>Generates a random number<|endoftext|>
62ba967f56136484f9045f8520de4b6637e9de73ee5326deebc2c70eb99a447c
def __init__(self, name=None): 'Creates a new gameboard for a player' self.name = name self._body = False self._head = False self._left_legs = False self._right_legs = False self._left_antenna = False self._right_antenna = False self._left_eye = False self._right_eye = False
Creates a new gameboard for a player
beetle_gui.py
__init__
PR3x/beetle
0
python
def __init__(self, name=None): self.name = name self._body = False self._head = False self._left_legs = False self._right_legs = False self._left_antenna = False self._right_antenna = False self._left_eye = False self._right_eye = False
def __init__(self, name=None): self.name = name self._body = False self._head = False self._left_legs = False self._right_legs = False self._left_antenna = False self._right_antenna = False self._left_eye = False self._right_eye = False<|docstring|>Creates a new gameboard for a player<|endoftext|>
c26f01b3b2ae4884a9dc22ba683095cc5a4227cc96f981886931ff58a88beb4c
def turn(self, roll) -> bool: 'Represents the act of taking a turn in the game.\n\n Moves forward a step in the state machine' if ((not self._body) and (roll == 1)): print(self.name, 'rolled a 1, built body') self._body = True return True if (self._body and (not self._head) and (roll == 2)): print(self.name, 'rolled a 2, built head') self._head = True return True if (self._head and (not self._left_legs) and (roll == 3)): print(self.name, 'rolled a 3, built left legs') self._left_legs = True return True if (self._left_legs and (not self._right_legs) and (roll == 3)): print(self.name, 'rolled a 3, built right legs') self._right_legs = True return True if (self._right_legs and (not self._left_antenna) and (roll == 4)): print(self.name, 'rolled a 4, built left antenna') self._left_antenna = True return True if (self._left_antenna and (not self._right_antenna) and (roll == 4)): print(self.name, 'rolled a 4, built right antenna') self._right_antenna = True return True if (self._right_antenna and (not self._left_eye) and (roll == 5)): print(self.name, 'rolled a 5, built left eye') self._left_eye = True return True if (self._left_eye and (not self._right_eye) and (roll == 5)): print(self.name, 'rolled a 5, built right eye') self._right_eye = True return True return False
Represents the act of taking a turn in the game. Moves forward a step in the state machine
beetle_gui.py
turn
PR3x/beetle
0
python
def turn(self, roll) -> bool: 'Represents the act of taking a turn in the game.\n\n Moves forward a step in the state machine' if ((not self._body) and (roll == 1)): print(self.name, 'rolled a 1, built body') self._body = True return True if (self._body and (not self._head) and (roll == 2)): print(self.name, 'rolled a 2, built head') self._head = True return True if (self._head and (not self._left_legs) and (roll == 3)): print(self.name, 'rolled a 3, built left legs') self._left_legs = True return True if (self._left_legs and (not self._right_legs) and (roll == 3)): print(self.name, 'rolled a 3, built right legs') self._right_legs = True return True if (self._right_legs and (not self._left_antenna) and (roll == 4)): print(self.name, 'rolled a 4, built left antenna') self._left_antenna = True return True if (self._left_antenna and (not self._right_antenna) and (roll == 4)): print(self.name, 'rolled a 4, built right antenna') self._right_antenna = True return True if (self._right_antenna and (not self._left_eye) and (roll == 5)): print(self.name, 'rolled a 5, built left eye') self._left_eye = True return True if (self._left_eye and (not self._right_eye) and (roll == 5)): print(self.name, 'rolled a 5, built right eye') self._right_eye = True return True return False
def turn(self, roll) -> bool: 'Represents the act of taking a turn in the game.\n\n Moves forward a step in the state machine' if ((not self._body) and (roll == 1)): print(self.name, 'rolled a 1, built body') self._body = True return True if (self._body and (not self._head) and (roll == 2)): print(self.name, 'rolled a 2, built head') self._head = True return True if (self._head and (not self._left_legs) and (roll == 3)): print(self.name, 'rolled a 3, built left legs') self._left_legs = True return True if (self._left_legs and (not self._right_legs) and (roll == 3)): print(self.name, 'rolled a 3, built right legs') self._right_legs = True return True if (self._right_legs and (not self._left_antenna) and (roll == 4)): print(self.name, 'rolled a 4, built left antenna') self._left_antenna = True return True if (self._left_antenna and (not self._right_antenna) and (roll == 4)): print(self.name, 'rolled a 4, built right antenna') self._right_antenna = True return True if (self._right_antenna and (not self._left_eye) and (roll == 5)): print(self.name, 'rolled a 5, built left eye') self._left_eye = True return True if (self._left_eye and (not self._right_eye) and (roll == 5)): print(self.name, 'rolled a 5, built right eye') self._right_eye = True return True return False<|docstring|>Represents the act of taking a turn in the game. Moves forward a step in the state machine<|endoftext|>
f1e867376cb17b2c6345f5e7371bfddf4258b7dadbf4b163757864ff5baed8be
def __str__(self) -> str: 'Pretty string representation of the beetle' percent_complete = ((sum([self._body, self._head, self._left_legs, self._right_legs, self._left_antenna, self._right_antenna, self._left_eye, self._right_eye]) * 100) / 8) return '{} is {}% complete'.format(self.name, percent_complete)
Pretty string representation of the beetle
beetle_gui.py
__str__
PR3x/beetle
0
python
def __str__(self) -> str: percent_complete = ((sum([self._body, self._head, self._left_legs, self._right_legs, self._left_antenna, self._right_antenna, self._left_eye, self._right_eye]) * 100) / 8) return '{} is {}% complete'.format(self.name, percent_complete)
def __str__(self) -> str: percent_complete = ((sum([self._body, self._head, self._left_legs, self._right_legs, self._left_antenna, self._right_antenna, self._left_eye, self._right_eye]) * 100) / 8) return '{} is {}% complete'.format(self.name, percent_complete)<|docstring|>Pretty string representation of the beetle<|endoftext|>
4c4ad9c64b72730aedbbe0553b8b81ae731a48157522d7291582f44ef24cf700
def print(self): 'Prints string representation directly to console' print(self)
Prints string representation directly to console
beetle_gui.py
print
PR3x/beetle
0
python
def print(self): print(self)
def print(self): print(self)<|docstring|>Prints string representation directly to console<|endoftext|>
c243a594d294b26bfb233bbb6d7ec3bb5ab738458075078a5a3ff9635e02eca1
def complete(self) -> bool: 'Returns true if beetle is complete and the game has been won\n\n All parts must exist.' return (self._body and self._head and self._left_legs and self._right_legs and self._left_antenna and self._right_antenna and self._left_eye and self._right_eye)
Returns true if beetle is complete and the game has been won All parts must exist.
beetle_gui.py
complete
PR3x/beetle
0
python
def complete(self) -> bool: 'Returns true if beetle is complete and the game has been won\n\n All parts must exist.' return (self._body and self._head and self._left_legs and self._right_legs and self._left_antenna and self._right_antenna and self._left_eye and self._right_eye)
def complete(self) -> bool: 'Returns true if beetle is complete and the game has been won\n\n All parts must exist.' return (self._body and self._head and self._left_legs and self._right_legs and self._left_antenna and self._right_antenna and self._left_eye and self._right_eye)<|docstring|>Returns true if beetle is complete and the game has been won All parts must exist.<|endoftext|>
f0825f50ab85ea603b6cff85ea75299782f9862137a5cfc4d35d6fc29cde7461
def draw(self): 'Draws the beetle to image_label using included gif images' image = self._app.none_image if self._body: image = self._app.body_image if self._head: image = self._app.head_image if self._left_legs: image = self._app.left_legs_image if self._right_legs: image = self._app.right_legs_image if self._left_antenna: image = self._app.left_antenna_image if self._right_antenna: image = self._app.right_antenna_image if self._left_eye: image = self._app.left_eye_image if self._right_eye: image = self._app.right_eye_image self._image_label['image'] = image
Draws the beetle to image_label using included gif images
beetle_gui.py
draw
PR3x/beetle
0
python
def draw(self): image = self._app.none_image if self._body: image = self._app.body_image if self._head: image = self._app.head_image if self._left_legs: image = self._app.left_legs_image if self._right_legs: image = self._app.right_legs_image if self._left_antenna: image = self._app.left_antenna_image if self._right_antenna: image = self._app.right_antenna_image if self._left_eye: image = self._app.left_eye_image if self._right_eye: image = self._app.right_eye_image self._image_label['image'] = image
def draw(self): image = self._app.none_image if self._body: image = self._app.body_image if self._head: image = self._app.head_image if self._left_legs: image = self._app.left_legs_image if self._right_legs: image = self._app.right_legs_image if self._left_antenna: image = self._app.left_antenna_image if self._right_antenna: image = self._app.right_antenna_image if self._left_eye: image = self._app.left_eye_image if self._right_eye: image = self._app.right_eye_image self._image_label['image'] = image<|docstring|>Draws the beetle to image_label using included gif images<|endoftext|>
6621eea9db9c0982242988baa960a3f5318cf0a0d250168cc8001910c2c16bf9
def turn(self, roll): 'Represents the act of taking a turn in the game.\n\n Moves forward a step in the state machine,\n then draws itself to the screen' out = Beetle.turn(self, roll) self.draw() return out
Represents the act of taking a turn in the game. Moves forward a step in the state machine, then draws itself to the screen
beetle_gui.py
turn
PR3x/beetle
0
python
def turn(self, roll): 'Represents the act of taking a turn in the game.\n\n Moves forward a step in the state machine,\n then draws itself to the screen' out = Beetle.turn(self, roll) self.draw() return out
def turn(self, roll): 'Represents the act of taking a turn in the game.\n\n Moves forward a step in the state machine,\n then draws itself to the screen' out = Beetle.turn(self, roll) self.draw() return out<|docstring|>Represents the act of taking a turn in the game. Moves forward a step in the state machine, then draws itself to the screen<|endoftext|>
531fc3e739f84fd57ebb05023a9e92513928fa07801f6f463ff27033eb0ffdb8
def __init__(self, app=None): 'Sets up a new game' self.__players = [] self._app = app self.__players.append(TkBeetle('Player 1', imageLabel=app.beetle_1, app=app)) self.__players.append(TkBeetle('Player 2', imageLabel=app.beetle_2, app=app)) self.__die = Die() self.complete = False
Sets up a new game
beetle_gui.py
__init__
PR3x/beetle
0
python
def __init__(self, app=None): self.__players = [] self._app = app self.__players.append(TkBeetle('Player 1', imageLabel=app.beetle_1, app=app)) self.__players.append(TkBeetle('Player 2', imageLabel=app.beetle_2, app=app)) self.__die = Die() self.complete = False
def __init__(self, app=None): self.__players = [] self._app = app self.__players.append(TkBeetle('Player 1', imageLabel=app.beetle_1, app=app)) self.__players.append(TkBeetle('Player 2', imageLabel=app.beetle_2, app=app)) self.__die = Die() self.complete = False<|docstring|>Sets up a new game<|endoftext|>
a0b5496c760689412983002cae6174a02cc8999861eca797bc5724734bac176e
def turn(self): 'Takes a turn for the current player.' round_info = '' for player in self.__players: roll = self.__die.roll() player.turn(roll) round_info += '{} rolled a {}\n'.format(player.name, roll) print(round_info) self._app.infotext['text'] = round_info if player.complete(): if ((player.name is not None) or (player.name is not '')): print(player.name, 'wins!') print('GAME OVER') self.complete = True (yield True) (yield False)
Takes a turn for the current player.
beetle_gui.py
turn
PR3x/beetle
0
python
def turn(self): round_info = for player in self.__players: roll = self.__die.roll() player.turn(roll) round_info += '{} rolled a {}\n'.format(player.name, roll) print(round_info) self._app.infotext['text'] = round_info if player.complete(): if ((player.name is not None) or (player.name is not )): print(player.name, 'wins!') print('GAME OVER') self.complete = True (yield True) (yield False)
def turn(self): round_info = for player in self.__players: roll = self.__die.roll() player.turn(roll) round_info += '{} rolled a {}\n'.format(player.name, roll) print(round_info) self._app.infotext['text'] = round_info if player.complete(): if ((player.name is not None) or (player.name is not )): print(player.name, 'wins!') print('GAME OVER') self.complete = True (yield True) (yield False)<|docstring|>Takes a turn for the current player.<|endoftext|>
4000efbf0ded4d5b6e07979f33092337cc6d12294828e5233a1f484cf3df0f89
def round(self): 'Takes a turn for all players' for turn in self.turn(): if turn: return True return False
Takes a turn for all players
beetle_gui.py
round
PR3x/beetle
0
python
def round(self): for turn in self.turn(): if turn: return True return False
def round(self): for turn in self.turn(): if turn: return True return False<|docstring|>Takes a turn for all players<|endoftext|>
9b54a2de6622726155ce4e504f94ed38a7a90f6a62d31c41664556bd45f240f8
def setup(self): 'Initialize the window and create some constants' self.none_image = PhotoImage(file='none.gif') self.body_image = PhotoImage(file='body.gif') self.head_image = PhotoImage(file='head.gif') self.left_legs_image = PhotoImage(file='left_legs.gif') self.right_legs_image = PhotoImage(file='right_legs.gif') self.left_antenna_image = PhotoImage(file='left_antenna.gif') self.right_antenna_image = PhotoImage(file='right_antenna.gif') self.left_eye_image = PhotoImage(file='left_eye.gif') self.right_eye_image = PhotoImage(file='right_eye.gif') self.grid(column=0, row=0, sticky=(N, W, E, S)) self.columnconfigure(0, weight=1) self.rowconfigure(0, weight=1) self.beetle_1 = Label(self) self.beetle_1['image'] = self.none_image self.beetle_1.grid(column=0, row=0, sticky=(N, W)) self.beetle_2 = Label(self) self.beetle_2['image'] = self.none_image self.beetle_2.grid(column=2, row=0, sticky=(N, E)) self.infotext = Label(self, text='Testing') self.infotext.grid(column=1, row=1, sticky=(W, S, E)) self._turn_button = Button(self, text='Roll', command=self.turn) self._turn_button.grid(column=0, row=1, sticky=(W, S)) self._reset_button = Button(self, text='Reset', command=self.reset) self._reset_button.grid(column=2, row=1, sticky=(E, S)) for child in self.winfo_children(): child.grid_configure(padx=5, pady=5) self._turn_button.focus()
Initialize the window and create some constants
beetle_gui.py
setup
PR3x/beetle
0
python
def setup(self): self.none_image = PhotoImage(file='none.gif') self.body_image = PhotoImage(file='body.gif') self.head_image = PhotoImage(file='head.gif') self.left_legs_image = PhotoImage(file='left_legs.gif') self.right_legs_image = PhotoImage(file='right_legs.gif') self.left_antenna_image = PhotoImage(file='left_antenna.gif') self.right_antenna_image = PhotoImage(file='right_antenna.gif') self.left_eye_image = PhotoImage(file='left_eye.gif') self.right_eye_image = PhotoImage(file='right_eye.gif') self.grid(column=0, row=0, sticky=(N, W, E, S)) self.columnconfigure(0, weight=1) self.rowconfigure(0, weight=1) self.beetle_1 = Label(self) self.beetle_1['image'] = self.none_image self.beetle_1.grid(column=0, row=0, sticky=(N, W)) self.beetle_2 = Label(self) self.beetle_2['image'] = self.none_image self.beetle_2.grid(column=2, row=0, sticky=(N, E)) self.infotext = Label(self, text='Testing') self.infotext.grid(column=1, row=1, sticky=(W, S, E)) self._turn_button = Button(self, text='Roll', command=self.turn) self._turn_button.grid(column=0, row=1, sticky=(W, S)) self._reset_button = Button(self, text='Reset', command=self.reset) self._reset_button.grid(column=2, row=1, sticky=(E, S)) for child in self.winfo_children(): child.grid_configure(padx=5, pady=5) self._turn_button.focus()
def setup(self): self.none_image = PhotoImage(file='none.gif') self.body_image = PhotoImage(file='body.gif') self.head_image = PhotoImage(file='head.gif') self.left_legs_image = PhotoImage(file='left_legs.gif') self.right_legs_image = PhotoImage(file='right_legs.gif') self.left_antenna_image = PhotoImage(file='left_antenna.gif') self.right_antenna_image = PhotoImage(file='right_antenna.gif') self.left_eye_image = PhotoImage(file='left_eye.gif') self.right_eye_image = PhotoImage(file='right_eye.gif') self.grid(column=0, row=0, sticky=(N, W, E, S)) self.columnconfigure(0, weight=1) self.rowconfigure(0, weight=1) self.beetle_1 = Label(self) self.beetle_1['image'] = self.none_image self.beetle_1.grid(column=0, row=0, sticky=(N, W)) self.beetle_2 = Label(self) self.beetle_2['image'] = self.none_image self.beetle_2.grid(column=2, row=0, sticky=(N, E)) self.infotext = Label(self, text='Testing') self.infotext.grid(column=1, row=1, sticky=(W, S, E)) self._turn_button = Button(self, text='Roll', command=self.turn) self._turn_button.grid(column=0, row=1, sticky=(W, S)) self._reset_button = Button(self, text='Reset', command=self.reset) self._reset_button.grid(column=2, row=1, sticky=(E, S)) for child in self.winfo_children(): child.grid_configure(padx=5, pady=5) self._turn_button.focus()<|docstring|>Initialize the window and create some constants<|endoftext|>
975d2f315731f0c5233bbb46302eb373cae888b526dbe0eab46f7ce135a0075f
def turn(self): 'Takes a turn in the game' self._game.round() if self._game.complete: self.game_over()
Takes a turn in the game
beetle_gui.py
turn
PR3x/beetle
0
python
def turn(self): self._game.round() if self._game.complete: self.game_over()
def turn(self): self._game.round() if self._game.complete: self.game_over()<|docstring|>Takes a turn in the game<|endoftext|>
15857a242994a8895a940db15dee38813104535e2b97bc1f2ebbcb447dd0aec0
def game_over(self): 'Caled when a player wins the game' self._turn_button.state(['disabled']) self._reset_button.focus() self.infotext['text'] += 'Game Over!'
Caled when a player wins the game
beetle_gui.py
game_over
PR3x/beetle
0
python
def game_over(self): self._turn_button.state(['disabled']) self._reset_button.focus() self.infotext['text'] += 'Game Over!'
def game_over(self): self._turn_button.state(['disabled']) self._reset_button.focus() self.infotext['text'] += 'Game Over!'<|docstring|>Caled when a player wins the game<|endoftext|>
56430519c475983d240a2291264eb555bcc2ca1a7a129e44126ac27c0c69e006
def reset(self): 'Resets the game state' self._game = Game(app=self) self.beetle_1['image'] = self.none_image self.beetle_2['image'] = self.none_image self._turn_button.state(['!disabled']) self._turn_button.focus()
Resets the game state
beetle_gui.py
reset
PR3x/beetle
0
python
def reset(self): self._game = Game(app=self) self.beetle_1['image'] = self.none_image self.beetle_2['image'] = self.none_image self._turn_button.state(['!disabled']) self._turn_button.focus()
def reset(self): self._game = Game(app=self) self.beetle_1['image'] = self.none_image self.beetle_2['image'] = self.none_image self._turn_button.state(['!disabled']) self._turn_button.focus()<|docstring|>Resets the game state<|endoftext|>
70c44ff66bb0b2c2cded976e2e2eee965e05f6316b13fb4dc2c1df0e5b1ee634
def extract(self, element: Element) -> Union[(List[Element], List[str])]: '\n Extract subelements or data from XML or HTML data.\n\n :param element: Target.\n :type element: :class:`data_extractor.lxml.Element`\n\n :returns: List of :class:`data_extractor.lxml.Element` objects, List of str, or str.\n :rtype: list\n\n :raises data_extractor.exceptions.ExprError: XPath Expression Error.\n ' from lxml.etree import XPathEvalError try: rv = self._find(element) if (not isinstance(rv, list)): return [rv] else: return rv except XPathEvalError as exc: raise ExprError(extractor=self, exc=exc) from exc
Extract subelements or data from XML or HTML data. :param element: Target. :type element: :class:`data_extractor.lxml.Element` :returns: List of :class:`data_extractor.lxml.Element` objects, List of str, or str. :rtype: list :raises data_extractor.exceptions.ExprError: XPath Expression Error.
data_extractor/lxml.py
extract
linw1995/data_extractor
28
python
def extract(self, element: Element) -> Union[(List[Element], List[str])]: '\n Extract subelements or data from XML or HTML data.\n\n :param element: Target.\n :type element: :class:`data_extractor.lxml.Element`\n\n :returns: List of :class:`data_extractor.lxml.Element` objects, List of str, or str.\n :rtype: list\n\n :raises data_extractor.exceptions.ExprError: XPath Expression Error.\n ' from lxml.etree import XPathEvalError try: rv = self._find(element) if (not isinstance(rv, list)): return [rv] else: return rv except XPathEvalError as exc: raise ExprError(extractor=self, exc=exc) from exc
def extract(self, element: Element) -> Union[(List[Element], List[str])]: '\n Extract subelements or data from XML or HTML data.\n\n :param element: Target.\n :type element: :class:`data_extractor.lxml.Element`\n\n :returns: List of :class:`data_extractor.lxml.Element` objects, List of str, or str.\n :rtype: list\n\n :raises data_extractor.exceptions.ExprError: XPath Expression Error.\n ' from lxml.etree import XPathEvalError try: rv = self._find(element) if (not isinstance(rv, list)): return [rv] else: return rv except XPathEvalError as exc: raise ExprError(extractor=self, exc=exc) from exc<|docstring|>Extract subelements or data from XML or HTML data. :param element: Target. :type element: :class:`data_extractor.lxml.Element` :returns: List of :class:`data_extractor.lxml.Element` objects, List of str, or str. :rtype: list :raises data_extractor.exceptions.ExprError: XPath Expression Error.<|endoftext|>
b55bf08396d787b4ed39dc1c575a87a8190bb02d0b8025ac9db21520adb21dbd
def extract(self, element: Element) -> List[Element]: '\n Extract subelements from XML or HTML data.\n\n :param element: Target.\n :type element: :class:`data_extractor.lxml.Element`\n\n :returns: List of :class:`data_extractor.lxml.Element` objects, extracted result.\n :rtype: list\n ' return self._extractor.extract(element)
Extract subelements from XML or HTML data. :param element: Target. :type element: :class:`data_extractor.lxml.Element` :returns: List of :class:`data_extractor.lxml.Element` objects, extracted result. :rtype: list
data_extractor/lxml.py
extract
linw1995/data_extractor
28
python
def extract(self, element: Element) -> List[Element]: '\n Extract subelements from XML or HTML data.\n\n :param element: Target.\n :type element: :class:`data_extractor.lxml.Element`\n\n :returns: List of :class:`data_extractor.lxml.Element` objects, extracted result.\n :rtype: list\n ' return self._extractor.extract(element)
def extract(self, element: Element) -> List[Element]: '\n Extract subelements from XML or HTML data.\n\n :param element: Target.\n :type element: :class:`data_extractor.lxml.Element`\n\n :returns: List of :class:`data_extractor.lxml.Element` objects, extracted result.\n :rtype: list\n ' return self._extractor.extract(element)<|docstring|>Extract subelements from XML or HTML data. :param element: Target. :type element: :class:`data_extractor.lxml.Element` :returns: List of :class:`data_extractor.lxml.Element` objects, extracted result. :rtype: list<|endoftext|>
077942fb20d15fba09de3aa00b984b6b252eab5d1a831f4c4ce82f437139cfa0
def extract(self, element: Element) -> List[str]: "\n Extract subelements' text from XML or HTML data.\n\n :param element: Target.\n :type element: :class:`data_extractor.lxml.Element`\n\n :returns: List of str, extracted result.\n :rtype: list\n\n :raises ~data_extractor.exceptions.ExprError: CSS Selector Expression Error.\n " return [ele.text for ele in super().extract(element)]
Extract subelements' text from XML or HTML data. :param element: Target. :type element: :class:`data_extractor.lxml.Element` :returns: List of str, extracted result. :rtype: list :raises ~data_extractor.exceptions.ExprError: CSS Selector Expression Error.
data_extractor/lxml.py
extract
linw1995/data_extractor
28
python
def extract(self, element: Element) -> List[str]: "\n Extract subelements' text from XML or HTML data.\n\n :param element: Target.\n :type element: :class:`data_extractor.lxml.Element`\n\n :returns: List of str, extracted result.\n :rtype: list\n\n :raises ~data_extractor.exceptions.ExprError: CSS Selector Expression Error.\n " return [ele.text for ele in super().extract(element)]
def extract(self, element: Element) -> List[str]: "\n Extract subelements' text from XML or HTML data.\n\n :param element: Target.\n :type element: :class:`data_extractor.lxml.Element`\n\n :returns: List of str, extracted result.\n :rtype: list\n\n :raises ~data_extractor.exceptions.ExprError: CSS Selector Expression Error.\n " return [ele.text for ele in super().extract(element)]<|docstring|>Extract subelements' text from XML or HTML data. :param element: Target. :type element: :class:`data_extractor.lxml.Element` :returns: List of str, extracted result. :rtype: list :raises ~data_extractor.exceptions.ExprError: CSS Selector Expression Error.<|endoftext|>
d99950097f55e0862eb0fc2e2f8416884adec17b35bc8fd267a9b26d0f9d4279
def extract(self, element: Element) -> List[str]: "\n Extract subelements' attribute value from XML or HTML data.\n\n :param element: Target.\n :type element: :class:`data_extractor.lxml.Element`\n\n :returns: List of str, extracted result.\n :rtype: list\n\n :raises ~data_extractor.exceptions.ExprError: CSS Selector Expression Error.\n " return [ele.get(self.attr) for ele in super().extract(element) if (self.attr in ele.keys())]
Extract subelements' attribute value from XML or HTML data. :param element: Target. :type element: :class:`data_extractor.lxml.Element` :returns: List of str, extracted result. :rtype: list :raises ~data_extractor.exceptions.ExprError: CSS Selector Expression Error.
data_extractor/lxml.py
extract
linw1995/data_extractor
28
python
def extract(self, element: Element) -> List[str]: "\n Extract subelements' attribute value from XML or HTML data.\n\n :param element: Target.\n :type element: :class:`data_extractor.lxml.Element`\n\n :returns: List of str, extracted result.\n :rtype: list\n\n :raises ~data_extractor.exceptions.ExprError: CSS Selector Expression Error.\n " return [ele.get(self.attr) for ele in super().extract(element) if (self.attr in ele.keys())]
def extract(self, element: Element) -> List[str]: "\n Extract subelements' attribute value from XML or HTML data.\n\n :param element: Target.\n :type element: :class:`data_extractor.lxml.Element`\n\n :returns: List of str, extracted result.\n :rtype: list\n\n :raises ~data_extractor.exceptions.ExprError: CSS Selector Expression Error.\n " return [ele.get(self.attr) for ele in super().extract(element) if (self.attr in ele.keys())]<|docstring|>Extract subelements' attribute value from XML or HTML data. :param element: Target. :type element: :class:`data_extractor.lxml.Element` :returns: List of str, extracted result. :rtype: list :raises ~data_extractor.exceptions.ExprError: CSS Selector Expression Error.<|endoftext|>
00be8a8052992b2d7c1985a9714b20d6a3adce88bd489b238ee664e674e9faea
def __init__(self, ncomps, base_neurons=[512, 512], center_idx: int=9, use_pca=True, use_shape=True, mano_root='assets/mano', mano_pose_coeff=1, mano_side='right', dropout=0): '\n Args:\n mano_root (path): dir containing mano pickle files\n center_idx: Joint idx on which to hand is centered (given joint has position\n [0, 0, 0]\n ncomps: Number of pose principal components that are predicted\n ' super(ManoBranch, self).__init__() self.use_shape = use_shape self.use_pca = use_pca self.mano_pose_coeff = mano_pose_coeff self.mano_side = mano_side if self.use_pca: mano_pose_size = (ncomps + 3) else: mano_pose_size = (16 * 9) base_layers = [] for (inp_neurons, out_neurons) in zip(base_neurons[:(- 1)], base_neurons[1:]): if dropout: base_layers.append(nn.Dropout(p=dropout)) base_layers.append(nn.Linear(inp_neurons, out_neurons)) base_layers.append(nn.ReLU()) self.base_layer = nn.Sequential(*base_layers) self.pose_reg = nn.Linear(base_neurons[(- 1)], mano_pose_size) if (not self.use_pca): self.pose_reg.bias.data.fill_(0) weight_mask = self.pose_reg.weight.data.new(np.identity(3)).view(9).repeat(16) self.pose_reg.weight.data = torch.abs((weight_mask.unsqueeze(1).repeat(1, 256).float() * self.pose_reg.weight.data)) if self.use_shape: self.shape_reg = torch.nn.Sequential(nn.Linear(base_neurons[(- 1)], 10)) self.mano_layer = ManoLayer(ncomps=ncomps, center_idx=center_idx, side=mano_side, mano_root=mano_root, use_pca=use_pca, flat_hand_mean=False, return_full_pose=True) self.faces = self.mano_layer.th_faces
Args: mano_root (path): dir containing mano pickle files center_idx: Joint idx on which to hand is centered (given joint has position [0, 0, 0] ncomps: Number of pose principal components that are predicted
hocontact/models/manobranch.py
__init__
lixiny/CPF
80
python
def __init__(self, ncomps, base_neurons=[512, 512], center_idx: int=9, use_pca=True, use_shape=True, mano_root='assets/mano', mano_pose_coeff=1, mano_side='right', dropout=0): '\n Args:\n mano_root (path): dir containing mano pickle files\n center_idx: Joint idx on which to hand is centered (given joint has position\n [0, 0, 0]\n ncomps: Number of pose principal components that are predicted\n ' super(ManoBranch, self).__init__() self.use_shape = use_shape self.use_pca = use_pca self.mano_pose_coeff = mano_pose_coeff self.mano_side = mano_side if self.use_pca: mano_pose_size = (ncomps + 3) else: mano_pose_size = (16 * 9) base_layers = [] for (inp_neurons, out_neurons) in zip(base_neurons[:(- 1)], base_neurons[1:]): if dropout: base_layers.append(nn.Dropout(p=dropout)) base_layers.append(nn.Linear(inp_neurons, out_neurons)) base_layers.append(nn.ReLU()) self.base_layer = nn.Sequential(*base_layers) self.pose_reg = nn.Linear(base_neurons[(- 1)], mano_pose_size) if (not self.use_pca): self.pose_reg.bias.data.fill_(0) weight_mask = self.pose_reg.weight.data.new(np.identity(3)).view(9).repeat(16) self.pose_reg.weight.data = torch.abs((weight_mask.unsqueeze(1).repeat(1, 256).float() * self.pose_reg.weight.data)) if self.use_shape: self.shape_reg = torch.nn.Sequential(nn.Linear(base_neurons[(- 1)], 10)) self.mano_layer = ManoLayer(ncomps=ncomps, center_idx=center_idx, side=mano_side, mano_root=mano_root, use_pca=use_pca, flat_hand_mean=False, return_full_pose=True) self.faces = self.mano_layer.th_faces
def __init__(self, ncomps, base_neurons=[512, 512], center_idx: int=9, use_pca=True, use_shape=True, mano_root='assets/mano', mano_pose_coeff=1, mano_side='right', dropout=0): '\n Args:\n mano_root (path): dir containing mano pickle files\n center_idx: Joint idx on which to hand is centered (given joint has position\n [0, 0, 0]\n ncomps: Number of pose principal components that are predicted\n ' super(ManoBranch, self).__init__() self.use_shape = use_shape self.use_pca = use_pca self.mano_pose_coeff = mano_pose_coeff self.mano_side = mano_side if self.use_pca: mano_pose_size = (ncomps + 3) else: mano_pose_size = (16 * 9) base_layers = [] for (inp_neurons, out_neurons) in zip(base_neurons[:(- 1)], base_neurons[1:]): if dropout: base_layers.append(nn.Dropout(p=dropout)) base_layers.append(nn.Linear(inp_neurons, out_neurons)) base_layers.append(nn.ReLU()) self.base_layer = nn.Sequential(*base_layers) self.pose_reg = nn.Linear(base_neurons[(- 1)], mano_pose_size) if (not self.use_pca): self.pose_reg.bias.data.fill_(0) weight_mask = self.pose_reg.weight.data.new(np.identity(3)).view(9).repeat(16) self.pose_reg.weight.data = torch.abs((weight_mask.unsqueeze(1).repeat(1, 256).float() * self.pose_reg.weight.data)) if self.use_shape: self.shape_reg = torch.nn.Sequential(nn.Linear(base_neurons[(- 1)], 10)) self.mano_layer = ManoLayer(ncomps=ncomps, center_idx=center_idx, side=mano_side, mano_root=mano_root, use_pca=use_pca, flat_hand_mean=False, return_full_pose=True) self.faces = self.mano_layer.th_faces<|docstring|>Args: mano_root (path): dir containing mano pickle files center_idx: Joint idx on which to hand is centered (given joint has position [0, 0, 0] ncomps: Number of pose principal components that are predicted<|endoftext|>
d71b09d8d478f9dfd88c151067afc546b737136314e328906c91a298bc96b56a
def critical_point(self, cp_override: CriticalPoint=None) -> Point: "\n The vector from the pipette's origin to its critical point. The\n critical point for a pipette is the end of the nozzle if no tip is\n attached, or the end of the tip if a tip is attached.\n\n If `cp_override` is specified and valid - so is either\n :py:attr:`CriticalPoint.NOZZLE` or :py:attr:`CriticalPoint.TIP` when\n we have a tip, or :py:attr:`CriticalPoint.XY_CENTER` - the specified\n critical point will be used.\n " if ((not self.has_tip) or (cp_override == CriticalPoint.NOZZLE)): cp_type = CriticalPoint.NOZZLE tip_length = 0.0 else: cp_type = CriticalPoint.TIP tip_length = self.current_tip_length if (cp_override == CriticalPoint.XY_CENTER): mod_offset_xy = [0, 0, self.model_offset[2]] cp_type = CriticalPoint.XY_CENTER elif (cp_override == CriticalPoint.FRONT_NOZZLE): mod_offset_xy = [0, (- self.model_offset[1]), self.model_offset[2]] cp_type = CriticalPoint.FRONT_NOZZLE else: mod_offset_xy = self.model_offset mod_and_tip = Point(mod_offset_xy[0], mod_offset_xy[1], (mod_offset_xy[2] - tip_length)) cp = (mod_and_tip + self._instrument_offset._replace(z=0)) if self._log.isEnabledFor(logging.DEBUG): mo = ('model offset: {} + '.format(self.model_offset) if (cp_type != CriticalPoint.XY_CENTER) else '') info_str = 'cp: {}{}: {}=({}instr offset xy: {}'.format(cp_type, ('(from override)' if cp_override else ''), cp, mo, self._instrument_offset._replace(z=0)) if (cp_type == CriticalPoint.TIP): info_str += '- current_tip_length: {}=(true tip length: {} - inst z: {}) (z only)'.format(self.current_tip_length, self._current_tip_length, self._instrument_offset.z) info_str += ')' self._log.debug(info_str) return cp
The vector from the pipette's origin to its critical point. The critical point for a pipette is the end of the nozzle if no tip is attached, or the end of the tip if a tip is attached. If `cp_override` is specified and valid - so is either :py:attr:`CriticalPoint.NOZZLE` or :py:attr:`CriticalPoint.TIP` when we have a tip, or :py:attr:`CriticalPoint.XY_CENTER` - the specified critical point will be used.
api/src/opentrons/hardware_control/pipette.py
critical_point
felipesanches/opentrons
0
python
def critical_point(self, cp_override: CriticalPoint=None) -> Point: "\n The vector from the pipette's origin to its critical point. The\n critical point for a pipette is the end of the nozzle if no tip is\n attached, or the end of the tip if a tip is attached.\n\n If `cp_override` is specified and valid - so is either\n :py:attr:`CriticalPoint.NOZZLE` or :py:attr:`CriticalPoint.TIP` when\n we have a tip, or :py:attr:`CriticalPoint.XY_CENTER` - the specified\n critical point will be used.\n " if ((not self.has_tip) or (cp_override == CriticalPoint.NOZZLE)): cp_type = CriticalPoint.NOZZLE tip_length = 0.0 else: cp_type = CriticalPoint.TIP tip_length = self.current_tip_length if (cp_override == CriticalPoint.XY_CENTER): mod_offset_xy = [0, 0, self.model_offset[2]] cp_type = CriticalPoint.XY_CENTER elif (cp_override == CriticalPoint.FRONT_NOZZLE): mod_offset_xy = [0, (- self.model_offset[1]), self.model_offset[2]] cp_type = CriticalPoint.FRONT_NOZZLE else: mod_offset_xy = self.model_offset mod_and_tip = Point(mod_offset_xy[0], mod_offset_xy[1], (mod_offset_xy[2] - tip_length)) cp = (mod_and_tip + self._instrument_offset._replace(z=0)) if self._log.isEnabledFor(logging.DEBUG): mo = ('model offset: {} + '.format(self.model_offset) if (cp_type != CriticalPoint.XY_CENTER) else ) info_str = 'cp: {}{}: {}=({}instr offset xy: {}'.format(cp_type, ('(from override)' if cp_override else ), cp, mo, self._instrument_offset._replace(z=0)) if (cp_type == CriticalPoint.TIP): info_str += '- current_tip_length: {}=(true tip length: {} - inst z: {}) (z only)'.format(self.current_tip_length, self._current_tip_length, self._instrument_offset.z) info_str += ')' self._log.debug(info_str) return cp
def critical_point(self, cp_override: CriticalPoint=None) -> Point: "\n The vector from the pipette's origin to its critical point. The\n critical point for a pipette is the end of the nozzle if no tip is\n attached, or the end of the tip if a tip is attached.\n\n If `cp_override` is specified and valid - so is either\n :py:attr:`CriticalPoint.NOZZLE` or :py:attr:`CriticalPoint.TIP` when\n we have a tip, or :py:attr:`CriticalPoint.XY_CENTER` - the specified\n critical point will be used.\n " if ((not self.has_tip) or (cp_override == CriticalPoint.NOZZLE)): cp_type = CriticalPoint.NOZZLE tip_length = 0.0 else: cp_type = CriticalPoint.TIP tip_length = self.current_tip_length if (cp_override == CriticalPoint.XY_CENTER): mod_offset_xy = [0, 0, self.model_offset[2]] cp_type = CriticalPoint.XY_CENTER elif (cp_override == CriticalPoint.FRONT_NOZZLE): mod_offset_xy = [0, (- self.model_offset[1]), self.model_offset[2]] cp_type = CriticalPoint.FRONT_NOZZLE else: mod_offset_xy = self.model_offset mod_and_tip = Point(mod_offset_xy[0], mod_offset_xy[1], (mod_offset_xy[2] - tip_length)) cp = (mod_and_tip + self._instrument_offset._replace(z=0)) if self._log.isEnabledFor(logging.DEBUG): mo = ('model offset: {} + '.format(self.model_offset) if (cp_type != CriticalPoint.XY_CENTER) else ) info_str = 'cp: {}{}: {}=({}instr offset xy: {}'.format(cp_type, ('(from override)' if cp_override else ), cp, mo, self._instrument_offset._replace(z=0)) if (cp_type == CriticalPoint.TIP): info_str += '- current_tip_length: {}=(true tip length: {} - inst z: {}) (z only)'.format(self.current_tip_length, self._current_tip_length, self._instrument_offset.z) info_str += ')' self._log.debug(info_str) return cp<|docstring|>The vector from the pipette's origin to its critical point. The critical point for a pipette is the end of the nozzle if no tip is attached, or the end of the tip if a tip is attached. If `cp_override` is specified and valid - so is either :py:attr:`CriticalPoint.NOZZLE` or :py:attr:`CriticalPoint.TIP` when we have a tip, or :py:attr:`CriticalPoint.XY_CENTER` - the specified critical point will be used.<|endoftext|>
f54ae77dd7ed3f0ee195c69891f8e059ef1cef6876244d1f17ce551ea2dc2f7e
@property def current_volume(self) -> float: ' The amount of liquid currently aspirated ' return self._current_volume
The amount of liquid currently aspirated
api/src/opentrons/hardware_control/pipette.py
current_volume
felipesanches/opentrons
0
python
@property def current_volume(self) -> float: ' ' return self._current_volume
@property def current_volume(self) -> float: ' ' return self._current_volume<|docstring|>The amount of liquid currently aspirated<|endoftext|>
830b1d581cc3d9969c660bbe5f5d8d6722e7e78fe11429bb6bacff53e6ec2d26
@property def current_tip_length(self) -> float: ' The length of the current tip attached (0.0 if no tip) ' return (self._current_tip_length - self._instrument_offset.z)
The length of the current tip attached (0.0 if no tip)
api/src/opentrons/hardware_control/pipette.py
current_tip_length
felipesanches/opentrons
0
python
@property def current_tip_length(self) -> float: ' ' return (self._current_tip_length - self._instrument_offset.z)
@property def current_tip_length(self) -> float: ' ' return (self._current_tip_length - self._instrument_offset.z)<|docstring|>The length of the current tip attached (0.0 if no tip)<|endoftext|>
ea1284ed807d3a54f591e5672c4c90479ff3fa4c796ecb60b24f6d886d4b801d
@property def current_tiprack_diameter(self) -> float: ' The diameter of the current tip rack (0.0 if no tip) ' return self._current_tiprack_diameter
The diameter of the current tip rack (0.0 if no tip)
api/src/opentrons/hardware_control/pipette.py
current_tiprack_diameter
felipesanches/opentrons
0
python
@property def current_tiprack_diameter(self) -> float: ' ' return self._current_tiprack_diameter
@property def current_tiprack_diameter(self) -> float: ' ' return self._current_tiprack_diameter<|docstring|>The diameter of the current tip rack (0.0 if no tip)<|endoftext|>
e6dbd218b546d9e8474dab3e87fafa7c1ce41ec2eae3a6724c1baef6166383cc
@property def working_volume(self) -> float: ' The working volume of the pipette ' return self._working_volume
The working volume of the pipette
api/src/opentrons/hardware_control/pipette.py
working_volume
felipesanches/opentrons
0
python
@property def working_volume(self) -> float: ' ' return self._working_volume
@property def working_volume(self) -> float: ' ' return self._working_volume<|docstring|>The working volume of the pipette<|endoftext|>
9851b10ca82e3464bf770e2300cdb4f289d7346de9ac34de83633225766319e2
@working_volume.setter def working_volume(self, tip_volume: float): ' The working volume is the current tip max volume ' self._working_volume = min(self.config.max_volume, tip_volume)
The working volume is the current tip max volume
api/src/opentrons/hardware_control/pipette.py
working_volume
felipesanches/opentrons
0
python
@working_volume.setter def working_volume(self, tip_volume: float): ' ' self._working_volume = min(self.config.max_volume, tip_volume)
@working_volume.setter def working_volume(self, tip_volume: float): ' ' self._working_volume = min(self.config.max_volume, tip_volume)<|docstring|>The working volume is the current tip max volume<|endoftext|>
027616c14fc286fc2861510822d0273259473450b52035c154fb96ac7b252ec6
@property def available_volume(self) -> float: ' The amount of liquid possible to aspirate ' return (self.working_volume - self.current_volume)
The amount of liquid possible to aspirate
api/src/opentrons/hardware_control/pipette.py
available_volume
felipesanches/opentrons
0
python
@property def available_volume(self) -> float: ' ' return (self.working_volume - self.current_volume)
@property def available_volume(self) -> float: ' ' return (self.working_volume - self.current_volume)<|docstring|>The amount of liquid possible to aspirate<|endoftext|>
b65b000524a1da5bb679743d39918874cf3a19f96f0cbede382ed43621ca69d2
def add_tip(self, tip_length: float) -> None: "\n Add a tip to the pipette for position tracking and validation\n (effectively updates the pipette's critical point)\n\n :param tip_length: a positive, non-zero float presenting the distance\n in Z from the end of the pipette nozzle to the end of the tip\n :return:\n " assert (tip_length > 0.0), 'tip_length must be greater than 0' assert (not self.has_tip) self._has_tip = True self._current_tip_length = tip_length
Add a tip to the pipette for position tracking and validation (effectively updates the pipette's critical point) :param tip_length: a positive, non-zero float presenting the distance in Z from the end of the pipette nozzle to the end of the tip :return:
api/src/opentrons/hardware_control/pipette.py
add_tip
felipesanches/opentrons
0
python
def add_tip(self, tip_length: float) -> None: "\n Add a tip to the pipette for position tracking and validation\n (effectively updates the pipette's critical point)\n\n :param tip_length: a positive, non-zero float presenting the distance\n in Z from the end of the pipette nozzle to the end of the tip\n :return:\n " assert (tip_length > 0.0), 'tip_length must be greater than 0' assert (not self.has_tip) self._has_tip = True self._current_tip_length = tip_length
def add_tip(self, tip_length: float) -> None: "\n Add a tip to the pipette for position tracking and validation\n (effectively updates the pipette's critical point)\n\n :param tip_length: a positive, non-zero float presenting the distance\n in Z from the end of the pipette nozzle to the end of the tip\n :return:\n " assert (tip_length > 0.0), 'tip_length must be greater than 0' assert (not self.has_tip) self._has_tip = True self._current_tip_length = tip_length<|docstring|>Add a tip to the pipette for position tracking and validation (effectively updates the pipette's critical point) :param tip_length: a positive, non-zero float presenting the distance in Z from the end of the pipette nozzle to the end of the tip :return:<|endoftext|>
fdfa9d9354823072eebc121f793d0b29336d80c96d8ea7a4ee7255b85ce5a81c
def remove_tip(self) -> None: "\n Remove the tip from the pipette (effectively updates the pipette's\n critical point)\n " assert self.has_tip self._has_tip = False self._current_tip_length = 0.0
Remove the tip from the pipette (effectively updates the pipette's critical point)
api/src/opentrons/hardware_control/pipette.py
remove_tip
felipesanches/opentrons
0
python
def remove_tip(self) -> None: "\n Remove the tip from the pipette (effectively updates the pipette's\n critical point)\n " assert self.has_tip self._has_tip = False self._current_tip_length = 0.0
def remove_tip(self) -> None: "\n Remove the tip from the pipette (effectively updates the pipette's\n critical point)\n " assert self.has_tip self._has_tip = False self._current_tip_length = 0.0<|docstring|>Remove the tip from the pipette (effectively updates the pipette's critical point)<|endoftext|>
6375d5e29a894339dbc8623ffd690b52c3ddf33d22d89b2558ae67e176e7e312
def __init__(self, cfgs, images, labels, mode='train', multi_gpu_mode=False): ' ResNet constructor. ' Net.__init__(self, cfgs, images, labels, mode) self._relu_leakiness = cfgs['RELU_LEAKINESS'] self._weight_decay_rate = cfgs['WEIGHT_DECAY_RATE'] self.multi_gpu_mode = multi_gpu_mode
ResNet constructor.
network/inception.py
__init__
Yuanhang8605/CNN-fro-cifar10
2
python
def __init__(self, cfgs, images, labels, mode='train', multi_gpu_mode=False): ' ' Net.__init__(self, cfgs, images, labels, mode) self._relu_leakiness = cfgs['RELU_LEAKINESS'] self._weight_decay_rate = cfgs['WEIGHT_DECAY_RATE'] self.multi_gpu_mode = multi_gpu_mode
def __init__(self, cfgs, images, labels, mode='train', multi_gpu_mode=False): ' ' Net.__init__(self, cfgs, images, labels, mode) self._relu_leakiness = cfgs['RELU_LEAKINESS'] self._weight_decay_rate = cfgs['WEIGHT_DECAY_RATE'] self.multi_gpu_mode = multi_gpu_mode<|docstring|>ResNet constructor.<|endoftext|>
ff0a65ad389162ac58c8895cbc40f25ac1473584e3b45bca390fb69b13aea6a9
def _stride_arr(self, stride): 'Map a stride scalar to the stride array for tf.nn.conv2d.' return [1, stride, stride, 1]
Map a stride scalar to the stride array for tf.nn.conv2d.
network/inception.py
_stride_arr
Yuanhang8605/CNN-fro-cifar10
2
python
def _stride_arr(self, stride): return [1, stride, stride, 1]
def _stride_arr(self, stride): return [1, stride, stride, 1]<|docstring|>Map a stride scalar to the stride array for tf.nn.conv2d.<|endoftext|>
b28361555b4479b2a9a77ff67a6b21f025d0e577ef083e35d90335a9ab073fdf
def inference(self): ' Build the core model within the gragh. \n return:\n loggits before classifier\n ' batch_size = self.images.get_shape()[0] with tf.variable_scope('init'): x = self.images x = ops.conv('init_conv1', x, 3, 3, 16, self._stride_arr(1), 'SAME', self.multi_gpu_mode) (x, train_op) = ops.batch_norm('bn1', x, self.mode, 0.001, self.multi_gpu_mode) self.extra_train_ops.extend(train_op) x = ops.relu(x, self._relu_leakiness) x = ops.conv('init_conv2', x, 3, 16, 16, self._stride_arr(1), 'SAME', self.multi_gpu_mode) (x, train_op) = ops.batch_norm('bn2', x, self.mode, 0.001, self.multi_gpu_mode) self.extra_train_ops.extend(train_op) x = ops.relu(x, self._relu_leakiness) with tf.variable_scope('unit_1_0'): x = tf.nn.max_pool(x, [1, 2, 2, 1], self._stride_arr(2), 'VALID', name='max_pool') x = ops.conv('conv', x, 3, 16, 32, self._stride_arr(1), 'SAME', self.multi_gpu_mode) (x, train_op) = ops.batch_norm('bn', x, self.mode, 0.001, self.multi_gpu_mode) self.extra_train_ops.extend(train_op) x = ops.relu(x, self._relu_leakiness) for i in six.moves.range(1, 2): with tf.variable_scope(('unit_1_%d' % i)): x = ops.conv('conv', x, 3, 32, 32, self._stride_arr(1), 'SAME', self.multi_gpu_mode) (x, train_op) = ops.batch_norm('bn', x, self.mode, 0.001, self.multi_gpu_mode) self.extra_train_ops.extend(train_op) x = ops.relu(x, self._relu_leakiness) with tf.variable_scope('unit_2_0'): x = tf.nn.max_pool(x, [1, 2, 2, 1], self._stride_arr(2), 'VALID', name='max_pool') x = ops.conv('conv', x, 3, 32, 64, self._stride_arr(1), 'SAME', self.multi_gpu_mode) (x, train_op) = ops.batch_norm('bn', x, self.mode, 0.001, self.multi_gpu_mode) self.extra_train_ops.extend(train_op) x = ops.relu(x, self._relu_leakiness) for i in six.moves.range(1, 4): with tf.variable_scope(('unit_2_%d' % i)): x = ops.conv('conv', x, 3, 64, 64, self._stride_arr(1), 'SAME', self.multi_gpu_mode) (x, train_op) = ops.batch_norm('bn', x, self.mode, 0.001, self.multi_gpu_mode) self.extra_train_ops.extend(train_op) x = ops.relu(x, self._relu_leakiness) with tf.variable_scope('unit_3_0'): x = tf.nn.max_pool(x, [1, 2, 2, 1], self._stride_arr(2), 'VALID', name='max_pool') x = ops.conv('conv', x, 3, 64, 128, self._stride_arr(1), 'SAME', self.multi_gpu_mode) (x, train_op) = ops.batch_norm('bn', x, self.mode, 0.001, self.multi_gpu_mode) self.extra_train_ops.extend(train_op) x = ops.relu(x, self._relu_leakiness) for i in six.moves.range(1, 4): with tf.variable_scope(('unit_3_%d' % i)): x = ops.conv('conv', x, 3, 128, 128, self._stride_arr(1), 'SAME', self.multi_gpu_mode) (x, train_op) = ops.batch_norm('bn', x, self.mode, 0.001, self.multi_gpu_mode) self.extra_train_ops.extend(train_op) x = ops.relu(x, self._relu_leakiness) with tf.variable_scope('unit_last'): x = ops.global_avg_pool(x) with tf.variable_scope('logit'): logits = ops.fc('fc1', x, batch_size, self.num_classes, self.multi_gpu_mode) self.logits = logits
Build the core model within the gragh. return: loggits before classifier
network/inception.py
inference
Yuanhang8605/CNN-fro-cifar10
2
python
def inference(self): ' Build the core model within the gragh. \n return:\n loggits before classifier\n ' batch_size = self.images.get_shape()[0] with tf.variable_scope('init'): x = self.images x = ops.conv('init_conv1', x, 3, 3, 16, self._stride_arr(1), 'SAME', self.multi_gpu_mode) (x, train_op) = ops.batch_norm('bn1', x, self.mode, 0.001, self.multi_gpu_mode) self.extra_train_ops.extend(train_op) x = ops.relu(x, self._relu_leakiness) x = ops.conv('init_conv2', x, 3, 16, 16, self._stride_arr(1), 'SAME', self.multi_gpu_mode) (x, train_op) = ops.batch_norm('bn2', x, self.mode, 0.001, self.multi_gpu_mode) self.extra_train_ops.extend(train_op) x = ops.relu(x, self._relu_leakiness) with tf.variable_scope('unit_1_0'): x = tf.nn.max_pool(x, [1, 2, 2, 1], self._stride_arr(2), 'VALID', name='max_pool') x = ops.conv('conv', x, 3, 16, 32, self._stride_arr(1), 'SAME', self.multi_gpu_mode) (x, train_op) = ops.batch_norm('bn', x, self.mode, 0.001, self.multi_gpu_mode) self.extra_train_ops.extend(train_op) x = ops.relu(x, self._relu_leakiness) for i in six.moves.range(1, 2): with tf.variable_scope(('unit_1_%d' % i)): x = ops.conv('conv', x, 3, 32, 32, self._stride_arr(1), 'SAME', self.multi_gpu_mode) (x, train_op) = ops.batch_norm('bn', x, self.mode, 0.001, self.multi_gpu_mode) self.extra_train_ops.extend(train_op) x = ops.relu(x, self._relu_leakiness) with tf.variable_scope('unit_2_0'): x = tf.nn.max_pool(x, [1, 2, 2, 1], self._stride_arr(2), 'VALID', name='max_pool') x = ops.conv('conv', x, 3, 32, 64, self._stride_arr(1), 'SAME', self.multi_gpu_mode) (x, train_op) = ops.batch_norm('bn', x, self.mode, 0.001, self.multi_gpu_mode) self.extra_train_ops.extend(train_op) x = ops.relu(x, self._relu_leakiness) for i in six.moves.range(1, 4): with tf.variable_scope(('unit_2_%d' % i)): x = ops.conv('conv', x, 3, 64, 64, self._stride_arr(1), 'SAME', self.multi_gpu_mode) (x, train_op) = ops.batch_norm('bn', x, self.mode, 0.001, self.multi_gpu_mode) self.extra_train_ops.extend(train_op) x = ops.relu(x, self._relu_leakiness) with tf.variable_scope('unit_3_0'): x = tf.nn.max_pool(x, [1, 2, 2, 1], self._stride_arr(2), 'VALID', name='max_pool') x = ops.conv('conv', x, 3, 64, 128, self._stride_arr(1), 'SAME', self.multi_gpu_mode) (x, train_op) = ops.batch_norm('bn', x, self.mode, 0.001, self.multi_gpu_mode) self.extra_train_ops.extend(train_op) x = ops.relu(x, self._relu_leakiness) for i in six.moves.range(1, 4): with tf.variable_scope(('unit_3_%d' % i)): x = ops.conv('conv', x, 3, 128, 128, self._stride_arr(1), 'SAME', self.multi_gpu_mode) (x, train_op) = ops.batch_norm('bn', x, self.mode, 0.001, self.multi_gpu_mode) self.extra_train_ops.extend(train_op) x = ops.relu(x, self._relu_leakiness) with tf.variable_scope('unit_last'): x = ops.global_avg_pool(x) with tf.variable_scope('logit'): logits = ops.fc('fc1', x, batch_size, self.num_classes, self.multi_gpu_mode) self.logits = logits
def inference(self): ' Build the core model within the gragh. \n return:\n loggits before classifier\n ' batch_size = self.images.get_shape()[0] with tf.variable_scope('init'): x = self.images x = ops.conv('init_conv1', x, 3, 3, 16, self._stride_arr(1), 'SAME', self.multi_gpu_mode) (x, train_op) = ops.batch_norm('bn1', x, self.mode, 0.001, self.multi_gpu_mode) self.extra_train_ops.extend(train_op) x = ops.relu(x, self._relu_leakiness) x = ops.conv('init_conv2', x, 3, 16, 16, self._stride_arr(1), 'SAME', self.multi_gpu_mode) (x, train_op) = ops.batch_norm('bn2', x, self.mode, 0.001, self.multi_gpu_mode) self.extra_train_ops.extend(train_op) x = ops.relu(x, self._relu_leakiness) with tf.variable_scope('unit_1_0'): x = tf.nn.max_pool(x, [1, 2, 2, 1], self._stride_arr(2), 'VALID', name='max_pool') x = ops.conv('conv', x, 3, 16, 32, self._stride_arr(1), 'SAME', self.multi_gpu_mode) (x, train_op) = ops.batch_norm('bn', x, self.mode, 0.001, self.multi_gpu_mode) self.extra_train_ops.extend(train_op) x = ops.relu(x, self._relu_leakiness) for i in six.moves.range(1, 2): with tf.variable_scope(('unit_1_%d' % i)): x = ops.conv('conv', x, 3, 32, 32, self._stride_arr(1), 'SAME', self.multi_gpu_mode) (x, train_op) = ops.batch_norm('bn', x, self.mode, 0.001, self.multi_gpu_mode) self.extra_train_ops.extend(train_op) x = ops.relu(x, self._relu_leakiness) with tf.variable_scope('unit_2_0'): x = tf.nn.max_pool(x, [1, 2, 2, 1], self._stride_arr(2), 'VALID', name='max_pool') x = ops.conv('conv', x, 3, 32, 64, self._stride_arr(1), 'SAME', self.multi_gpu_mode) (x, train_op) = ops.batch_norm('bn', x, self.mode, 0.001, self.multi_gpu_mode) self.extra_train_ops.extend(train_op) x = ops.relu(x, self._relu_leakiness) for i in six.moves.range(1, 4): with tf.variable_scope(('unit_2_%d' % i)): x = ops.conv('conv', x, 3, 64, 64, self._stride_arr(1), 'SAME', self.multi_gpu_mode) (x, train_op) = ops.batch_norm('bn', x, self.mode, 0.001, self.multi_gpu_mode) self.extra_train_ops.extend(train_op) x = ops.relu(x, self._relu_leakiness) with tf.variable_scope('unit_3_0'): x = tf.nn.max_pool(x, [1, 2, 2, 1], self._stride_arr(2), 'VALID', name='max_pool') x = ops.conv('conv', x, 3, 64, 128, self._stride_arr(1), 'SAME', self.multi_gpu_mode) (x, train_op) = ops.batch_norm('bn', x, self.mode, 0.001, self.multi_gpu_mode) self.extra_train_ops.extend(train_op) x = ops.relu(x, self._relu_leakiness) for i in six.moves.range(1, 4): with tf.variable_scope(('unit_3_%d' % i)): x = ops.conv('conv', x, 3, 128, 128, self._stride_arr(1), 'SAME', self.multi_gpu_mode) (x, train_op) = ops.batch_norm('bn', x, self.mode, 0.001, self.multi_gpu_mode) self.extra_train_ops.extend(train_op) x = ops.relu(x, self._relu_leakiness) with tf.variable_scope('unit_last'): x = ops.global_avg_pool(x) with tf.variable_scope('logit'): logits = ops.fc('fc1', x, batch_size, self.num_classes, self.multi_gpu_mode) self.logits = logits<|docstring|>Build the core model within the gragh. return: loggits before classifier<|endoftext|>
21eb12df36788cdc6d8d479248d1cf77f0fa29e4dff815db35f9a3a6a665b731
def _float_feature(value): 'Returns a float_list from a float / double.' return tf.train.Feature(float_list=tf.train.FloatList(value=value))
Returns a float_list from a float / double.
get_features/tf_utils.py
_float_feature
kslin/miRNA_models
1
python
def _float_feature(value): return tf.train.Feature(float_list=tf.train.FloatList(value=value))
def _float_feature(value): return tf.train.Feature(float_list=tf.train.FloatList(value=value))<|docstring|>Returns a float_list from a float / double.<|endoftext|>
6836b86df4932aa6d2014bd06a309af0900856446ce02a065a277f5073101bf7
def _int64_feature(value): 'Returns an int64_list from a bool / enum / int / uint.' return tf.train.Feature(int64_list=tf.train.Int64List(value=value))
Returns an int64_list from a bool / enum / int / uint.
get_features/tf_utils.py
_int64_feature
kslin/miRNA_models
1
python
def _int64_feature(value): return tf.train.Feature(int64_list=tf.train.Int64List(value=value))
def _int64_feature(value): return tf.train.Feature(int64_list=tf.train.Int64List(value=value))<|docstring|>Returns an int64_list from a bool / enum / int / uint.<|endoftext|>
a879f13c6fa5ccc4c225bed4a57c7e0b68ced836e9614d282d8702528a3f47b8
def _bytes_feature(value): 'Returns a bytes_list from a string / byte.' return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
Returns a bytes_list from a string / byte.
get_features/tf_utils.py
_bytes_feature
kslin/miRNA_models
1
python
def _bytes_feature(value): return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def _bytes_feature(value): return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))<|docstring|>Returns a bytes_list from a string / byte.<|endoftext|>
29a920874c20d6e0e5c5476b30a823be32187dd2ff13b1ea44d8e595fd331019
def _string_feature(value): 'Returns a bytes_list from a list of strings.' return tf.train.Feature(bytes_list=tf.train.BytesList(value=value))
Returns a bytes_list from a list of strings.
get_features/tf_utils.py
_string_feature
kslin/miRNA_models
1
python
def _string_feature(value): return tf.train.Feature(bytes_list=tf.train.BytesList(value=value))
def _string_feature(value): return tf.train.Feature(bytes_list=tf.train.BytesList(value=value))<|docstring|>Returns a bytes_list from a list of strings.<|endoftext|>
5e1e1d76da7f5c6ba1114587d04f77c6a521e1fa8ee2a789739acfa7a2b5b2a2
def is_found_with_aho_corasick(secret, automaton): '\n :type secret: str\n\n :type automaton: ahocorasick.Automaton|None\n :param automaton: optional automaton for ignoring certain words.\n\n :rtype: bool\n Returns True if secret contains a word in the automaton.\n ' if (not automaton): return False try: next(automaton.iter(string=secret.lower())) return True except StopIteration: return False
:type secret: str :type automaton: ahocorasick.Automaton|None :param automaton: optional automaton for ignoring certain words. :rtype: bool Returns True if secret contains a word in the automaton.
detect_secrets/plugins/common/filters.py
is_found_with_aho_corasick
coaic/detect-secrets
46
python
def is_found_with_aho_corasick(secret, automaton): '\n :type secret: str\n\n :type automaton: ahocorasick.Automaton|None\n :param automaton: optional automaton for ignoring certain words.\n\n :rtype: bool\n Returns True if secret contains a word in the automaton.\n ' if (not automaton): return False try: next(automaton.iter(string=secret.lower())) return True except StopIteration: return False
def is_found_with_aho_corasick(secret, automaton): '\n :type secret: str\n\n :type automaton: ahocorasick.Automaton|None\n :param automaton: optional automaton for ignoring certain words.\n\n :rtype: bool\n Returns True if secret contains a word in the automaton.\n ' if (not automaton): return False try: next(automaton.iter(string=secret.lower())) return True except StopIteration: return False<|docstring|>:type secret: str :type automaton: ahocorasick.Automaton|None :param automaton: optional automaton for ignoring certain words. :rtype: bool Returns True if secret contains a word in the automaton.<|endoftext|>
78f2c572bcf3fdcaa4ca5f7b2a70d47910263d7a3f73977acfc9dad9700a73ca
def get_aho_corasick_helper(automaton): '\n Returns a function which determines if a word matches the\n input automaton.\n\n :type automaton: ahocorasick.Automaton\n ' def fn(secret): return is_found_with_aho_corasick(secret, automaton) return fn
Returns a function which determines if a word matches the input automaton. :type automaton: ahocorasick.Automaton
detect_secrets/plugins/common/filters.py
get_aho_corasick_helper
coaic/detect-secrets
46
python
def get_aho_corasick_helper(automaton): '\n Returns a function which determines if a word matches the\n input automaton.\n\n :type automaton: ahocorasick.Automaton\n ' def fn(secret): return is_found_with_aho_corasick(secret, automaton) return fn
def get_aho_corasick_helper(automaton): '\n Returns a function which determines if a word matches the\n input automaton.\n\n :type automaton: ahocorasick.Automaton\n ' def fn(secret): return is_found_with_aho_corasick(secret, automaton) return fn<|docstring|>Returns a function which determines if a word matches the input automaton. :type automaton: ahocorasick.Automaton<|endoftext|>
a4179b32802c1d55b294ec317279a250d0832d24037961952b54314a4765752b
def is_sequential_string(secret, *args): '\n :type secret: str\n\n :rtype: bool\n Returns True if string is sequential.\n ' sequences = ((((string.ascii_uppercase + string.ascii_uppercase) + string.digits) + '+/'), (((string.digits + string.ascii_uppercase) + string.ascii_uppercase) + '+/'), ((string.digits + string.ascii_uppercase) * 2), (string.digits * 2), (string.hexdigits.upper() + string.hexdigits.upper()), (string.ascii_uppercase + '=/')) uppercase = secret.upper() for sequential_string in sequences: if (uppercase in sequential_string): return True return False
:type secret: str :rtype: bool Returns True if string is sequential.
detect_secrets/plugins/common/filters.py
is_sequential_string
coaic/detect-secrets
46
python
def is_sequential_string(secret, *args): '\n :type secret: str\n\n :rtype: bool\n Returns True if string is sequential.\n ' sequences = ((((string.ascii_uppercase + string.ascii_uppercase) + string.digits) + '+/'), (((string.digits + string.ascii_uppercase) + string.ascii_uppercase) + '+/'), ((string.digits + string.ascii_uppercase) * 2), (string.digits * 2), (string.hexdigits.upper() + string.hexdigits.upper()), (string.ascii_uppercase + '=/')) uppercase = secret.upper() for sequential_string in sequences: if (uppercase in sequential_string): return True return False
def is_sequential_string(secret, *args): '\n :type secret: str\n\n :rtype: bool\n Returns True if string is sequential.\n ' sequences = ((((string.ascii_uppercase + string.ascii_uppercase) + string.digits) + '+/'), (((string.digits + string.ascii_uppercase) + string.ascii_uppercase) + '+/'), ((string.digits + string.ascii_uppercase) * 2), (string.digits * 2), (string.hexdigits.upper() + string.hexdigits.upper()), (string.ascii_uppercase + '=/')) uppercase = secret.upper() for sequential_string in sequences: if (uppercase in sequential_string): return True return False<|docstring|>:type secret: str :rtype: bool Returns True if string is sequential.<|endoftext|>
d5e658ddb572c733271e7cbc1230c802b82b55f2e7422788bcf36d15c58ab987
def is_potential_uuid(secret, *args): '\n Determines if a potential secret contains any UUIDs.\n\n :type secret: str\n\n :rtype: bool\n Returns True if the string has a UUID, false otherwise.\n ' return bool(_UUID_REGEX.search(secret))
Determines if a potential secret contains any UUIDs. :type secret: str :rtype: bool Returns True if the string has a UUID, false otherwise.
detect_secrets/plugins/common/filters.py
is_potential_uuid
coaic/detect-secrets
46
python
def is_potential_uuid(secret, *args): '\n Determines if a potential secret contains any UUIDs.\n\n :type secret: str\n\n :rtype: bool\n Returns True if the string has a UUID, false otherwise.\n ' return bool(_UUID_REGEX.search(secret))
def is_potential_uuid(secret, *args): '\n Determines if a potential secret contains any UUIDs.\n\n :type secret: str\n\n :rtype: bool\n Returns True if the string has a UUID, false otherwise.\n ' return bool(_UUID_REGEX.search(secret))<|docstring|>Determines if a potential secret contains any UUIDs. :type secret: str :rtype: bool Returns True if the string has a UUID, false otherwise.<|endoftext|>
73b778780ef8546f07251d113f5ecfe3b3f53e7ede40394214ef3cfaf143af3e
def is_likely_id_string(secret, line): '\n :type secret: str\n\n :type line: str\n :param line: Line context for the plaintext secret\n\n :rtype: bool\n Returns true if the secret could be an id, false otherwise.\n ' if (secret not in line): return False secret_index = line.index(secret) return bool(_ID_DETECTOR_REGEX.search(line, pos=0, endpos=secret_index))
:type secret: str :type line: str :param line: Line context for the plaintext secret :rtype: bool Returns true if the secret could be an id, false otherwise.
detect_secrets/plugins/common/filters.py
is_likely_id_string
coaic/detect-secrets
46
python
def is_likely_id_string(secret, line): '\n :type secret: str\n\n :type line: str\n :param line: Line context for the plaintext secret\n\n :rtype: bool\n Returns true if the secret could be an id, false otherwise.\n ' if (secret not in line): return False secret_index = line.index(secret) return bool(_ID_DETECTOR_REGEX.search(line, pos=0, endpos=secret_index))
def is_likely_id_string(secret, line): '\n :type secret: str\n\n :type line: str\n :param line: Line context for the plaintext secret\n\n :rtype: bool\n Returns true if the secret could be an id, false otherwise.\n ' if (secret not in line): return False secret_index = line.index(secret) return bool(_ID_DETECTOR_REGEX.search(line, pos=0, endpos=secret_index))<|docstring|>:type secret: str :type line: str :param line: Line context for the plaintext secret :rtype: bool Returns true if the secret could be an id, false otherwise.<|endoftext|>
5bd22ee32820e589599f1c4ce9023bba62cbba50b0c6357cf4d5bf2f6c351c38
def is_false_positive_with_line_context(secret, line, functions=DEFAULT_FALSE_POSITIVE_WITH_LINE_CONTEXT_HEURISTICS): '\n :type secret: str\n\n :type line: str\n :param line: plaintext line on which secret was found\n\n :type functions: Iterable[Callable]\n :param functions: list of heuristics to use\n\n :rtype: bool\n Returns True if any false-positive heuristic which considers the whole file line\n returns true.\n ' return any((func(secret, line) for func in functions))
:type secret: str :type line: str :param line: plaintext line on which secret was found :type functions: Iterable[Callable] :param functions: list of heuristics to use :rtype: bool Returns True if any false-positive heuristic which considers the whole file line returns true.
detect_secrets/plugins/common/filters.py
is_false_positive_with_line_context
coaic/detect-secrets
46
python
def is_false_positive_with_line_context(secret, line, functions=DEFAULT_FALSE_POSITIVE_WITH_LINE_CONTEXT_HEURISTICS): '\n :type secret: str\n\n :type line: str\n :param line: plaintext line on which secret was found\n\n :type functions: Iterable[Callable]\n :param functions: list of heuristics to use\n\n :rtype: bool\n Returns True if any false-positive heuristic which considers the whole file line\n returns true.\n ' return any((func(secret, line) for func in functions))
def is_false_positive_with_line_context(secret, line, functions=DEFAULT_FALSE_POSITIVE_WITH_LINE_CONTEXT_HEURISTICS): '\n :type secret: str\n\n :type line: str\n :param line: plaintext line on which secret was found\n\n :type functions: Iterable[Callable]\n :param functions: list of heuristics to use\n\n :rtype: bool\n Returns True if any false-positive heuristic which considers the whole file line\n returns true.\n ' return any((func(secret, line) for func in functions))<|docstring|>:type secret: str :type line: str :param line: plaintext line on which secret was found :type functions: Iterable[Callable] :param functions: list of heuristics to use :rtype: bool Returns True if any false-positive heuristic which considers the whole file line returns true.<|endoftext|>
d26428be73220d400c0b900f83d2188b9737189012577179c0e598dfc380dd17
def load_data(path_to_fixture, database='default'): '\n Create a function for loading fixture data.\n\n Rather than using the built-in `loaddata` command as-is, the\n returned function loads fixture data based on the current model\n state (in case a data migration needs to run in the middle of\n schema migrations).\n ' def do_it(apps, schema_editor): if (schema_editor.connection.alias == database): original_get_model = python._get_model try: def _get_model(model_identifier): try: return apps.get_model(model_identifier) except (LookupError, TypeError): msg = "Invalid model identifier: '{}' ".format(model_identifier) raise base.DeserializationError(msg) python._get_model = _get_model call_command('loaddata', path_to_fixture, database=database) finally: python._get_model = original_get_model return do_it
Create a function for loading fixture data. Rather than using the built-in `loaddata` command as-is, the returned function loads fixture data based on the current model state (in case a data migration needs to run in the middle of schema migrations).
django/sierra/utils/load_data.py
load_data
Miamiohlibs/catalog-api
19
python
def load_data(path_to_fixture, database='default'): '\n Create a function for loading fixture data.\n\n Rather than using the built-in `loaddata` command as-is, the\n returned function loads fixture data based on the current model\n state (in case a data migration needs to run in the middle of\n schema migrations).\n ' def do_it(apps, schema_editor): if (schema_editor.connection.alias == database): original_get_model = python._get_model try: def _get_model(model_identifier): try: return apps.get_model(model_identifier) except (LookupError, TypeError): msg = "Invalid model identifier: '{}' ".format(model_identifier) raise base.DeserializationError(msg) python._get_model = _get_model call_command('loaddata', path_to_fixture, database=database) finally: python._get_model = original_get_model return do_it
def load_data(path_to_fixture, database='default'): '\n Create a function for loading fixture data.\n\n Rather than using the built-in `loaddata` command as-is, the\n returned function loads fixture data based on the current model\n state (in case a data migration needs to run in the middle of\n schema migrations).\n ' def do_it(apps, schema_editor): if (schema_editor.connection.alias == database): original_get_model = python._get_model try: def _get_model(model_identifier): try: return apps.get_model(model_identifier) except (LookupError, TypeError): msg = "Invalid model identifier: '{}' ".format(model_identifier) raise base.DeserializationError(msg) python._get_model = _get_model call_command('loaddata', path_to_fixture, database=database) finally: python._get_model = original_get_model return do_it<|docstring|>Create a function for loading fixture data. Rather than using the built-in `loaddata` command as-is, the returned function loads fixture data based on the current model state (in case a data migration needs to run in the middle of schema migrations).<|endoftext|>
b36ec6f1359ea0421c8032bfcac4e15d59b037ea09b3a4a63bd7b434b1e623ae
def __init__(self, seed=None): '\n __init__(self, seed=None)\n ' if ((seed is not None) and isinstance(seed, int)): np.random.seed(seed)
__init__(self, seed=None)
pywinEA/imputation/dynamic.py
__init__
FernandoGaGu/pywinEA
1
python
def : '\n \n ' if ((seed is not None) and isinstance(seed, int)): np.random.seed(seed)
def : '\n \n ' if ((seed is not None) and isinstance(seed, int)): np.random.seed(seed)<|docstring|>__init__(self, seed=None)<|endoftext|>
5bf41ae7831187058c724c6982b6c36dad47b1e19fe57890fe24ea4798817639
def impute(self, data: np.ndarray, y: np.ndarray): '\n Function that receives a dataset with missing values and replaces the values filling first in a forward\n way, that is, replacing missing values with the previous known value. Additionally, it may be the case\n in which a missing value is in the first row, therefore, after filling it using a forward strategy, it\n applies a backward filling to avoid the possible presence of missing values. Each time the impute()\n method is called the rows are shuffled randomly. The dataset is returned in the same order in which\n it is received.\n\n Parameters\n -------------\n :param data: 2d-array\n Predictor variables with missing values\n :param y: 1d-array\n Class labels\n\n Returns\n ----------\n :return: 2d-array\n Dataset without imputation values.\n ' idx = [n for n in range(data.shape[0])] data = np.hstack((data, np.array(idx).reshape(len(idx), 1))) np.random.shuffle(data) data = DynamicValue._forward_fill(data) data = DynamicValue._forward_fill(data[::(- 1)]) data = data[np.argsort(data[(:, (data.shape[1] - 1))])] return data[(:, :(data.shape[1] - 1))]
Function that receives a dataset with missing values and replaces the values filling first in a forward way, that is, replacing missing values with the previous known value. Additionally, it may be the case in which a missing value is in the first row, therefore, after filling it using a forward strategy, it applies a backward filling to avoid the possible presence of missing values. Each time the impute() method is called the rows are shuffled randomly. The dataset is returned in the same order in which it is received. Parameters ------------- :param data: 2d-array Predictor variables with missing values :param y: 1d-array Class labels Returns ---------- :return: 2d-array Dataset without imputation values.
pywinEA/imputation/dynamic.py
impute
FernandoGaGu/pywinEA
1
python
def impute(self, data: np.ndarray, y: np.ndarray): '\n Function that receives a dataset with missing values and replaces the values filling first in a forward\n way, that is, replacing missing values with the previous known value. Additionally, it may be the case\n in which a missing value is in the first row, therefore, after filling it using a forward strategy, it\n applies a backward filling to avoid the possible presence of missing values. Each time the impute()\n method is called the rows are shuffled randomly. The dataset is returned in the same order in which\n it is received.\n\n Parameters\n -------------\n :param data: 2d-array\n Predictor variables with missing values\n :param y: 1d-array\n Class labels\n\n Returns\n ----------\n :return: 2d-array\n Dataset without imputation values.\n ' idx = [n for n in range(data.shape[0])] data = np.hstack((data, np.array(idx).reshape(len(idx), 1))) np.random.shuffle(data) data = DynamicValue._forward_fill(data) data = DynamicValue._forward_fill(data[::(- 1)]) data = data[np.argsort(data[(:, (data.shape[1] - 1))])] return data[(:, :(data.shape[1] - 1))]
def impute(self, data: np.ndarray, y: np.ndarray): '\n Function that receives a dataset with missing values and replaces the values filling first in a forward\n way, that is, replacing missing values with the previous known value. Additionally, it may be the case\n in which a missing value is in the first row, therefore, after filling it using a forward strategy, it\n applies a backward filling to avoid the possible presence of missing values. Each time the impute()\n method is called the rows are shuffled randomly. The dataset is returned in the same order in which\n it is received.\n\n Parameters\n -------------\n :param data: 2d-array\n Predictor variables with missing values\n :param y: 1d-array\n Class labels\n\n Returns\n ----------\n :return: 2d-array\n Dataset without imputation values.\n ' idx = [n for n in range(data.shape[0])] data = np.hstack((data, np.array(idx).reshape(len(idx), 1))) np.random.shuffle(data) data = DynamicValue._forward_fill(data) data = DynamicValue._forward_fill(data[::(- 1)]) data = data[np.argsort(data[(:, (data.shape[1] - 1))])] return data[(:, :(data.shape[1] - 1))]<|docstring|>Function that receives a dataset with missing values and replaces the values filling first in a forward way, that is, replacing missing values with the previous known value. Additionally, it may be the case in which a missing value is in the first row, therefore, after filling it using a forward strategy, it applies a backward filling to avoid the possible presence of missing values. Each time the impute() method is called the rows are shuffled randomly. The dataset is returned in the same order in which it is received. Parameters ------------- :param data: 2d-array Predictor variables with missing values :param y: 1d-array Class labels Returns ---------- :return: 2d-array Dataset without imputation values.<|endoftext|>
6c893fec800a1ccb2c4027c5e15827c09d83ed9e1c5b93087cee65c08ad2ab92
@staticmethod def _forward_fill(data: np.ndarray): '\n Function that replaces missing values with the value of the previous instance.\n\n Parameters\n -------------\n :param data: 2d-array\n Dataset with missing values.\n\n Returns\n -----------\n :return: 2d-array\n Dataset filling using a forward strategy\n ' last_values = None for row in data: if (last_values is not None): idx = np.isnan(row) row[idx] = last_values[idx] last_values = row return data
Function that replaces missing values with the value of the previous instance. Parameters ------------- :param data: 2d-array Dataset with missing values. Returns ----------- :return: 2d-array Dataset filling using a forward strategy
pywinEA/imputation/dynamic.py
_forward_fill
FernandoGaGu/pywinEA
1
python
@staticmethod def _forward_fill(data: np.ndarray): '\n Function that replaces missing values with the value of the previous instance.\n\n Parameters\n -------------\n :param data: 2d-array\n Dataset with missing values.\n\n Returns\n -----------\n :return: 2d-array\n Dataset filling using a forward strategy\n ' last_values = None for row in data: if (last_values is not None): idx = np.isnan(row) row[idx] = last_values[idx] last_values = row return data
@staticmethod def _forward_fill(data: np.ndarray): '\n Function that replaces missing values with the value of the previous instance.\n\n Parameters\n -------------\n :param data: 2d-array\n Dataset with missing values.\n\n Returns\n -----------\n :return: 2d-array\n Dataset filling using a forward strategy\n ' last_values = None for row in data: if (last_values is not None): idx = np.isnan(row) row[idx] = last_values[idx] last_values = row return data<|docstring|>Function that replaces missing values with the value of the previous instance. Parameters ------------- :param data: 2d-array Dataset with missing values. Returns ----------- :return: 2d-array Dataset filling using a forward strategy<|endoftext|>
42abdd192e7994411d279ceac0c3dcd324d851a98911dd1c8596e3a61ee1462e
def vgg11(pretrained=False, **kwargs): 'VGG 11-layer model (configuration "A")\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = VGG(make_layers(cfg['A']), **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['vgg11'])) return model
VGG 11-layer model (configuration "A") Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
Yolov1_pytorch/models/net.py
vgg11
davidpqc1231/AnnotatedNetworkModelGit
274
python
def vgg11(pretrained=False, **kwargs): 'VGG 11-layer model (configuration "A")\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = VGG(make_layers(cfg['A']), **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['vgg11'])) return model
def vgg11(pretrained=False, **kwargs): 'VGG 11-layer model (configuration "A")\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = VGG(make_layers(cfg['A']), **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['vgg11'])) return model<|docstring|>VGG 11-layer model (configuration "A") Args: pretrained (bool): If True, returns a model pre-trained on ImageNet<|endoftext|>
6f725e9b9fe3b8fc8f15c6ae1761268e794947f384548c9f5a2223203310b391
def vgg11_bn(pretrained=False, **kwargs): 'VGG 11-layer model (configuration "A") with batch normalization\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = VGG(make_layers(cfg['A'], batch_norm=True), **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['vgg11_bn'])) return model
VGG 11-layer model (configuration "A") with batch normalization Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
Yolov1_pytorch/models/net.py
vgg11_bn
davidpqc1231/AnnotatedNetworkModelGit
274
python
def vgg11_bn(pretrained=False, **kwargs): 'VGG 11-layer model (configuration "A") with batch normalization\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = VGG(make_layers(cfg['A'], batch_norm=True), **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['vgg11_bn'])) return model
def vgg11_bn(pretrained=False, **kwargs): 'VGG 11-layer model (configuration "A") with batch normalization\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = VGG(make_layers(cfg['A'], batch_norm=True), **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['vgg11_bn'])) return model<|docstring|>VGG 11-layer model (configuration "A") with batch normalization Args: pretrained (bool): If True, returns a model pre-trained on ImageNet<|endoftext|>
afa91b205f3e110f09f1883a89510efad68e575d7ae63cea3d013eb3f5ebe4b4
def vgg13(pretrained=False, **kwargs): 'VGG 13-layer model (configuration "B")\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = VGG(make_layers(cfg['B']), **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['vgg13'])) return model
VGG 13-layer model (configuration "B") Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
Yolov1_pytorch/models/net.py
vgg13
davidpqc1231/AnnotatedNetworkModelGit
274
python
def vgg13(pretrained=False, **kwargs): 'VGG 13-layer model (configuration "B")\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = VGG(make_layers(cfg['B']), **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['vgg13'])) return model
def vgg13(pretrained=False, **kwargs): 'VGG 13-layer model (configuration "B")\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = VGG(make_layers(cfg['B']), **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['vgg13'])) return model<|docstring|>VGG 13-layer model (configuration "B") Args: pretrained (bool): If True, returns a model pre-trained on ImageNet<|endoftext|>
e8ade1fc61224077854c11d11cc3c6c1960195b2a497d739a8e12fa5c934e2ae
def vgg13_bn(pretrained=False, **kwargs): 'VGG 13-layer model (configuration "B") with batch normalization\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = VGG(make_layers(cfg['B'], batch_norm=True), **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['vgg13_bn'])) return model
VGG 13-layer model (configuration "B") with batch normalization Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
Yolov1_pytorch/models/net.py
vgg13_bn
davidpqc1231/AnnotatedNetworkModelGit
274
python
def vgg13_bn(pretrained=False, **kwargs): 'VGG 13-layer model (configuration "B") with batch normalization\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = VGG(make_layers(cfg['B'], batch_norm=True), **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['vgg13_bn'])) return model
def vgg13_bn(pretrained=False, **kwargs): 'VGG 13-layer model (configuration "B") with batch normalization\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = VGG(make_layers(cfg['B'], batch_norm=True), **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['vgg13_bn'])) return model<|docstring|>VGG 13-layer model (configuration "B") with batch normalization Args: pretrained (bool): If True, returns a model pre-trained on ImageNet<|endoftext|>
e629823a99c532869872fbf1ff2db7e91337e876d4e61aa09cd9a6445a095ad8
def vgg16(pretrained=False, **kwargs): 'VGG 16-layer model (configuration "D")\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = VGG(make_layers(cfg['D']), **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['vgg16'])) return model
VGG 16-layer model (configuration "D") Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
Yolov1_pytorch/models/net.py
vgg16
davidpqc1231/AnnotatedNetworkModelGit
274
python
def vgg16(pretrained=False, **kwargs): 'VGG 16-layer model (configuration "D")\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = VGG(make_layers(cfg['D']), **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['vgg16'])) return model
def vgg16(pretrained=False, **kwargs): 'VGG 16-layer model (configuration "D")\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = VGG(make_layers(cfg['D']), **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['vgg16'])) return model<|docstring|>VGG 16-layer model (configuration "D") Args: pretrained (bool): If True, returns a model pre-trained on ImageNet<|endoftext|>
9d697f3c4b5dec0dbc794393186b1fa3d3495e78dde29f95f970b3c976dbe1ac
def vgg16_bn(pretrained=False, **kwargs): 'VGG 16-layer model (configuration "D") with batch normalization\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = VGG(make_layers(cfg['D'], batch_norm=True), **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['vgg16_bn'])) return model
VGG 16-layer model (configuration "D") with batch normalization Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
Yolov1_pytorch/models/net.py
vgg16_bn
davidpqc1231/AnnotatedNetworkModelGit
274
python
def vgg16_bn(pretrained=False, **kwargs): 'VGG 16-layer model (configuration "D") with batch normalization\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = VGG(make_layers(cfg['D'], batch_norm=True), **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['vgg16_bn'])) return model
def vgg16_bn(pretrained=False, **kwargs): 'VGG 16-layer model (configuration "D") with batch normalization\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = VGG(make_layers(cfg['D'], batch_norm=True), **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['vgg16_bn'])) return model<|docstring|>VGG 16-layer model (configuration "D") with batch normalization Args: pretrained (bool): If True, returns a model pre-trained on ImageNet<|endoftext|>
9565d6ecbf40a805a171c0f30098ffc7fe76c3b74fa1b2f07b212989bb06e35f
def vgg19(pretrained=False, **kwargs): 'VGG 19-layer model (configuration "E")\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = VGG(make_layers(cfg['E']), **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['vgg19'])) return model
VGG 19-layer model (configuration "E") Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
Yolov1_pytorch/models/net.py
vgg19
davidpqc1231/AnnotatedNetworkModelGit
274
python
def vgg19(pretrained=False, **kwargs): 'VGG 19-layer model (configuration "E")\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = VGG(make_layers(cfg['E']), **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['vgg19'])) return model
def vgg19(pretrained=False, **kwargs): 'VGG 19-layer model (configuration "E")\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = VGG(make_layers(cfg['E']), **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['vgg19'])) return model<|docstring|>VGG 19-layer model (configuration "E") Args: pretrained (bool): If True, returns a model pre-trained on ImageNet<|endoftext|>
ce99d96a10e251bf9c73bcb4def32bb027b3474d0f90b7da5501fc22e7ecd05b
def vgg19_bn(pretrained=False, **kwargs): "VGG 19-layer model (configuration 'E') with batch normalization\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n " model = VGG(make_layers(cfg['E'], batch_norm=True), **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['vgg19_bn'])) return model
VGG 19-layer model (configuration 'E') with batch normalization Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
Yolov1_pytorch/models/net.py
vgg19_bn
davidpqc1231/AnnotatedNetworkModelGit
274
python
def vgg19_bn(pretrained=False, **kwargs): "VGG 19-layer model (configuration 'E') with batch normalization\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n " model = VGG(make_layers(cfg['E'], batch_norm=True), **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['vgg19_bn'])) return model
def vgg19_bn(pretrained=False, **kwargs): "VGG 19-layer model (configuration 'E') with batch normalization\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n " model = VGG(make_layers(cfg['E'], batch_norm=True), **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['vgg19_bn'])) return model<|docstring|>VGG 19-layer model (configuration 'E') with batch normalization Args: pretrained (bool): If True, returns a model pre-trained on ImageNet<|endoftext|>