hexsha
stringlengths
40
40
size
int64
2
1.02M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
245
max_stars_repo_name
stringlengths
6
130
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
245
max_issues_repo_name
stringlengths
6
130
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
245
max_forks_repo_name
stringlengths
6
130
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
2
1.02M
avg_line_length
float64
1
417k
max_line_length
int64
1
987k
alphanum_fraction
float64
0
1
content_no_comment
stringlengths
0
1.01M
is_comment_constant_removed
bool
1 class
is_sharp_comment_removed
bool
1 class
f7178a5f0eaaff23bb2efef24ecd4ae204c5ee9e
638
py
Python
src/django_backend_api/manage.py
Adityaraj1711/django-backend-architecture
7f3c270af0cb5dd2ebc097c7436a4958cd48ff7c
[ "MIT" ]
25
2020-04-28T19:25:28.000Z
2021-07-04T17:24:35.000Z
src/django_backend_api/manage.py
Adityaraj1711/django-backend-architecture
7f3c270af0cb5dd2ebc097c7436a4958cd48ff7c
[ "MIT" ]
13
2020-08-05T22:40:37.000Z
2022-03-12T00:24:36.000Z
src/django_backend_api/manage.py
Adityaraj1711/django-backend-architecture
7f3c270af0cb5dd2ebc097c7436a4958cd48ff7c
[ "MIT" ]
2
2020-10-29T13:10:01.000Z
2021-11-22T01:55:14.000Z
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_backend_api.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main()
29
82
0.688088
import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_backend_api.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main()
true
true
f7178a80bd5a4eb44808ea505c773373aa6ce545
102
py
Python
example.py
CJSmekens/code-refinery-bq-1
12cf67033e82176da665156037204eb405a0f6a7
[ "Apache-2.0" ]
null
null
null
example.py
CJSmekens/code-refinery-bq-1
12cf67033e82176da665156037204eb405a0f6a7
[ "Apache-2.0" ]
2
2021-06-07T10:01:32.000Z
2021-06-07T10:10:18.000Z
example.py
CJSmekens/code-refinery-bq-1
12cf67033e82176da665156037204eb405a0f6a7
[ "Apache-2.0" ]
1
2021-06-07T09:53:19.000Z
2021-06-07T09:53:19.000Z
def add(a,b): return a + b def subtract(a,b): return a - b def product(a,b): return a * b
11.333333
18
0.558824
def add(a,b): return a + b def subtract(a,b): return a - b def product(a,b): return a * b
true
true
f7178af25c554b1c64de2dc78db065ca48b7edd5
10,521
py
Python
micro_app_sdk/model/ops_automation/job_tasks_pb2.py
easyopsapis/easyops-api-python
adf6e3bad33fa6266b5fa0a449dd4ac42f8447d0
[ "Apache-2.0" ]
5
2019-07-31T04:11:05.000Z
2021-01-07T03:23:20.000Z
micro_app_sdk/model/ops_automation/job_tasks_pb2.py
easyopsapis/easyops-api-python
adf6e3bad33fa6266b5fa0a449dd4ac42f8447d0
[ "Apache-2.0" ]
null
null
null
micro_app_sdk/model/ops_automation/job_tasks_pb2.py
easyopsapis/easyops-api-python
adf6e3bad33fa6266b5fa0a449dd4ac42f8447d0
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: job_tasks.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from micro_app_sdk.model.ops_automation import mail_info_pb2 as micro__app__sdk_dot_model_dot_ops__automation_dot_mail__info__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='job_tasks.proto', package='ops_automation', syntax='proto3', serialized_options=_b('ZHgo.easyops.local/contracts/protorepo-models/easyops/model/ops_automation'), serialized_pb=_b('\n\x0fjob_tasks.proto\x12\x0eops_automation\x1a\x32micro_app_sdk/model/ops_automation/mail_info.proto\"\x82\x03\n\x08JobTasks\x12\n\n\x02id\x18\x01 \x01(\t\x12\r\n\x05jobId\x18\x02 \x01(\t\x12\x0f\n\x07jobName\x18\x03 \x01(\t\x12\x10\n\x08menuName\x18\x04 \x01(\t\x12\x0e\n\x06\x65xecId\x18\x05 \x01(\t\x12\x14\n\x0cresourceType\x18\x06 \x01(\t\x12\x12\n\nresourceId\x18\x07 \x01(\t\x12\x13\n\x0bresourceVId\x18\x08 \x01(\t\x12\x15\n\rresourceVName\x18\t \x01(\t\x12\x0f\n\x07trigger\x18\n \x01(\t\x12\x10\n\x08\x65xecUser\x18\x0b \x01(\t\x12\r\n\x05hosts\x18\x0c \x03(\t\x12\x0e\n\x06status\x18\r \x01(\t\x12&\n\x04mail\x18\x0e \x01(\x0b\x32\x18.ops_automation.MailInfo\x12\x13\n\x0bsuccessRate\x18\x0f \x01(\x02\x12\r\n\x05\x65rror\x18\x10 \x01(\t\x12\x12\n\ncreateTime\x18\x11 \x01(\t\x12\x12\n\nupdateTime\x18\x12 \x01(\t\x12\x0f\n\x07\x63reator\x18\x13 \x01(\t\x12\x0b\n\x03org\x18\x14 \x01(\x05\x42JZHgo.easyops.local/contracts/protorepo-models/easyops/model/ops_automationb\x06proto3') , dependencies=[micro__app__sdk_dot_model_dot_ops__automation_dot_mail__info__pb2.DESCRIPTOR,]) _JOBTASKS = _descriptor.Descriptor( name='JobTasks', full_name='ops_automation.JobTasks', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='id', full_name='ops_automation.JobTasks.id', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='jobId', full_name='ops_automation.JobTasks.jobId', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='jobName', full_name='ops_automation.JobTasks.jobName', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='menuName', full_name='ops_automation.JobTasks.menuName', index=3, number=4, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='execId', full_name='ops_automation.JobTasks.execId', index=4, number=5, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='resourceType', full_name='ops_automation.JobTasks.resourceType', index=5, number=6, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='resourceId', full_name='ops_automation.JobTasks.resourceId', index=6, number=7, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='resourceVId', full_name='ops_automation.JobTasks.resourceVId', index=7, number=8, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='resourceVName', full_name='ops_automation.JobTasks.resourceVName', index=8, number=9, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='trigger', full_name='ops_automation.JobTasks.trigger', index=9, number=10, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='execUser', full_name='ops_automation.JobTasks.execUser', index=10, number=11, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='hosts', full_name='ops_automation.JobTasks.hosts', index=11, number=12, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='status', full_name='ops_automation.JobTasks.status', index=12, number=13, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='mail', full_name='ops_automation.JobTasks.mail', index=13, number=14, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='successRate', full_name='ops_automation.JobTasks.successRate', index=14, number=15, type=2, cpp_type=6, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='error', full_name='ops_automation.JobTasks.error', index=15, number=16, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='createTime', full_name='ops_automation.JobTasks.createTime', index=16, number=17, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='updateTime', full_name='ops_automation.JobTasks.updateTime', index=17, number=18, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='creator', full_name='ops_automation.JobTasks.creator', index=18, number=19, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='org', full_name='ops_automation.JobTasks.org', index=19, number=20, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=88, serialized_end=474, ) _JOBTASKS.fields_by_name['mail'].message_type = micro__app__sdk_dot_model_dot_ops__automation_dot_mail__info__pb2._MAILINFO DESCRIPTOR.message_types_by_name['JobTasks'] = _JOBTASKS _sym_db.RegisterFileDescriptor(DESCRIPTOR) JobTasks = _reflection.GeneratedProtocolMessageType('JobTasks', (_message.Message,), { 'DESCRIPTOR' : _JOBTASKS, '__module__' : 'job_tasks_pb2' # @@protoc_insertion_point(class_scope:ops_automation.JobTasks) }) _sym_db.RegisterMessage(JobTasks) DESCRIPTOR._options = None # @@protoc_insertion_point(module_scope)
50.581731
1,012
0.737763
import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database _sym_db = _symbol_database.Default() from micro_app_sdk.model.ops_automation import mail_info_pb2 as micro__app__sdk_dot_model_dot_ops__automation_dot_mail__info__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='job_tasks.proto', package='ops_automation', syntax='proto3', serialized_options=_b('ZHgo.easyops.local/contracts/protorepo-models/easyops/model/ops_automation'), serialized_pb=_b('\n\x0fjob_tasks.proto\x12\x0eops_automation\x1a\x32micro_app_sdk/model/ops_automation/mail_info.proto\"\x82\x03\n\x08JobTasks\x12\n\n\x02id\x18\x01 \x01(\t\x12\r\n\x05jobId\x18\x02 \x01(\t\x12\x0f\n\x07jobName\x18\x03 \x01(\t\x12\x10\n\x08menuName\x18\x04 \x01(\t\x12\x0e\n\x06\x65xecId\x18\x05 \x01(\t\x12\x14\n\x0cresourceType\x18\x06 \x01(\t\x12\x12\n\nresourceId\x18\x07 \x01(\t\x12\x13\n\x0bresourceVId\x18\x08 \x01(\t\x12\x15\n\rresourceVName\x18\t \x01(\t\x12\x0f\n\x07trigger\x18\n \x01(\t\x12\x10\n\x08\x65xecUser\x18\x0b \x01(\t\x12\r\n\x05hosts\x18\x0c \x03(\t\x12\x0e\n\x06status\x18\r \x01(\t\x12&\n\x04mail\x18\x0e \x01(\x0b\x32\x18.ops_automation.MailInfo\x12\x13\n\x0bsuccessRate\x18\x0f \x01(\x02\x12\r\n\x05\x65rror\x18\x10 \x01(\t\x12\x12\n\ncreateTime\x18\x11 \x01(\t\x12\x12\n\nupdateTime\x18\x12 \x01(\t\x12\x0f\n\x07\x63reator\x18\x13 \x01(\t\x12\x0b\n\x03org\x18\x14 \x01(\x05\x42JZHgo.easyops.local/contracts/protorepo-models/easyops/model/ops_automationb\x06proto3') , dependencies=[micro__app__sdk_dot_model_dot_ops__automation_dot_mail__info__pb2.DESCRIPTOR,]) _JOBTASKS = _descriptor.Descriptor( name='JobTasks', full_name='ops_automation.JobTasks', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='id', full_name='ops_automation.JobTasks.id', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='jobId', full_name='ops_automation.JobTasks.jobId', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='jobName', full_name='ops_automation.JobTasks.jobName', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='menuName', full_name='ops_automation.JobTasks.menuName', index=3, number=4, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='execId', full_name='ops_automation.JobTasks.execId', index=4, number=5, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='resourceType', full_name='ops_automation.JobTasks.resourceType', index=5, number=6, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='resourceId', full_name='ops_automation.JobTasks.resourceId', index=6, number=7, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='resourceVId', full_name='ops_automation.JobTasks.resourceVId', index=7, number=8, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='resourceVName', full_name='ops_automation.JobTasks.resourceVName', index=8, number=9, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='trigger', full_name='ops_automation.JobTasks.trigger', index=9, number=10, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='execUser', full_name='ops_automation.JobTasks.execUser', index=10, number=11, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='hosts', full_name='ops_automation.JobTasks.hosts', index=11, number=12, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='status', full_name='ops_automation.JobTasks.status', index=12, number=13, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='mail', full_name='ops_automation.JobTasks.mail', index=13, number=14, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='successRate', full_name='ops_automation.JobTasks.successRate', index=14, number=15, type=2, cpp_type=6, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='error', full_name='ops_automation.JobTasks.error', index=15, number=16, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='createTime', full_name='ops_automation.JobTasks.createTime', index=16, number=17, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='updateTime', full_name='ops_automation.JobTasks.updateTime', index=17, number=18, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='creator', full_name='ops_automation.JobTasks.creator', index=18, number=19, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='org', full_name='ops_automation.JobTasks.org', index=19, number=20, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=88, serialized_end=474, ) _JOBTASKS.fields_by_name['mail'].message_type = micro__app__sdk_dot_model_dot_ops__automation_dot_mail__info__pb2._MAILINFO DESCRIPTOR.message_types_by_name['JobTasks'] = _JOBTASKS _sym_db.RegisterFileDescriptor(DESCRIPTOR) JobTasks = _reflection.GeneratedProtocolMessageType('JobTasks', (_message.Message,), { 'DESCRIPTOR' : _JOBTASKS, '__module__' : 'job_tasks_pb2' # @@protoc_insertion_point(class_scope:ops_automation.JobTasks) }) _sym_db.RegisterMessage(JobTasks) DESCRIPTOR._options = None # @@protoc_insertion_point(module_scope)
true
true
f7178bb0eb777f6aea029f4307dd32ff4cc85674
2,500
py
Python
mobilecoind/strategies/balances.py
mccobr/mobilecoin
cd7753a0aed838097b456d230151fb34e8cff034
[ "Apache-2.0" ]
2
2021-03-13T04:41:04.000Z
2021-03-13T04:42:37.000Z
mobilecoind/strategies/balances.py
mccobr/mobilecoin
cd7753a0aed838097b456d230151fb34e8cff034
[ "Apache-2.0" ]
292
2020-10-22T00:34:35.000Z
2022-03-29T09:29:14.000Z
mobilecoind/strategies/balances.py
mccobr/mobilecoin
cd7753a0aed838097b456d230151fb34e8cff034
[ "Apache-2.0" ]
1
2022-03-26T20:34:00.000Z
2022-03-26T20:34:00.000Z
#!/usr/bin/env python3 # Copyright (c) 2018-2021 The MobileCoin Foundation """ The purpose of this script is to print the balances for all keys in a given account directory. Example setup and usage: ``` python3 balances.py --key-dir ../../../target/sample_data/master/keys/ ``` """ import argparse import grpc import mobilecoind_api_pb2 import mobilecoind_api_pb2_grpc import os from accounts import connect, load_key_and_register from google.protobuf.empty_pb2 import Empty def parse_args() -> argparse.ArgumentParser: parser = argparse.ArgumentParser() parser.add_argument("--mobilecoind-host", default="localhost", type=str, help="Mobilecoind host") parser.add_argument("--mobilecoind-port", default="4444", type=str, help="Mobilecoind port") parser.add_argument("--key-dir", required=True, type=str, help="Path to account key dir") parser.add_argument("--prune", action="store_true", help="Prune key files for accounts with 0 balance") return parser.parse_args() if __name__ == '__main__': args = parse_args() print(args) stub = connect(args.mobilecoind_host, args.mobilecoind_port) block_count = stub.GetLedgerInfo(Empty()).block_count total = 0 for keyfile in sorted( filter(lambda x: x.endswith(".json"), os.listdir(args.key_dir))): print(keyfile) account_data = load_key_and_register( os.path.join(args.key_dir, keyfile), stub) # Get starting balance request = mobilecoind_api_pb2.GetMonitorStatusRequest(monitor_id=account_data.monitor_id) monitor_block = stub.GetMonitorStatus(request).status.next_block if block_count != monitor_block: print(f"\tAccount not synced.") else: resp = stub.GetBalance( mobilecoind_api_pb2.GetBalanceRequest(monitor_id=account_data.monitor_id)) balance = resp.balance total += balance print(f"\tBalance: {resp.balance:,}") # Remove balances of 0 FIXME: MC-367 also from mobilecoind wallet if int(balance) == 0 and args.prune: os.remove(os.path.join(args.key_dir, keyfile)) print(f"Total balance of key collection: {total:,} PicoMob")
34.246575
97
0.6156
import argparse import grpc import mobilecoind_api_pb2 import mobilecoind_api_pb2_grpc import os from accounts import connect, load_key_and_register from google.protobuf.empty_pb2 import Empty def parse_args() -> argparse.ArgumentParser: parser = argparse.ArgumentParser() parser.add_argument("--mobilecoind-host", default="localhost", type=str, help="Mobilecoind host") parser.add_argument("--mobilecoind-port", default="4444", type=str, help="Mobilecoind port") parser.add_argument("--key-dir", required=True, type=str, help="Path to account key dir") parser.add_argument("--prune", action="store_true", help="Prune key files for accounts with 0 balance") return parser.parse_args() if __name__ == '__main__': args = parse_args() print(args) stub = connect(args.mobilecoind_host, args.mobilecoind_port) block_count = stub.GetLedgerInfo(Empty()).block_count total = 0 for keyfile in sorted( filter(lambda x: x.endswith(".json"), os.listdir(args.key_dir))): print(keyfile) account_data = load_key_and_register( os.path.join(args.key_dir, keyfile), stub) request = mobilecoind_api_pb2.GetMonitorStatusRequest(monitor_id=account_data.monitor_id) monitor_block = stub.GetMonitorStatus(request).status.next_block if block_count != monitor_block: print(f"\tAccount not synced.") else: resp = stub.GetBalance( mobilecoind_api_pb2.GetBalanceRequest(monitor_id=account_data.monitor_id)) balance = resp.balance total += balance print(f"\tBalance: {resp.balance:,}") if int(balance) == 0 and args.prune: os.remove(os.path.join(args.key_dir, keyfile)) print(f"Total balance of key collection: {total:,} PicoMob")
true
true
f7178ca40551efa85c6e00fccc36031532a0273f
2,864
py
Python
DataManagement.py
DonCammne/OpenSeesPyAssistant
f380f0f2a2f3d1336320bd8d26fa5efe00a12134
[ "MIT" ]
null
null
null
DataManagement.py
DonCammne/OpenSeesPyAssistant
f380f0f2a2f3d1336320bd8d26fa5efe00a12134
[ "MIT" ]
null
null
null
DataManagement.py
DonCammne/OpenSeesPyAssistant
f380f0f2a2f3d1336320bd8d26fa5efe00a12134
[ "MIT" ]
null
null
null
""" Module with the parent abstract class DataManagement. \n Carmine Schipani, 2021 """ from abc import ABC, abstractmethod from OpenSeesPyAssistant.ErrorHandling import * import numpy as np class DataManagement(ABC): """ Abstract parent class for data management. Using the associated MATLAB class \n LOAD_CLASS.m \n for the postprocessing in MATLAB, allowing for simpler and more reliable data management because the parameters from the OpenSeesPy analysis are imported automatically. """ def SaveData(self, f): """ Function that lists in the command window and saves in a opened file text "f" the data from the "self" class that calls it. Example: call this function after this line: \n with open(FileName, 'w') as f: @param f (io.TextIOWrapper): Opened file to write into @exception WrongDimension: The number of lists in the list self.data needs to be 2 """ if len(self.data[0]) != 2: raise WrongDimension() delimiter = "##############################" # 30 times # col_delimiter = "\t" # tab for data_line in self.data: f.write('\n') for col in data_line: if type(col) == np.ndarray: tmp_str = np.array_str(col, max_line_width = np.inf) else: tmp_str = str(col) f.write(tmp_str) f.write(col_delimiter) f.write('\n') f.write('NEW INFO SECTION DELIMITER \t') f.write(delimiter) @abstractmethod def ShowInfo(self): """ Abstract method that shows the data stored in the class in the command window. In some cases, it's possible to plot some information (for example the curve of the material model). """ pass @abstractmethod def ReInit(self): """ Abstract method that computes the value of the parameters with respect of the arguments. \n Use after changing the value of argument inside the class (to update the values accordingly). \n This function can be very useful in combination with the function "deepcopy()" from the module "copy". \n Be careful that the parameter self.Initialized is also copied, thus it is safer to copy the class before the method that calls the actual OpenSees commands (and initialise the object). """ pass @abstractmethod def UpdateStoredData(self): """ Abstract method used to define and update the self.data member variable. \n This member variable (self.data) is a list of lists with 2 entries (info_name and info_value) and for each list is stored a different member variable of the class. \n Useful to debug the model, export data, copy object. """ pass
39.232877
192
0.631634
from abc import ABC, abstractmethod from OpenSeesPyAssistant.ErrorHandling import * import numpy as np class DataManagement(ABC): def SaveData(self, f): if len(self.data[0]) != 2: raise WrongDimension() delimiter = "##############################" col_delimiter = "\t" for data_line in self.data: f.write('\n') for col in data_line: if type(col) == np.ndarray: tmp_str = np.array_str(col, max_line_width = np.inf) else: tmp_str = str(col) f.write(tmp_str) f.write(col_delimiter) f.write('\n') f.write('NEW INFO SECTION DELIMITER \t') f.write(delimiter) @abstractmethod def ShowInfo(self): pass @abstractmethod def ReInit(self): pass @abstractmethod def UpdateStoredData(self): pass
true
true
f7178e22c6a7b86147f3ad4e697f29a6c67dce4f
826
py
Python
final exam 2/World Tour.py
DiyanKalaydzhiev23/fundamentals---python
7fa032d9a3270648ffa383bb00dad8e51613189d
[ "MIT" ]
null
null
null
final exam 2/World Tour.py
DiyanKalaydzhiev23/fundamentals---python
7fa032d9a3270648ffa383bb00dad8e51613189d
[ "MIT" ]
null
null
null
final exam 2/World Tour.py
DiyanKalaydzhiev23/fundamentals---python
7fa032d9a3270648ffa383bb00dad8e51613189d
[ "MIT" ]
null
null
null
stops = list(input()) command = input().split(":") while command[0] != "Travel": if command[0] == "Add Stop": if 0 <= int(command[1]) < len(stops): index = int(command[1]) for letter in command[2]: stops.insert(index, letter) index += 1 elif command[0] == "Remove Stop": if 0 <= int(command[1]) < len(stops) and 0 <= int(command[2]) < len(stops): [stops.pop(int(command[1])) for i in range(int(command[1]), int(command[2])+1)] elif command[0] == "Switch": stops = ''.join(stops) if command[1] in stops: stops = stops.replace(command[1], command[2]) stops = list(stops) print(''.join(stops)) command = input().split(":") print(f"Ready for world tour! Planned stops: {''.join(stops)}")
35.913043
91
0.53632
stops = list(input()) command = input().split(":") while command[0] != "Travel": if command[0] == "Add Stop": if 0 <= int(command[1]) < len(stops): index = int(command[1]) for letter in command[2]: stops.insert(index, letter) index += 1 elif command[0] == "Remove Stop": if 0 <= int(command[1]) < len(stops) and 0 <= int(command[2]) < len(stops): [stops.pop(int(command[1])) for i in range(int(command[1]), int(command[2])+1)] elif command[0] == "Switch": stops = ''.join(stops) if command[1] in stops: stops = stops.replace(command[1], command[2]) stops = list(stops) print(''.join(stops)) command = input().split(":") print(f"Ready for world tour! Planned stops: {''.join(stops)}")
true
true
f7178e9db3fd873fbe00c6932d476c7f06e20608
3,456
py
Python
hydrus/core/HydrusExceptions.py
ReAnzu/hydrus
069f77e1941d13b3bdd969aeeffd7ae003fcb71e
[ "WTFPL" ]
1
2021-02-24T22:12:30.000Z
2021-02-24T22:12:30.000Z
hydrus/core/HydrusExceptions.py
ReAnzu/hydrus
069f77e1941d13b3bdd969aeeffd7ae003fcb71e
[ "WTFPL" ]
null
null
null
hydrus/core/HydrusExceptions.py
ReAnzu/hydrus
069f77e1941d13b3bdd969aeeffd7ae003fcb71e
[ "WTFPL" ]
null
null
null
import collections.abc import os class HydrusException( Exception ): def __str__( self ): if isinstance( self.args, collections.abc.Iterable ): s = [] for arg in self.args: try: s.append( str( arg ) ) except: s.append( repr( arg ) ) else: s = [ repr( self.args ) ] return os.linesep.join( s ) class CantRenderWithCVException( HydrusException ): pass class DataMissing( HydrusException ): pass class DBException( HydrusException ): def __init__( self, e, first_line, db_traceback ): self.db_e = e HydrusException.__init__( self, first_line, db_traceback ) class DBAccessException( HydrusException ): pass class DBCredentialsException( HydrusException ): pass class FileMissingException( HydrusException ): pass class DirectoryMissingException( HydrusException ): pass class SerialisationException( HydrusException ): pass class NameException( HydrusException ): pass class ShutdownException( HydrusException ): pass class QtDeadWindowException(HydrusException): pass class VetoException( HydrusException ): pass class CancelledException( VetoException ): pass class UnsupportedFileException( VetoException ): pass class DamagedOrUnusualFileException( UnsupportedFileException ): pass class FileSizeException( UnsupportedFileException ): pass class DecompressionBombException( FileSizeException ): pass class TagSizeException( VetoException ): pass class ParseException( HydrusException ): pass class StringConvertException( ParseException ): pass class StringMatchException( ParseException ): pass class StringSplitterException( ParseException ): pass class URLClassException( ParseException ): pass class GUGException( ParseException ): pass class NetworkException( HydrusException ): pass class NetworkInfrastructureException( NetworkException ): pass class ConnectionException( NetworkInfrastructureException ): pass class FirewallException( NetworkInfrastructureException ): pass class RouterException( NetworkInfrastructureException ): pass class CloudFlareException( NetworkInfrastructureException ): pass class BandwidthException( NetworkInfrastructureException ): pass class ServerException( NetworkInfrastructureException ): pass class ServerBusyException( NetworkInfrastructureException ): pass class StreamTimeoutException( NetworkException ): pass class NetworkVersionException( NetworkException ): pass class NoContentException( NetworkException ): pass class NotFoundException( NetworkException ): pass class NotModifiedException( NetworkException ): pass class BadRequestException( NetworkException ): pass class ConflictException( NetworkException ): pass class MissingCredentialsException( NetworkException ): pass class DoesNotSupportCORSException( NetworkException ): pass class InsufficientCredentialsException( NetworkException ): pass class RedirectionException( NetworkException ): pass class SessionException( NetworkException ): pass class WrongServiceTypeException( NetworkException ): pass class ValidationException( NetworkException ): pass class ShouldReattemptNetworkException( NetworkException ): pass
35.265306
69
0.732928
import collections.abc import os class HydrusException( Exception ): def __str__( self ): if isinstance( self.args, collections.abc.Iterable ): s = [] for arg in self.args: try: s.append( str( arg ) ) except: s.append( repr( arg ) ) else: s = [ repr( self.args ) ] return os.linesep.join( s ) class CantRenderWithCVException( HydrusException ): pass class DataMissing( HydrusException ): pass class DBException( HydrusException ): def __init__( self, e, first_line, db_traceback ): self.db_e = e HydrusException.__init__( self, first_line, db_traceback ) class DBAccessException( HydrusException ): pass class DBCredentialsException( HydrusException ): pass class FileMissingException( HydrusException ): pass class DirectoryMissingException( HydrusException ): pass class SerialisationException( HydrusException ): pass class NameException( HydrusException ): pass class ShutdownException( HydrusException ): pass class QtDeadWindowException(HydrusException): pass class VetoException( HydrusException ): pass class CancelledException( VetoException ): pass class UnsupportedFileException( VetoException ): pass class DamagedOrUnusualFileException( UnsupportedFileException ): pass class FileSizeException( UnsupportedFileException ): pass class DecompressionBombException( FileSizeException ): pass class TagSizeException( VetoException ): pass class ParseException( HydrusException ): pass class StringConvertException( ParseException ): pass class StringMatchException( ParseException ): pass class StringSplitterException( ParseException ): pass class URLClassException( ParseException ): pass class GUGException( ParseException ): pass class NetworkException( HydrusException ): pass class NetworkInfrastructureException( NetworkException ): pass class ConnectionException( NetworkInfrastructureException ): pass class FirewallException( NetworkInfrastructureException ): pass class RouterException( NetworkInfrastructureException ): pass class CloudFlareException( NetworkInfrastructureException ): pass class BandwidthException( NetworkInfrastructureException ): pass class ServerException( NetworkInfrastructureException ): pass class ServerBusyException( NetworkInfrastructureException ): pass class StreamTimeoutException( NetworkException ): pass class NetworkVersionException( NetworkException ): pass class NoContentException( NetworkException ): pass class NotFoundException( NetworkException ): pass class NotModifiedException( NetworkException ): pass class BadRequestException( NetworkException ): pass class ConflictException( NetworkException ): pass class MissingCredentialsException( NetworkException ): pass class DoesNotSupportCORSException( NetworkException ): pass class InsufficientCredentialsException( NetworkException ): pass class RedirectionException( NetworkException ): pass class SessionException( NetworkException ): pass class WrongServiceTypeException( NetworkException ): pass class ValidationException( NetworkException ): pass class ShouldReattemptNetworkException( NetworkException ): pass
true
true
f7178ea0d3c97e41fedd16e6e263162427023912
8,139
py
Python
synapse/appservice/__init__.py
mweinelt/synapse
42a9ea37e4c6ff9d91b530c40d366446b9fc2234
[ "Apache-2.0" ]
null
null
null
synapse/appservice/__init__.py
mweinelt/synapse
42a9ea37e4c6ff9d91b530c40d366446b9fc2234
[ "Apache-2.0" ]
null
null
null
synapse/appservice/__init__.py
mweinelt/synapse
42a9ea37e4c6ff9d91b530c40d366446b9fc2234
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # Copyright 2015, 2016 OpenMarket Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from synapse.api.constants import EventTypes import logging import re logger = logging.getLogger(__name__) class ApplicationServiceState(object): DOWN = "down" UP = "up" class AppServiceTransaction(object): """Represents an application service transaction.""" def __init__(self, service, id, events): self.service = service self.id = id self.events = events def send(self, as_api): """Sends this transaction using the provided AS API interface. Args: as_api(ApplicationServiceApi): The API to use to send. Returns: A Deferred which resolves to True if the transaction was sent. """ return as_api.push_bulk( service=self.service, events=self.events, txn_id=self.id ) def complete(self, store): """Completes this transaction as successful. Marks this transaction ID on the application service and removes the transaction contents from the database. Args: store: The database store to operate on. Returns: A Deferred which resolves to True if the transaction was completed. """ return store.complete_appservice_txn( service=self.service, txn_id=self.id ) class ApplicationService(object): """Defines an application service. This definition is mostly what is provided to the /register AS API. Provides methods to check if this service is "interested" in events. """ NS_USERS = "users" NS_ALIASES = "aliases" NS_ROOMS = "rooms" # The ordering here is important as it is used to map database values (which # are stored as ints representing the position in this list) to namespace # values. NS_LIST = [NS_USERS, NS_ALIASES, NS_ROOMS] def __init__(self, token, url=None, namespaces=None, hs_token=None, sender=None, id=None): self.token = token self.url = url self.hs_token = hs_token self.sender = sender self.namespaces = self._check_namespaces(namespaces) self.id = id def _check_namespaces(self, namespaces): # Sanity check that it is of the form: # { # users: [ {regex: "[A-z]+.*", exclusive: true}, ...], # aliases: [ {regex: "[A-z]+.*", exclusive: true}, ...], # rooms: [ {regex: "[A-z]+.*", exclusive: true}, ...], # } if not namespaces: namespaces = {} for ns in ApplicationService.NS_LIST: if ns not in namespaces: namespaces[ns] = [] continue if type(namespaces[ns]) != list: raise ValueError("Bad namespace value for '%s'" % ns) for regex_obj in namespaces[ns]: if not isinstance(regex_obj, dict): raise ValueError("Expected dict regex for ns '%s'" % ns) if not isinstance(regex_obj.get("exclusive"), bool): raise ValueError( "Expected bool for 'exclusive' in ns '%s'" % ns ) if not isinstance(regex_obj.get("regex"), basestring): raise ValueError( "Expected string for 'regex' in ns '%s'" % ns ) return namespaces def _matches_regex(self, test_string, namespace_key, return_obj=False): if not isinstance(test_string, basestring): logger.error( "Expected a string to test regex against, but got %s", test_string ) return False for regex_obj in self.namespaces[namespace_key]: if re.match(regex_obj["regex"], test_string): if return_obj: return regex_obj return True return False def _is_exclusive(self, ns_key, test_string): regex_obj = self._matches_regex(test_string, ns_key, return_obj=True) if regex_obj: return regex_obj["exclusive"] return False def _matches_user(self, event, member_list): if (hasattr(event, "sender") and self.is_interested_in_user(event.sender)): return True # also check m.room.member state key if (hasattr(event, "type") and event.type == EventTypes.Member and hasattr(event, "state_key") and self.is_interested_in_user(event.state_key)): return True # check joined member events for user_id in member_list: if self.is_interested_in_user(user_id): return True return False def _matches_room_id(self, event): if hasattr(event, "room_id"): return self.is_interested_in_room(event.room_id) return False def _matches_aliases(self, event, alias_list): for alias in alias_list: if self.is_interested_in_alias(alias): return True return False def is_interested(self, event, restrict_to=None, aliases_for_event=None, member_list=None): """Check if this service is interested in this event. Args: event(Event): The event to check. restrict_to(str): The namespace to restrict regex tests to. aliases_for_event(list): A list of all the known room aliases for this event. member_list(list): A list of all joined user_ids in this room. Returns: bool: True if this service would like to know about this event. """ if aliases_for_event is None: aliases_for_event = [] if member_list is None: member_list = [] if restrict_to and restrict_to not in ApplicationService.NS_LIST: # this is a programming error, so fail early and raise a general # exception raise Exception("Unexpected restrict_to value: %s". restrict_to) if not restrict_to: return (self._matches_user(event, member_list) or self._matches_aliases(event, aliases_for_event) or self._matches_room_id(event)) elif restrict_to == ApplicationService.NS_ALIASES: return self._matches_aliases(event, aliases_for_event) elif restrict_to == ApplicationService.NS_ROOMS: return self._matches_room_id(event) elif restrict_to == ApplicationService.NS_USERS: return self._matches_user(event, member_list) def is_interested_in_user(self, user_id): return ( self._matches_regex(user_id, ApplicationService.NS_USERS) or user_id == self.sender ) def is_interested_in_alias(self, alias): return self._matches_regex(alias, ApplicationService.NS_ALIASES) def is_interested_in_room(self, room_id): return self._matches_regex(room_id, ApplicationService.NS_ROOMS) def is_exclusive_user(self, user_id): return ( self._is_exclusive(ApplicationService.NS_USERS, user_id) or user_id == self.sender ) def is_exclusive_alias(self, alias): return self._is_exclusive(ApplicationService.NS_ALIASES, alias) def is_exclusive_room(self, room_id): return self._is_exclusive(ApplicationService.NS_ROOMS, room_id) def __str__(self): return "ApplicationService: %s" % (self.__dict__,)
35.854626
80
0.6158
from synapse.api.constants import EventTypes import logging import re logger = logging.getLogger(__name__) class ApplicationServiceState(object): DOWN = "down" UP = "up" class AppServiceTransaction(object): def __init__(self, service, id, events): self.service = service self.id = id self.events = events def send(self, as_api): return as_api.push_bulk( service=self.service, events=self.events, txn_id=self.id ) def complete(self, store): return store.complete_appservice_txn( service=self.service, txn_id=self.id ) class ApplicationService(object): NS_USERS = "users" NS_ALIASES = "aliases" NS_ROOMS = "rooms" NS_LIST = [NS_USERS, NS_ALIASES, NS_ROOMS] def __init__(self, token, url=None, namespaces=None, hs_token=None, sender=None, id=None): self.token = token self.url = url self.hs_token = hs_token self.sender = sender self.namespaces = self._check_namespaces(namespaces) self.id = id def _check_namespaces(self, namespaces): if not namespaces: namespaces = {} for ns in ApplicationService.NS_LIST: if ns not in namespaces: namespaces[ns] = [] continue if type(namespaces[ns]) != list: raise ValueError("Bad namespace value for '%s'" % ns) for regex_obj in namespaces[ns]: if not isinstance(regex_obj, dict): raise ValueError("Expected dict regex for ns '%s'" % ns) if not isinstance(regex_obj.get("exclusive"), bool): raise ValueError( "Expected bool for 'exclusive' in ns '%s'" % ns ) if not isinstance(regex_obj.get("regex"), basestring): raise ValueError( "Expected string for 'regex' in ns '%s'" % ns ) return namespaces def _matches_regex(self, test_string, namespace_key, return_obj=False): if not isinstance(test_string, basestring): logger.error( "Expected a string to test regex against, but got %s", test_string ) return False for regex_obj in self.namespaces[namespace_key]: if re.match(regex_obj["regex"], test_string): if return_obj: return regex_obj return True return False def _is_exclusive(self, ns_key, test_string): regex_obj = self._matches_regex(test_string, ns_key, return_obj=True) if regex_obj: return regex_obj["exclusive"] return False def _matches_user(self, event, member_list): if (hasattr(event, "sender") and self.is_interested_in_user(event.sender)): return True if (hasattr(event, "type") and event.type == EventTypes.Member and hasattr(event, "state_key") and self.is_interested_in_user(event.state_key)): return True for user_id in member_list: if self.is_interested_in_user(user_id): return True return False def _matches_room_id(self, event): if hasattr(event, "room_id"): return self.is_interested_in_room(event.room_id) return False def _matches_aliases(self, event, alias_list): for alias in alias_list: if self.is_interested_in_alias(alias): return True return False def is_interested(self, event, restrict_to=None, aliases_for_event=None, member_list=None): if aliases_for_event is None: aliases_for_event = [] if member_list is None: member_list = [] if restrict_to and restrict_to not in ApplicationService.NS_LIST: raise Exception("Unexpected restrict_to value: %s". restrict_to) if not restrict_to: return (self._matches_user(event, member_list) or self._matches_aliases(event, aliases_for_event) or self._matches_room_id(event)) elif restrict_to == ApplicationService.NS_ALIASES: return self._matches_aliases(event, aliases_for_event) elif restrict_to == ApplicationService.NS_ROOMS: return self._matches_room_id(event) elif restrict_to == ApplicationService.NS_USERS: return self._matches_user(event, member_list) def is_interested_in_user(self, user_id): return ( self._matches_regex(user_id, ApplicationService.NS_USERS) or user_id == self.sender ) def is_interested_in_alias(self, alias): return self._matches_regex(alias, ApplicationService.NS_ALIASES) def is_interested_in_room(self, room_id): return self._matches_regex(room_id, ApplicationService.NS_ROOMS) def is_exclusive_user(self, user_id): return ( self._is_exclusive(ApplicationService.NS_USERS, user_id) or user_id == self.sender ) def is_exclusive_alias(self, alias): return self._is_exclusive(ApplicationService.NS_ALIASES, alias) def is_exclusive_room(self, room_id): return self._is_exclusive(ApplicationService.NS_ROOMS, room_id) def __str__(self): return "ApplicationService: %s" % (self.__dict__,)
true
true
f717904cee8dca9e6d25f6ea498b85acd973ab00
8,645
py
Python
src/extractor/make_bb_info_mats.py
lonelu/Metalprot_learning
8edb2c3e4f6ba129a409d75fd4d15ceb3a9e307b
[ "MIT" ]
null
null
null
src/extractor/make_bb_info_mats.py
lonelu/Metalprot_learning
8edb2c3e4f6ba129a409d75fd4d15ceb3a9e307b
[ "MIT" ]
null
null
null
src/extractor/make_bb_info_mats.py
lonelu/Metalprot_learning
8edb2c3e4f6ba129a409d75fd4d15ceb3a9e307b
[ "MIT" ]
null
null
null
from numpy.core.numeric import full from numpy.lib.function_base import append import prody as pr import os import numpy import matplotlib as mpl import pylab from itertools import combinations, combinations_with_replacement from docopt import docopt import itertools import pickle import sys from scipy.linalg.basic import matrix_balance from scipy.spatial.distance import cdist from . import ligand_database as ld from . import features_pdb2dihe as fpdh metal_sel = 'ion or name NI MN ZN CO CU MG FE' #TO DO: create artificial aa in the 4th aa. def get_atg(full_pdb): ''' prody atomgroup will be used to calc bb info. If the contact aa is at terminal, then the shape of the dist matrix will be < 12. So contact aa will be copied and added. ''' metal = full_pdb.select(metal_sel)[0] contact_aas = full_pdb.select('protein and not carbon and not hydrogen and within 2.83 of resindex ' + str(metal.getResindex())) contact_aa_resinds = numpy.unique(contact_aas.getResindices()) extention = 1 coords = [] resnames = [] names = [] resnums = [] resn = 1 for resind in contact_aa_resinds: ext_inds = ld.extend_res_indices([resind], full_pdb, extend =extention) #In some cases, the contact aa is at terminal. We can add more aa to match the shape. if len(ext_inds) == 2: if ext_inds[0] == resind: ext_inds.insert(0, resind) else: ext_inds.append(resind) if len(ext_inds) == 1: ext_inds.append(resind) ext_inds.append(resind) for ind in ext_inds: aa = full_pdb.select('resindex ' + str(ind)) coords.extend(aa.getCoords()) resnames.extend(aa.getResnames()) names.extend(aa.getNames()) resnums.extend([resn for _i in range(len(aa))]) resn += 1 if len(contact_aa_resinds) == 3: coords.extend([]) resnames.extend([]) names.extend([]) resnums.extend([]) #ag = pr.AtomGroup('-'.join([str(p) for p in per])) ag = pr.AtomGroup('0-1-2-3') ag.setCoords(coords) ag.setResnums(resnums) ag.setResnames(resnames) ag.setNames(names) return ag def get_atgs(full_pdb, contain_metal = True): ''' prody atomgroup will be used to calc bb info. If the contact aa is at terminal, then the shape of the dist matrix will be < 12. So contact aa will be copied and added. ''' if contain_metal: metal = full_pdb.select(metal_sel)[0] contact_aas = full_pdb.select('protein and not carbon and not hydrogen and within 2.83 of resindex ' + str(metal.getResindex())) else: #TO DO: it is not quite right here if the pdb happened to have more HIS-CYS-GLU-ASP. Skip now. contact_aas = full_pdb.select('resname HIS CYS GLU ASP') if not contact_aas and len(numpy.unique(contact_aas.getResindices())) > 4: return [] contact_aa_resinds = numpy.unique(contact_aas.getResindices()) extention = 1 # TO DO: If the len of contact_ass is not 4... ags = [] #for per in itertools.permutations(range(len(contact_aa_resinds))): for per in [range(len(contact_aa_resinds))]: print(per) coords = [] resnames = [] names = [] resnums = [] resn = 1 for idx in per: resind = contact_aa_resinds[idx] ext_inds = ld.extend_res_indices([resind], full_pdb, extend =extention) #In some cases, the contact aa is at terminal. We can add more aa to match the shape. if len(ext_inds) == 2: if ext_inds[0] == resind: ext_inds.insert(0, resind) else: ext_inds.append(resind) if len(ext_inds) == 1: ext_inds.append(resind) ext_inds.append(resind) for ind in ext_inds: aa = full_pdb.select('resindex ' + str(ind)) coords.extend(aa.getCoords()) resnames.extend(aa.getResnames()) names.extend(aa.getNames()) resnums.extend([resn for _i in range(len(aa))]) resn += 1 ag = pr.AtomGroup('-'.join([str(p) for p in per])) ag.setCoords(coords) ag.setResnums(resnums) ag.setResnames(resnames) ag.setNames(names) ags.append(ag) return ags def get_bb_dist_seq(core): ''' If we know N CA C, The coords of CB could be calcualted. So we may not need CB coords. ''' n_coords = core.select('name N').getCoords() c_coords = core.select('name C').getCoords() ca_coords = core.select('name CA').getCoords() n_n = cdist(n_coords, n_coords) c_c = cdist(c_coords, c_coords) ca_ca = cdist(ca_coords, ca_coords) cb_coords = [] for i in range(len(n_coords)): Ca = ca_coords[i] C = c_coords[i] N = n_coords[i] b = Ca - N c = C - Ca a = numpy.cross(b, c) Cb = -0.58273431*a + 0.56802827*b - 0.54067466*c + Ca cb_coords.append(Cb) cb_coords = core.select('name CB').getCoords() cb_cb = cdist(cb_coords, cb_coords) return n_n, c_c, ca_ca, cb_cb def get_dihe(ag): ''' Please check features_pdb2dihe.py. Only the contact aa will be extracted. ''' nres = len(ag.select('name CA')) print(nres) dist, _omega, _theta_asym, _phi_asym = fpdh.get_neighbors(ag, nres, 20.0) #TO DO: extract info, only the contact aa matters?! omega = numpy.zeros((nres, nres)) theta_asym = numpy.zeros((nres, nres)) phi_asym = numpy.zeros((nres, nres)) for i in range(1, nres, 3): for j in range(1, nres, 3): omega[i, j] = _omega[i, j] theta_asym[i, j] = _theta_asym[i, j] phi_asym[i, j] = _phi_asym[i, j] return omega, theta_asym, phi_asym def get_seq_mat(ag, matrix_size = 12): seq = ag.select('name CA').getResnames() threelettercodes = ['ALA', 'ARG', 'ASN', 'ASP', 'CYS', 'GLU', 'GLN', 'GLY', 'HIS', 'ILE', 'LEU', 'LYS', 'MET',\ 'PHE', 'PRO', 'SER', 'THR', 'TRP', 'TYR', 'VAL'] seq_channels = numpy.zeros([40, matrix_size, matrix_size], dtype=int) for i in range(len(seq)): aa = seq[i] try: idx = threelettercodes.index(aa) except: print('Resname of following atom not found: {}'.format(aa)) continue for j in range(len(seq)): seq_channels[idx][i][j] = 1 # horizontal rows of 1's in first 20 channels seq_channels[idx+20][j][i] = 1 # vertical columns of 1's in next 20 channels return seq_channels def mk_full_mats(ag, matrix_size = 12): nres = len(ag.select('name CA')) n_n, c_c, ca_ca, cb_cb = get_bb_dist_seq(ag) omega, theta_asym, phi_asym = get_dihe(ag) seq_mats = get_seq_mat(ag, matrix_size) full_mat = numpy.zeros((47, matrix_size, matrix_size)) # Make sure the shape of each matrix is smaller than the matrix_size. full_mat[0,0:n_n.shape[0], 0:n_n.shape[1]] = n_n full_mat[1,0:c_c.shape[0], 0:c_c.shape[1]] = c_c full_mat[2,0:ca_ca.shape[0], 0:ca_ca.shape[1]] = ca_ca full_mat[3,0:cb_cb.shape[0], 0:cb_cb.shape[1]] = cb_cb full_mat[4,0:omega.shape[0], 0:omega.shape[1]] = omega full_mat[5,0:theta_asym.shape[0], 0:theta_asym.shape[1]] = theta_asym full_mat[6,0:phi_asym.shape[0], 0:phi_asym.shape[1]] = phi_asym for i in range(7, 47): full_mat[i, :, :] = seq_mats[i - 7] return full_mat def write_pickle_file(full_mat, pdb, ag, out_folder, tag = ''): """ Writes a pickle file containing the input numpy array into the current permutation's folder. Currently using this only to save the full matrix (all 46 channels). """ numpy.set_printoptions(threshold=numpy.inf) pdb_name = pdb.split('.')[0] pkl_file = out_folder + pdb_name + '_full_mat_' + ag.getTitle() + tag + '.pkl' with open(pkl_file, 'wb') as f: print(pkl_file) pickle.dump(full_mat, f) return def write_dist_mat_file(mat, pdb, ag, out_folder, tag = ''): """ Writes out a file containing the distance matrix """ # output_folder = 'core_contact_maps/dist_mat_txt_folder/' numpy.set_printoptions(threshold=numpy.inf) dist_mat_file = pdb.split('.')[0] dist_mat_file = out_folder + dist_mat_file + '_full_mat_' + ag.getTitle() + tag + '.txt' with open(dist_mat_file, 'w') as open_file: for i in mat: open_file.write(str(i) + '\n') return def run_mk_bb_info_mats(workdir, out_path, mat_size = 12, top = 1000, contain_metal = True, opts = None): os.makedirs(out_path, exist_ok=True) count = 0 errors = '' for pdb_name in os.listdir(workdir): if count >= top: break if '.pdb' not in pdb_name: continue pdb_file = workdir + pdb_name pdb = pr.parsePDB(pdb_file) ags = get_atgs(pdb, contain_metal) for ag in ags: try: #TO DO: currently, only consider 3 or 4 aa binding. if len(ag.select('name CA'))> 12 or len(ag.select('name CA')) < 7: print(pdb_name + ' not used. ') continue full_mat = mk_full_mats(ag, mat_size) write_dist_mat_file(full_mat, pdb_name, ag, out_path) write_pickle_file(full_mat, pdb_name, ag, out_path) count += 1 except: print('error: ' + pdb_name) errors += pdb_name + '\n' if count >= top: break with open(out_path + '_error.txt', 'w') as f: f.write(errors) return
25.501475
131
0.682244
from numpy.core.numeric import full from numpy.lib.function_base import append import prody as pr import os import numpy import matplotlib as mpl import pylab from itertools import combinations, combinations_with_replacement from docopt import docopt import itertools import pickle import sys from scipy.linalg.basic import matrix_balance from scipy.spatial.distance import cdist from . import ligand_database as ld from . import features_pdb2dihe as fpdh metal_sel = 'ion or name NI MN ZN CO CU MG FE' def get_atg(full_pdb): metal = full_pdb.select(metal_sel)[0] contact_aas = full_pdb.select('protein and not carbon and not hydrogen and within 2.83 of resindex ' + str(metal.getResindex())) contact_aa_resinds = numpy.unique(contact_aas.getResindices()) extention = 1 coords = [] resnames = [] names = [] resnums = [] resn = 1 for resind in contact_aa_resinds: ext_inds = ld.extend_res_indices([resind], full_pdb, extend =extention) if len(ext_inds) == 2: if ext_inds[0] == resind: ext_inds.insert(0, resind) else: ext_inds.append(resind) if len(ext_inds) == 1: ext_inds.append(resind) ext_inds.append(resind) for ind in ext_inds: aa = full_pdb.select('resindex ' + str(ind)) coords.extend(aa.getCoords()) resnames.extend(aa.getResnames()) names.extend(aa.getNames()) resnums.extend([resn for _i in range(len(aa))]) resn += 1 if len(contact_aa_resinds) == 3: coords.extend([]) resnames.extend([]) names.extend([]) resnums.extend([]) ag = pr.AtomGroup('0-1-2-3') ag.setCoords(coords) ag.setResnums(resnums) ag.setResnames(resnames) ag.setNames(names) return ag def get_atgs(full_pdb, contain_metal = True): if contain_metal: metal = full_pdb.select(metal_sel)[0] contact_aas = full_pdb.select('protein and not carbon and not hydrogen and within 2.83 of resindex ' + str(metal.getResindex())) else: contact_aas = full_pdb.select('resname HIS CYS GLU ASP') if not contact_aas and len(numpy.unique(contact_aas.getResindices())) > 4: return [] contact_aa_resinds = numpy.unique(contact_aas.getResindices()) extention = 1 ags = [] for per in [range(len(contact_aa_resinds))]: print(per) coords = [] resnames = [] names = [] resnums = [] resn = 1 for idx in per: resind = contact_aa_resinds[idx] ext_inds = ld.extend_res_indices([resind], full_pdb, extend =extention) if len(ext_inds) == 2: if ext_inds[0] == resind: ext_inds.insert(0, resind) else: ext_inds.append(resind) if len(ext_inds) == 1: ext_inds.append(resind) ext_inds.append(resind) for ind in ext_inds: aa = full_pdb.select('resindex ' + str(ind)) coords.extend(aa.getCoords()) resnames.extend(aa.getResnames()) names.extend(aa.getNames()) resnums.extend([resn for _i in range(len(aa))]) resn += 1 ag = pr.AtomGroup('-'.join([str(p) for p in per])) ag.setCoords(coords) ag.setResnums(resnums) ag.setResnames(resnames) ag.setNames(names) ags.append(ag) return ags def get_bb_dist_seq(core): n_coords = core.select('name N').getCoords() c_coords = core.select('name C').getCoords() ca_coords = core.select('name CA').getCoords() n_n = cdist(n_coords, n_coords) c_c = cdist(c_coords, c_coords) ca_ca = cdist(ca_coords, ca_coords) cb_coords = [] for i in range(len(n_coords)): Ca = ca_coords[i] C = c_coords[i] N = n_coords[i] b = Ca - N c = C - Ca a = numpy.cross(b, c) Cb = -0.58273431*a + 0.56802827*b - 0.54067466*c + Ca cb_coords.append(Cb) cb_coords = core.select('name CB').getCoords() cb_cb = cdist(cb_coords, cb_coords) return n_n, c_c, ca_ca, cb_cb def get_dihe(ag): nres = len(ag.select('name CA')) print(nres) dist, _omega, _theta_asym, _phi_asym = fpdh.get_neighbors(ag, nres, 20.0) omega = numpy.zeros((nres, nres)) theta_asym = numpy.zeros((nres, nres)) phi_asym = numpy.zeros((nres, nres)) for i in range(1, nres, 3): for j in range(1, nres, 3): omega[i, j] = _omega[i, j] theta_asym[i, j] = _theta_asym[i, j] phi_asym[i, j] = _phi_asym[i, j] return omega, theta_asym, phi_asym def get_seq_mat(ag, matrix_size = 12): seq = ag.select('name CA').getResnames() threelettercodes = ['ALA', 'ARG', 'ASN', 'ASP', 'CYS', 'GLU', 'GLN', 'GLY', 'HIS', 'ILE', 'LEU', 'LYS', 'MET',\ 'PHE', 'PRO', 'SER', 'THR', 'TRP', 'TYR', 'VAL'] seq_channels = numpy.zeros([40, matrix_size, matrix_size], dtype=int) for i in range(len(seq)): aa = seq[i] try: idx = threelettercodes.index(aa) except: print('Resname of following atom not found: {}'.format(aa)) continue for j in range(len(seq)): seq_channels[idx][i][j] = 1 seq_channels[idx+20][j][i] = 1 # vertical columns of 1's in next 20 channels return seq_channels def mk_full_mats(ag, matrix_size = 12): nres = len(ag.select('name CA')) n_n, c_c, ca_ca, cb_cb = get_bb_dist_seq(ag) omega, theta_asym, phi_asym = get_dihe(ag) seq_mats = get_seq_mat(ag, matrix_size) full_mat = numpy.zeros((47, matrix_size, matrix_size)) full_mat[0,0:n_n.shape[0], 0:n_n.shape[1]] = n_n full_mat[1,0:c_c.shape[0], 0:c_c.shape[1]] = c_c full_mat[2,0:ca_ca.shape[0], 0:ca_ca.shape[1]] = ca_ca full_mat[3,0:cb_cb.shape[0], 0:cb_cb.shape[1]] = cb_cb full_mat[4,0:omega.shape[0], 0:omega.shape[1]] = omega full_mat[5,0:theta_asym.shape[0], 0:theta_asym.shape[1]] = theta_asym full_mat[6,0:phi_asym.shape[0], 0:phi_asym.shape[1]] = phi_asym for i in range(7, 47): full_mat[i, :, :] = seq_mats[i - 7] return full_mat def write_pickle_file(full_mat, pdb, ag, out_folder, tag = ''): numpy.set_printoptions(threshold=numpy.inf) pdb_name = pdb.split('.')[0] pkl_file = out_folder + pdb_name + '_full_mat_' + ag.getTitle() + tag + '.pkl' with open(pkl_file, 'wb') as f: print(pkl_file) pickle.dump(full_mat, f) return def write_dist_mat_file(mat, pdb, ag, out_folder, tag = ''): numpy.set_printoptions(threshold=numpy.inf) dist_mat_file = pdb.split('.')[0] dist_mat_file = out_folder + dist_mat_file + '_full_mat_' + ag.getTitle() + tag + '.txt' with open(dist_mat_file, 'w') as open_file: for i in mat: open_file.write(str(i) + '\n') return def run_mk_bb_info_mats(workdir, out_path, mat_size = 12, top = 1000, contain_metal = True, opts = None): os.makedirs(out_path, exist_ok=True) count = 0 errors = '' for pdb_name in os.listdir(workdir): if count >= top: break if '.pdb' not in pdb_name: continue pdb_file = workdir + pdb_name pdb = pr.parsePDB(pdb_file) ags = get_atgs(pdb, contain_metal) for ag in ags: try: if len(ag.select('name CA'))> 12 or len(ag.select('name CA')) < 7: print(pdb_name + ' not used. ') continue full_mat = mk_full_mats(ag, mat_size) write_dist_mat_file(full_mat, pdb_name, ag, out_path) write_pickle_file(full_mat, pdb_name, ag, out_path) count += 1 except: print('error: ' + pdb_name) errors += pdb_name + '\n' if count >= top: break with open(out_path + '_error.txt', 'w') as f: f.write(errors) return
true
true
f71791c60cc7fc628325ca20e013c1f715b14cbf
1,168
py
Python
openamundsen/__init__.py
openamundsen/openamundsen
2ac09eb34b0c72c84c421a0dac08d114a05b7b1c
[ "MIT" ]
3
2021-05-28T06:46:36.000Z
2021-06-14T13:39:25.000Z
openamundsen/__init__.py
openamundsen/openamundsen
2ac09eb34b0c72c84c421a0dac08d114a05b7b1c
[ "MIT" ]
22
2021-04-28T12:31:58.000Z
2022-03-09T18:29:12.000Z
openamundsen/__init__.py
openamundsen/openamundsen
2ac09eb34b0c72c84c421a0dac08d114a05b7b1c
[ "MIT" ]
1
2021-06-01T12:48:54.000Z
2021-06-01T12:48:54.000Z
from .conf import Configuration, parse_config, read_config from .model import OpenAmundsen, Model from . import constants, errors, terrain # Get version (method as used by matplotlib: https://github.com/matplotlib/matplotlib/blob/bcc1ce8461f5b6e874baaaa02ef776d0243a4abe/lib/matplotlib/__init__.py#L133-L151) def __getattr__(name): if name == '__version__': from pathlib import Path import setuptools_scm global __version__ root = Path(__file__).resolve().parents[1] if (root / '.git').exists() and not (root / '.git/shallow').exists(): __version__ = setuptools_scm.get_version( root=root, version_scheme='post-release', fallback_version='0.0.0+UNKNOWN', ) else: try: from . import _version __version__ = _version.version except ImportError: __version__ = '0.0.0+UNKNOWN' return __version__ raise AttributeError(f'module {__name__!r} has no attribute {name!r}') __all__ = [ 'OpenAmundsen', 'Configuration', 'parse_config', 'read_config', ]
33.371429
169
0.626712
from .conf import Configuration, parse_config, read_config from .model import OpenAmundsen, Model from . import constants, errors, terrain ttr__(name): if name == '__version__': from pathlib import Path import setuptools_scm global __version__ root = Path(__file__).resolve().parents[1] if (root / '.git').exists() and not (root / '.git/shallow').exists(): __version__ = setuptools_scm.get_version( root=root, version_scheme='post-release', fallback_version='0.0.0+UNKNOWN', ) else: try: from . import _version __version__ = _version.version except ImportError: __version__ = '0.0.0+UNKNOWN' return __version__ raise AttributeError(f'module {__name__!r} has no attribute {name!r}') __all__ = [ 'OpenAmundsen', 'Configuration', 'parse_config', 'read_config', ]
true
true
f71791e019fc01edfa394b5acc7c6d6563b6ea45
35,147
py
Python
tests/components/mqtt/test_light_json.py
jlvaillant/core
ae37f9a1d9c5067957854b3c25dcc73fe9a10bee
[ "Apache-2.0" ]
2
2019-11-20T20:56:59.000Z
2021-01-03T08:52:18.000Z
tests/components/mqtt/test_light_json.py
jlvaillant/core
ae37f9a1d9c5067957854b3c25dcc73fe9a10bee
[ "Apache-2.0" ]
2
2021-06-08T21:54:21.000Z
2022-03-12T00:37:59.000Z
tests/components/mqtt/test_light_json.py
sampou/homeassistant
6c1a5d9e5a72eed3a582457142b1db7867b6ff7b
[ "Apache-2.0" ]
1
2021-04-18T19:36:34.000Z
2021-04-18T19:36:34.000Z
"""The tests for the MQTT JSON light platform. Configuration with RGB, brightness, color temp, effect, white value and XY: light: platform: mqtt_json name: mqtt_json_light_1 state_topic: "home/rgb1" command_topic: "home/rgb1/set" brightness: true color_temp: true effect: true rgb: true white_value: true xy: true Configuration with RGB, brightness, color temp, effect, white value: light: platform: mqtt_json name: mqtt_json_light_1 state_topic: "home/rgb1" command_topic: "home/rgb1/set" brightness: true color_temp: true effect: true rgb: true white_value: true Configuration with RGB, brightness, color temp and effect: light: platform: mqtt_json name: mqtt_json_light_1 state_topic: "home/rgb1" command_topic: "home/rgb1/set" brightness: true color_temp: true effect: true rgb: true Configuration with RGB, brightness and color temp: light: platform: mqtt_json name: mqtt_json_light_1 state_topic: "home/rgb1" command_topic: "home/rgb1/set" brightness: true rgb: true color_temp: true Configuration with RGB, brightness: light: platform: mqtt_json name: mqtt_json_light_1 state_topic: "home/rgb1" command_topic: "home/rgb1/set" brightness: true rgb: true Config without RGB: light: platform: mqtt_json name: mqtt_json_light_1 state_topic: "home/rgb1" command_topic: "home/rgb1/set" brightness: true Config without RGB and brightness: light: platform: mqtt_json name: mqtt_json_light_1 state_topic: "home/rgb1" command_topic: "home/rgb1/set" Config with brightness and scale: light: platform: mqtt_json name: test state_topic: "mqtt_json_light_1" command_topic: "mqtt_json_light_1/set" brightness: true brightness_scale: 99 """ import json from unittest import mock from unittest.mock import patch from homeassistant.components import light from homeassistant.const import ( ATTR_ASSUMED_STATE, ATTR_SUPPORTED_FEATURES, STATE_OFF, STATE_ON, ) import homeassistant.core as ha from homeassistant.setup import async_setup_component from .test_common import ( help_test_availability_without_topic, help_test_custom_availability_payload, help_test_default_availability_payload, help_test_discovery_broken, help_test_discovery_removal, help_test_discovery_update, help_test_discovery_update_attr, help_test_entity_device_info_remove, help_test_entity_device_info_update, help_test_entity_device_info_with_connection, help_test_entity_device_info_with_identifier, help_test_entity_id_update_discovery_update, help_test_entity_id_update_subscriptions, help_test_setting_attribute_via_mqtt_json_message, help_test_setting_attribute_with_template, help_test_unique_id, help_test_update_with_json_attrs_bad_JSON, help_test_update_with_json_attrs_not_dict, ) from tests.common import async_fire_mqtt_message, mock_coro from tests.components.light import common DEFAULT_CONFIG = { light.DOMAIN: { "platform": "mqtt", "schema": "json", "name": "test", "command_topic": "test-topic", } } class JsonValidator(object): """Helper to compare JSON.""" def __init__(self, jsondata): """Initialize JSON validator.""" self.jsondata = jsondata def __eq__(self, other): """Compare JSON data.""" return json.loads(self.jsondata) == json.loads(other) async def test_fail_setup_if_no_command_topic(hass, mqtt_mock): """Test if setup fails with no command topic.""" assert await async_setup_component( hass, light.DOMAIN, {light.DOMAIN: {"platform": "mqtt", "schema": "json", "name": "test"}}, ) assert hass.states.get("light.test") is None async def test_no_color_brightness_color_temp_white_val_if_no_topics(hass, mqtt_mock): """Test for no RGB, brightness, color temp, effect, white val or XY.""" assert await async_setup_component( hass, light.DOMAIN, { light.DOMAIN: { "platform": "mqtt", "schema": "json", "name": "test", "state_topic": "test_light_rgb", "command_topic": "test_light_rgb/set", } }, ) state = hass.states.get("light.test") assert state.state == STATE_OFF assert state.attributes.get(ATTR_SUPPORTED_FEATURES) == 40 assert state.attributes.get("rgb_color") is None assert state.attributes.get("brightness") is None assert state.attributes.get("color_temp") is None assert state.attributes.get("effect") is None assert state.attributes.get("white_value") is None assert state.attributes.get("xy_color") is None assert state.attributes.get("hs_color") is None async_fire_mqtt_message(hass, "test_light_rgb", '{"state":"ON"}') state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("rgb_color") is None assert state.attributes.get("brightness") is None assert state.attributes.get("color_temp") is None assert state.attributes.get("effect") is None assert state.attributes.get("white_value") is None assert state.attributes.get("xy_color") is None assert state.attributes.get("hs_color") is None async def test_controlling_state_via_topic(hass, mqtt_mock): """Test the controlling of the state via topic.""" assert await async_setup_component( hass, light.DOMAIN, { light.DOMAIN: { "platform": "mqtt", "schema": "json", "name": "test", "state_topic": "test_light_rgb", "command_topic": "test_light_rgb/set", "brightness": True, "color_temp": True, "effect": True, "rgb": True, "white_value": True, "xy": True, "hs": True, "qos": "0", } }, ) state = hass.states.get("light.test") assert state.state == STATE_OFF assert state.attributes.get(ATTR_SUPPORTED_FEATURES) == 191 assert state.attributes.get("rgb_color") is None assert state.attributes.get("brightness") is None assert state.attributes.get("color_temp") is None assert state.attributes.get("effect") is None assert state.attributes.get("white_value") is None assert state.attributes.get("xy_color") is None assert state.attributes.get("hs_color") is None assert not state.attributes.get(ATTR_ASSUMED_STATE) # Turn on the light, full white async_fire_mqtt_message( hass, "test_light_rgb", '{"state":"ON",' '"color":{"r":255,"g":255,"b":255},' '"brightness":255,' '"color_temp":155,' '"effect":"colorloop",' '"white_value":150}', ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("rgb_color") == (255, 255, 255) assert state.attributes.get("brightness") == 255 assert state.attributes.get("color_temp") == 155 assert state.attributes.get("effect") == "colorloop" assert state.attributes.get("white_value") == 150 assert state.attributes.get("xy_color") == (0.323, 0.329) assert state.attributes.get("hs_color") == (0.0, 0.0) # Turn the light off async_fire_mqtt_message(hass, "test_light_rgb", '{"state":"OFF"}') state = hass.states.get("light.test") assert state.state == STATE_OFF async_fire_mqtt_message(hass, "test_light_rgb", '{"state":"ON", "brightness":100}') light_state = hass.states.get("light.test") assert light_state.attributes["brightness"] == 100 async_fire_mqtt_message( hass, "test_light_rgb", '{"state":"ON", ' '"color":{"r":125,"g":125,"b":125}}' ) light_state = hass.states.get("light.test") assert light_state.attributes.get("rgb_color") == (255, 255, 255) async_fire_mqtt_message( hass, "test_light_rgb", '{"state":"ON", "color":{"x":0.135,"y":0.135}}' ) light_state = hass.states.get("light.test") assert light_state.attributes.get("xy_color") == (0.141, 0.14) async_fire_mqtt_message( hass, "test_light_rgb", '{"state":"ON", "color":{"h":180,"s":50}}' ) light_state = hass.states.get("light.test") assert light_state.attributes.get("hs_color") == (180.0, 50.0) async_fire_mqtt_message(hass, "test_light_rgb", '{"state":"ON", "color_temp":155}') light_state = hass.states.get("light.test") assert light_state.attributes.get("color_temp") == 155 async_fire_mqtt_message( hass, "test_light_rgb", '{"state":"ON", "effect":"colorloop"}' ) light_state = hass.states.get("light.test") assert light_state.attributes.get("effect") == "colorloop" async_fire_mqtt_message(hass, "test_light_rgb", '{"state":"ON", "white_value":155}') light_state = hass.states.get("light.test") assert light_state.attributes.get("white_value") == 155 async def test_sending_mqtt_commands_and_optimistic(hass, mqtt_mock): """Test the sending of command in optimistic mode.""" fake_state = ha.State( "light.test", "on", { "brightness": 95, "hs_color": [100, 100], "effect": "random", "color_temp": 100, "white_value": 50, }, ) with patch( "homeassistant.helpers.restore_state.RestoreEntity.async_get_last_state", return_value=mock_coro(fake_state), ): assert await async_setup_component( hass, light.DOMAIN, { light.DOMAIN: { "platform": "mqtt", "schema": "json", "name": "test", "command_topic": "test_light_rgb/set", "brightness": True, "color_temp": True, "effect": True, "hs": True, "rgb": True, "xy": True, "white_value": True, "qos": 2, } }, ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") == 95 assert state.attributes.get("hs_color") == (100, 100) assert state.attributes.get("effect") == "random" assert state.attributes.get("color_temp") == 100 assert state.attributes.get("white_value") == 50 assert state.attributes.get(ATTR_SUPPORTED_FEATURES) == 191 assert state.attributes.get(ATTR_ASSUMED_STATE) await common.async_turn_on(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with( "test_light_rgb/set", '{"state": "ON"}', 2, False ) mqtt_mock.async_publish.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_ON await common.async_turn_on(hass, "light.test", color_temp=90) mqtt_mock.async_publish.assert_called_once_with( "test_light_rgb/set", JsonValidator('{"state": "ON", "color_temp": 90}'), 2, False, ) mqtt_mock.async_publish.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_ON await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with( "test_light_rgb/set", '{"state": "OFF"}', 2, False ) mqtt_mock.async_publish.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_OFF mqtt_mock.reset_mock() await common.async_turn_on( hass, "light.test", brightness=50, xy_color=[0.123, 0.123] ) await common.async_turn_on(hass, "light.test", brightness=50, hs_color=[359, 78]) await common.async_turn_on( hass, "light.test", rgb_color=[255, 128, 0], white_value=80 ) mqtt_mock.async_publish.assert_has_calls( [ mock.call( "test_light_rgb/set", JsonValidator( '{"state": "ON", "color": {"r": 0, "g": 123, "b": 255,' ' "x": 0.14, "y": 0.131, "h": 210.824, "s": 100.0},' ' "brightness": 50}' ), 2, False, ), mock.call( "test_light_rgb/set", JsonValidator( '{"state": "ON", "color": {"r": 255, "g": 56, "b": 59,' ' "x": 0.654, "y": 0.301, "h": 359.0, "s": 78.0},' ' "brightness": 50}' ), 2, False, ), mock.call( "test_light_rgb/set", JsonValidator( '{"state": "ON", "color": {"r": 255, "g": 128, "b": 0,' ' "x": 0.611, "y": 0.375, "h": 30.118, "s": 100.0},' ' "white_value": 80}' ), 2, False, ), ], any_order=True, ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes["rgb_color"] == (255, 128, 0) assert state.attributes["brightness"] == 50 assert state.attributes["hs_color"] == (30.118, 100) assert state.attributes["white_value"] == 80 assert state.attributes["xy_color"] == (0.611, 0.375) async def test_sending_hs_color(hass, mqtt_mock): """Test light.turn_on with hs color sends hs color parameters.""" assert await async_setup_component( hass, light.DOMAIN, { light.DOMAIN: { "platform": "mqtt", "schema": "json", "name": "test", "command_topic": "test_light_rgb/set", "brightness": True, "hs": True, } }, ) state = hass.states.get("light.test") assert state.state == STATE_OFF mqtt_mock.reset_mock() await common.async_turn_on( hass, "light.test", brightness=50, xy_color=[0.123, 0.123] ) await common.async_turn_on(hass, "light.test", brightness=50, hs_color=[359, 78]) await common.async_turn_on( hass, "light.test", rgb_color=[255, 128, 0], white_value=80 ) mqtt_mock.async_publish.assert_has_calls( [ mock.call( "test_light_rgb/set", JsonValidator( '{"state": "ON", "color": {"h": 210.824, "s": 100.0},' ' "brightness": 50}' ), 0, False, ), mock.call( "test_light_rgb/set", JsonValidator( '{"state": "ON", "color": {"h": 359.0, "s": 78.0},' ' "brightness": 50}' ), 0, False, ), mock.call( "test_light_rgb/set", JsonValidator( '{"state": "ON", "color": {"h": 30.118, "s": 100.0},' ' "white_value": 80}' ), 0, False, ), ], any_order=True, ) async def test_sending_rgb_color_no_brightness(hass, mqtt_mock): """Test light.turn_on with hs color sends rgb color parameters.""" assert await async_setup_component( hass, light.DOMAIN, { light.DOMAIN: { "platform": "mqtt", "schema": "json", "name": "test", "command_topic": "test_light_rgb/set", "rgb": True, } }, ) state = hass.states.get("light.test") assert state.state == STATE_OFF await common.async_turn_on( hass, "light.test", brightness=50, xy_color=[0.123, 0.123] ) await common.async_turn_on(hass, "light.test", brightness=50, hs_color=[359, 78]) await common.async_turn_on( hass, "light.test", rgb_color=[255, 128, 0], brightness=255 ) mqtt_mock.async_publish.assert_has_calls( [ mock.call( "test_light_rgb/set", JsonValidator('{"state": "ON", "color": {"r": 0, "g": 24, "b": 50}}'), 0, False, ), mock.call( "test_light_rgb/set", JsonValidator('{"state": "ON", "color": {"r": 50, "g": 11, "b": 11}}'), 0, False, ), mock.call( "test_light_rgb/set", JsonValidator('{"state": "ON", "color": {"r": 255, "g": 128, "b": 0}}'), 0, False, ), ], any_order=True, ) async def test_sending_rgb_color_with_brightness(hass, mqtt_mock): """Test light.turn_on with hs color sends rgb color parameters.""" assert await async_setup_component( hass, light.DOMAIN, { light.DOMAIN: { "platform": "mqtt", "schema": "json", "name": "test", "command_topic": "test_light_rgb/set", "brightness": True, "rgb": True, } }, ) state = hass.states.get("light.test") assert state.state == STATE_OFF await common.async_turn_on( hass, "light.test", brightness=50, xy_color=[0.123, 0.123] ) await common.async_turn_on(hass, "light.test", brightness=50, hs_color=[359, 78]) await common.async_turn_on( hass, "light.test", rgb_color=[255, 128, 0], white_value=80 ) mqtt_mock.async_publish.assert_has_calls( [ mock.call( "test_light_rgb/set", JsonValidator( '{"state": "ON", "color": {"r": 0, "g": 123, "b": 255},' ' "brightness": 50}' ), 0, False, ), mock.call( "test_light_rgb/set", JsonValidator( '{"state": "ON", "color": {"r": 255, "g": 56, "b": 59},' ' "brightness": 50}' ), 0, False, ), mock.call( "test_light_rgb/set", JsonValidator( '{"state": "ON", "color": {"r": 255, "g": 128, "b": 0},' ' "white_value": 80}' ), 0, False, ), ], any_order=True, ) async def test_sending_xy_color(hass, mqtt_mock): """Test light.turn_on with hs color sends xy color parameters.""" assert await async_setup_component( hass, light.DOMAIN, { light.DOMAIN: { "platform": "mqtt", "schema": "json", "name": "test", "command_topic": "test_light_rgb/set", "brightness": True, "xy": True, } }, ) state = hass.states.get("light.test") assert state.state == STATE_OFF await common.async_turn_on( hass, "light.test", brightness=50, xy_color=[0.123, 0.123] ) await common.async_turn_on(hass, "light.test", brightness=50, hs_color=[359, 78]) await common.async_turn_on( hass, "light.test", rgb_color=[255, 128, 0], white_value=80 ) mqtt_mock.async_publish.assert_has_calls( [ mock.call( "test_light_rgb/set", JsonValidator( '{"state": "ON", "color": {"x": 0.14, "y": 0.131},' ' "brightness": 50}' ), 0, False, ), mock.call( "test_light_rgb/set", JsonValidator( '{"state": "ON", "color": {"x": 0.654, "y": 0.301},' ' "brightness": 50}' ), 0, False, ), mock.call( "test_light_rgb/set", JsonValidator( '{"state": "ON", "color": {"x": 0.611, "y": 0.375},' ' "white_value": 80}' ), 0, False, ), ], any_order=True, ) async def test_effect(hass, mqtt_mock): """Test for effect being sent when included.""" assert await async_setup_component( hass, light.DOMAIN, { light.DOMAIN: { "platform": "mqtt", "schema": "json", "name": "test", "command_topic": "test_light_rgb/set", "effect": True, "qos": 0, } }, ) state = hass.states.get("light.test") assert state.state == STATE_OFF assert state.attributes.get(ATTR_SUPPORTED_FEATURES) == 44 await common.async_turn_on(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with( "test_light_rgb/set", JsonValidator('{"state": "ON"}'), 0, False ) mqtt_mock.async_publish.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("effect") == "none" await common.async_turn_on(hass, "light.test", effect="rainbow") mqtt_mock.async_publish.assert_called_once_with( "test_light_rgb/set", JsonValidator('{"state": "ON", "effect": "rainbow"}'), 0, False, ) mqtt_mock.async_publish.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("effect") == "rainbow" await common.async_turn_on(hass, "light.test", effect="colorloop") mqtt_mock.async_publish.assert_called_once_with( "test_light_rgb/set", JsonValidator('{"state": "ON", "effect": "colorloop"}'), 0, False, ) mqtt_mock.async_publish.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("effect") == "colorloop" async def test_flash_short_and_long(hass, mqtt_mock): """Test for flash length being sent when included.""" assert await async_setup_component( hass, light.DOMAIN, { light.DOMAIN: { "platform": "mqtt", "schema": "json", "name": "test", "command_topic": "test_light_rgb/set", "flash_time_short": 5, "flash_time_long": 15, "qos": 0, } }, ) state = hass.states.get("light.test") assert state.state == STATE_OFF assert state.attributes.get(ATTR_SUPPORTED_FEATURES) == 40 await common.async_turn_on(hass, "light.test", flash="short") mqtt_mock.async_publish.assert_called_once_with( "test_light_rgb/set", JsonValidator('{"state": "ON", "flash": 5}'), 0, False ) mqtt_mock.async_publish.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_ON await common.async_turn_on(hass, "light.test", flash="long") mqtt_mock.async_publish.assert_called_once_with( "test_light_rgb/set", JsonValidator('{"state": "ON", "flash": 15}'), 0, False ) mqtt_mock.async_publish.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_ON async def test_transition(hass, mqtt_mock): """Test for transition time being sent when included.""" assert await async_setup_component( hass, light.DOMAIN, { light.DOMAIN: { "platform": "mqtt", "schema": "json", "name": "test", "command_topic": "test_light_rgb/set", "qos": 0, } }, ) state = hass.states.get("light.test") assert state.state == STATE_OFF assert state.attributes.get(ATTR_SUPPORTED_FEATURES) == 40 await common.async_turn_on(hass, "light.test", transition=15) mqtt_mock.async_publish.assert_called_once_with( "test_light_rgb/set", JsonValidator('{"state": "ON", "transition": 15}'), 0, False, ) mqtt_mock.async_publish.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_ON await common.async_turn_off(hass, "light.test", transition=30) mqtt_mock.async_publish.assert_called_once_with( "test_light_rgb/set", JsonValidator('{"state": "OFF", "transition": 30}'), 0, False, ) mqtt_mock.async_publish.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_OFF async def test_brightness_scale(hass, mqtt_mock): """Test for brightness scaling.""" assert await async_setup_component( hass, light.DOMAIN, { light.DOMAIN: { "platform": "mqtt", "schema": "json", "name": "test", "state_topic": "test_light_bright_scale", "command_topic": "test_light_bright_scale/set", "brightness": True, "brightness_scale": 99, } }, ) state = hass.states.get("light.test") assert state.state == STATE_OFF assert state.attributes.get("brightness") is None assert not state.attributes.get(ATTR_ASSUMED_STATE) # Turn on the light async_fire_mqtt_message(hass, "test_light_bright_scale", '{"state":"ON"}') state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") == 255 # Turn on the light with brightness async_fire_mqtt_message( hass, "test_light_bright_scale", '{"state":"ON", "brightness": 99}' ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") == 255 async def test_invalid_values(hass, mqtt_mock): """Test that invalid color/brightness/white/etc. values are ignored.""" assert await async_setup_component( hass, light.DOMAIN, { light.DOMAIN: { "platform": "mqtt", "schema": "json", "name": "test", "state_topic": "test_light_rgb", "command_topic": "test_light_rgb/set", "brightness": True, "color_temp": True, "rgb": True, "white_value": True, "qos": "0", } }, ) state = hass.states.get("light.test") assert state.state == STATE_OFF assert state.attributes.get(ATTR_SUPPORTED_FEATURES) == 187 assert state.attributes.get("rgb_color") is None assert state.attributes.get("brightness") is None assert state.attributes.get("white_value") is None assert state.attributes.get("color_temp") is None assert not state.attributes.get(ATTR_ASSUMED_STATE) # Turn on the light async_fire_mqtt_message( hass, "test_light_rgb", '{"state":"ON",' '"color":{"r":255,"g":255,"b":255},' '"brightness": 255,' '"white_value": 255,' '"color_temp": 100,' '"effect": "rainbow"}', ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("rgb_color") == (255, 255, 255) assert state.attributes.get("brightness") == 255 assert state.attributes.get("white_value") == 255 assert state.attributes.get("color_temp") == 100 # Bad HS color values async_fire_mqtt_message( hass, "test_light_rgb", '{"state":"ON",' '"color":{"h":"bad","s":"val"}}', ) # Color should not have changed state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("rgb_color") == (255, 255, 255) # Bad RGB color values async_fire_mqtt_message( hass, "test_light_rgb", '{"state":"ON",' '"color":{"r":"bad","g":"val","b":"test"}}', ) # Color should not have changed state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("rgb_color") == (255, 255, 255) # Bad XY color values async_fire_mqtt_message( hass, "test_light_rgb", '{"state":"ON",' '"color":{"x":"bad","y":"val"}}', ) # Color should not have changed state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("rgb_color") == (255, 255, 255) # Bad brightness values async_fire_mqtt_message( hass, "test_light_rgb", '{"state":"ON",' '"brightness": "badValue"}' ) # Brightness should not have changed state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") == 255 # Bad white value async_fire_mqtt_message( hass, "test_light_rgb", '{"state":"ON",' '"white_value": "badValue"}' ) # White value should not have changed state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("white_value") == 255 # Bad color temperature async_fire_mqtt_message( hass, "test_light_rgb", '{"state":"ON",' '"color_temp": "badValue"}' ) # Color temperature should not have changed state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("color_temp") == 100 async def test_availability_without_topic(hass, mqtt_mock): """Test availability without defined availability topic.""" await help_test_availability_without_topic( hass, mqtt_mock, light.DOMAIN, DEFAULT_CONFIG ) async def test_default_availability_payload(hass, mqtt_mock): """Test availability by default payload with defined topic.""" await help_test_default_availability_payload( hass, mqtt_mock, light.DOMAIN, DEFAULT_CONFIG ) async def test_custom_availability_payload(hass, mqtt_mock): """Test availability by custom payload with defined topic.""" await help_test_custom_availability_payload( hass, mqtt_mock, light.DOMAIN, DEFAULT_CONFIG ) async def test_setting_attribute_via_mqtt_json_message(hass, mqtt_mock): """Test the setting of attribute via MQTT with JSON payload.""" await help_test_setting_attribute_via_mqtt_json_message( hass, mqtt_mock, light.DOMAIN, DEFAULT_CONFIG ) async def test_setting_attribute_with_template(hass, mqtt_mock): """Test the setting of attribute via MQTT with JSON payload.""" await help_test_setting_attribute_with_template( hass, mqtt_mock, light.DOMAIN, DEFAULT_CONFIG ) async def test_update_with_json_attrs_not_dict(hass, mqtt_mock, caplog): """Test attributes get extracted from a JSON result.""" await help_test_update_with_json_attrs_not_dict( hass, mqtt_mock, caplog, light.DOMAIN, DEFAULT_CONFIG ) async def test_update_with_json_attrs_bad_JSON(hass, mqtt_mock, caplog): """Test attributes get extracted from a JSON result.""" await help_test_update_with_json_attrs_bad_JSON( hass, mqtt_mock, caplog, light.DOMAIN, DEFAULT_CONFIG ) async def test_discovery_update_attr(hass, mqtt_mock, caplog): """Test update of discovered MQTTAttributes.""" await help_test_discovery_update_attr( hass, mqtt_mock, caplog, light.DOMAIN, DEFAULT_CONFIG ) async def test_unique_id(hass): """Test unique id option only creates one light per unique_id.""" config = { light.DOMAIN: [ { "platform": "mqtt", "name": "Test 1", "schema": "json", "state_topic": "test-topic", "command_topic": "test_topic", "unique_id": "TOTALLY_UNIQUE", }, { "platform": "mqtt", "name": "Test 2", "schema": "json", "state_topic": "test-topic", "command_topic": "test_topic", "unique_id": "TOTALLY_UNIQUE", }, ] } await help_test_unique_id(hass, light.DOMAIN, config) async def test_discovery_removal(hass, mqtt_mock, caplog): """Test removal of discovered mqtt_json lights.""" data = '{ "name": "test",' ' "schema": "json",' ' "command_topic": "test_topic" }' await help_test_discovery_removal(hass, mqtt_mock, caplog, light.DOMAIN, data) async def test_discovery_update_light(hass, mqtt_mock, caplog): """Test update of discovered light.""" data1 = ( '{ "name": "Beer",' ' "schema": "json",' ' "state_topic": "test_topic",' ' "command_topic": "test_topic" }' ) data2 = ( '{ "name": "Milk",' ' "schema": "json",' ' "state_topic": "test_topic",' ' "command_topic": "test_topic" }' ) await help_test_discovery_update( hass, mqtt_mock, caplog, light.DOMAIN, data1, data2 ) async def test_discovery_broken(hass, mqtt_mock, caplog): """Test handling of bad discovery message.""" data1 = '{ "name": "Beer" }' data2 = ( '{ "name": "Milk",' ' "schema": "json",' ' "state_topic": "test_topic",' ' "command_topic": "test_topic" }' ) await help_test_discovery_broken( hass, mqtt_mock, caplog, light.DOMAIN, data1, data2 ) async def test_entity_device_info_with_connection(hass, mqtt_mock): """Test MQTT light device registry integration.""" await help_test_entity_device_info_with_connection( hass, mqtt_mock, light.DOMAIN, DEFAULT_CONFIG ) async def test_entity_device_info_with_identifier(hass, mqtt_mock): """Test MQTT light device registry integration.""" await help_test_entity_device_info_with_identifier( hass, mqtt_mock, light.DOMAIN, DEFAULT_CONFIG ) async def test_entity_device_info_update(hass, mqtt_mock): """Test device registry update.""" await help_test_entity_device_info_update( hass, mqtt_mock, light.DOMAIN, DEFAULT_CONFIG ) async def test_entity_device_info_remove(hass, mqtt_mock): """Test device registry remove.""" await help_test_entity_device_info_remove( hass, mqtt_mock, light.DOMAIN, DEFAULT_CONFIG ) async def test_entity_id_update_subscriptions(hass, mqtt_mock): """Test MQTT subscriptions are managed when entity_id is updated.""" await help_test_entity_id_update_subscriptions( hass, mqtt_mock, light.DOMAIN, DEFAULT_CONFIG ) async def test_entity_id_update_discovery_update(hass, mqtt_mock): """Test MQTT discovery update when entity_id is updated.""" await help_test_entity_id_update_discovery_update( hass, mqtt_mock, light.DOMAIN, DEFAULT_CONFIG )
30.912049
88
0.583094
import json from unittest import mock from unittest.mock import patch from homeassistant.components import light from homeassistant.const import ( ATTR_ASSUMED_STATE, ATTR_SUPPORTED_FEATURES, STATE_OFF, STATE_ON, ) import homeassistant.core as ha from homeassistant.setup import async_setup_component from .test_common import ( help_test_availability_without_topic, help_test_custom_availability_payload, help_test_default_availability_payload, help_test_discovery_broken, help_test_discovery_removal, help_test_discovery_update, help_test_discovery_update_attr, help_test_entity_device_info_remove, help_test_entity_device_info_update, help_test_entity_device_info_with_connection, help_test_entity_device_info_with_identifier, help_test_entity_id_update_discovery_update, help_test_entity_id_update_subscriptions, help_test_setting_attribute_via_mqtt_json_message, help_test_setting_attribute_with_template, help_test_unique_id, help_test_update_with_json_attrs_bad_JSON, help_test_update_with_json_attrs_not_dict, ) from tests.common import async_fire_mqtt_message, mock_coro from tests.components.light import common DEFAULT_CONFIG = { light.DOMAIN: { "platform": "mqtt", "schema": "json", "name": "test", "command_topic": "test-topic", } } class JsonValidator(object): def __init__(self, jsondata): self.jsondata = jsondata def __eq__(self, other): return json.loads(self.jsondata) == json.loads(other) async def test_fail_setup_if_no_command_topic(hass, mqtt_mock): assert await async_setup_component( hass, light.DOMAIN, {light.DOMAIN: {"platform": "mqtt", "schema": "json", "name": "test"}}, ) assert hass.states.get("light.test") is None async def test_no_color_brightness_color_temp_white_val_if_no_topics(hass, mqtt_mock): assert await async_setup_component( hass, light.DOMAIN, { light.DOMAIN: { "platform": "mqtt", "schema": "json", "name": "test", "state_topic": "test_light_rgb", "command_topic": "test_light_rgb/set", } }, ) state = hass.states.get("light.test") assert state.state == STATE_OFF assert state.attributes.get(ATTR_SUPPORTED_FEATURES) == 40 assert state.attributes.get("rgb_color") is None assert state.attributes.get("brightness") is None assert state.attributes.get("color_temp") is None assert state.attributes.get("effect") is None assert state.attributes.get("white_value") is None assert state.attributes.get("xy_color") is None assert state.attributes.get("hs_color") is None async_fire_mqtt_message(hass, "test_light_rgb", '{"state":"ON"}') state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("rgb_color") is None assert state.attributes.get("brightness") is None assert state.attributes.get("color_temp") is None assert state.attributes.get("effect") is None assert state.attributes.get("white_value") is None assert state.attributes.get("xy_color") is None assert state.attributes.get("hs_color") is None async def test_controlling_state_via_topic(hass, mqtt_mock): assert await async_setup_component( hass, light.DOMAIN, { light.DOMAIN: { "platform": "mqtt", "schema": "json", "name": "test", "state_topic": "test_light_rgb", "command_topic": "test_light_rgb/set", "brightness": True, "color_temp": True, "effect": True, "rgb": True, "white_value": True, "xy": True, "hs": True, "qos": "0", } }, ) state = hass.states.get("light.test") assert state.state == STATE_OFF assert state.attributes.get(ATTR_SUPPORTED_FEATURES) == 191 assert state.attributes.get("rgb_color") is None assert state.attributes.get("brightness") is None assert state.attributes.get("color_temp") is None assert state.attributes.get("effect") is None assert state.attributes.get("white_value") is None assert state.attributes.get("xy_color") is None assert state.attributes.get("hs_color") is None assert not state.attributes.get(ATTR_ASSUMED_STATE) async_fire_mqtt_message( hass, "test_light_rgb", '{"state":"ON",' '"color":{"r":255,"g":255,"b":255},' '"brightness":255,' '"color_temp":155,' '"effect":"colorloop",' '"white_value":150}', ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("rgb_color") == (255, 255, 255) assert state.attributes.get("brightness") == 255 assert state.attributes.get("color_temp") == 155 assert state.attributes.get("effect") == "colorloop" assert state.attributes.get("white_value") == 150 assert state.attributes.get("xy_color") == (0.323, 0.329) assert state.attributes.get("hs_color") == (0.0, 0.0) async_fire_mqtt_message(hass, "test_light_rgb", '{"state":"OFF"}') state = hass.states.get("light.test") assert state.state == STATE_OFF async_fire_mqtt_message(hass, "test_light_rgb", '{"state":"ON", "brightness":100}') light_state = hass.states.get("light.test") assert light_state.attributes["brightness"] == 100 async_fire_mqtt_message( hass, "test_light_rgb", '{"state":"ON", ' '"color":{"r":125,"g":125,"b":125}}' ) light_state = hass.states.get("light.test") assert light_state.attributes.get("rgb_color") == (255, 255, 255) async_fire_mqtt_message( hass, "test_light_rgb", '{"state":"ON", "color":{"x":0.135,"y":0.135}}' ) light_state = hass.states.get("light.test") assert light_state.attributes.get("xy_color") == (0.141, 0.14) async_fire_mqtt_message( hass, "test_light_rgb", '{"state":"ON", "color":{"h":180,"s":50}}' ) light_state = hass.states.get("light.test") assert light_state.attributes.get("hs_color") == (180.0, 50.0) async_fire_mqtt_message(hass, "test_light_rgb", '{"state":"ON", "color_temp":155}') light_state = hass.states.get("light.test") assert light_state.attributes.get("color_temp") == 155 async_fire_mqtt_message( hass, "test_light_rgb", '{"state":"ON", "effect":"colorloop"}' ) light_state = hass.states.get("light.test") assert light_state.attributes.get("effect") == "colorloop" async_fire_mqtt_message(hass, "test_light_rgb", '{"state":"ON", "white_value":155}') light_state = hass.states.get("light.test") assert light_state.attributes.get("white_value") == 155 async def test_sending_mqtt_commands_and_optimistic(hass, mqtt_mock): fake_state = ha.State( "light.test", "on", { "brightness": 95, "hs_color": [100, 100], "effect": "random", "color_temp": 100, "white_value": 50, }, ) with patch( "homeassistant.helpers.restore_state.RestoreEntity.async_get_last_state", return_value=mock_coro(fake_state), ): assert await async_setup_component( hass, light.DOMAIN, { light.DOMAIN: { "platform": "mqtt", "schema": "json", "name": "test", "command_topic": "test_light_rgb/set", "brightness": True, "color_temp": True, "effect": True, "hs": True, "rgb": True, "xy": True, "white_value": True, "qos": 2, } }, ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") == 95 assert state.attributes.get("hs_color") == (100, 100) assert state.attributes.get("effect") == "random" assert state.attributes.get("color_temp") == 100 assert state.attributes.get("white_value") == 50 assert state.attributes.get(ATTR_SUPPORTED_FEATURES) == 191 assert state.attributes.get(ATTR_ASSUMED_STATE) await common.async_turn_on(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with( "test_light_rgb/set", '{"state": "ON"}', 2, False ) mqtt_mock.async_publish.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_ON await common.async_turn_on(hass, "light.test", color_temp=90) mqtt_mock.async_publish.assert_called_once_with( "test_light_rgb/set", JsonValidator('{"state": "ON", "color_temp": 90}'), 2, False, ) mqtt_mock.async_publish.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_ON await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with( "test_light_rgb/set", '{"state": "OFF"}', 2, False ) mqtt_mock.async_publish.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_OFF mqtt_mock.reset_mock() await common.async_turn_on( hass, "light.test", brightness=50, xy_color=[0.123, 0.123] ) await common.async_turn_on(hass, "light.test", brightness=50, hs_color=[359, 78]) await common.async_turn_on( hass, "light.test", rgb_color=[255, 128, 0], white_value=80 ) mqtt_mock.async_publish.assert_has_calls( [ mock.call( "test_light_rgb/set", JsonValidator( '{"state": "ON", "color": {"r": 0, "g": 123, "b": 255,' ' "x": 0.14, "y": 0.131, "h": 210.824, "s": 100.0},' ' "brightness": 50}' ), 2, False, ), mock.call( "test_light_rgb/set", JsonValidator( '{"state": "ON", "color": {"r": 255, "g": 56, "b": 59,' ' "x": 0.654, "y": 0.301, "h": 359.0, "s": 78.0},' ' "brightness": 50}' ), 2, False, ), mock.call( "test_light_rgb/set", JsonValidator( '{"state": "ON", "color": {"r": 255, "g": 128, "b": 0,' ' "x": 0.611, "y": 0.375, "h": 30.118, "s": 100.0},' ' "white_value": 80}' ), 2, False, ), ], any_order=True, ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes["rgb_color"] == (255, 128, 0) assert state.attributes["brightness"] == 50 assert state.attributes["hs_color"] == (30.118, 100) assert state.attributes["white_value"] == 80 assert state.attributes["xy_color"] == (0.611, 0.375) async def test_sending_hs_color(hass, mqtt_mock): assert await async_setup_component( hass, light.DOMAIN, { light.DOMAIN: { "platform": "mqtt", "schema": "json", "name": "test", "command_topic": "test_light_rgb/set", "brightness": True, "hs": True, } }, ) state = hass.states.get("light.test") assert state.state == STATE_OFF mqtt_mock.reset_mock() await common.async_turn_on( hass, "light.test", brightness=50, xy_color=[0.123, 0.123] ) await common.async_turn_on(hass, "light.test", brightness=50, hs_color=[359, 78]) await common.async_turn_on( hass, "light.test", rgb_color=[255, 128, 0], white_value=80 ) mqtt_mock.async_publish.assert_has_calls( [ mock.call( "test_light_rgb/set", JsonValidator( '{"state": "ON", "color": {"h": 210.824, "s": 100.0},' ' "brightness": 50}' ), 0, False, ), mock.call( "test_light_rgb/set", JsonValidator( '{"state": "ON", "color": {"h": 359.0, "s": 78.0},' ' "brightness": 50}' ), 0, False, ), mock.call( "test_light_rgb/set", JsonValidator( '{"state": "ON", "color": {"h": 30.118, "s": 100.0},' ' "white_value": 80}' ), 0, False, ), ], any_order=True, ) async def test_sending_rgb_color_no_brightness(hass, mqtt_mock): assert await async_setup_component( hass, light.DOMAIN, { light.DOMAIN: { "platform": "mqtt", "schema": "json", "name": "test", "command_topic": "test_light_rgb/set", "rgb": True, } }, ) state = hass.states.get("light.test") assert state.state == STATE_OFF await common.async_turn_on( hass, "light.test", brightness=50, xy_color=[0.123, 0.123] ) await common.async_turn_on(hass, "light.test", brightness=50, hs_color=[359, 78]) await common.async_turn_on( hass, "light.test", rgb_color=[255, 128, 0], brightness=255 ) mqtt_mock.async_publish.assert_has_calls( [ mock.call( "test_light_rgb/set", JsonValidator('{"state": "ON", "color": {"r": 0, "g": 24, "b": 50}}'), 0, False, ), mock.call( "test_light_rgb/set", JsonValidator('{"state": "ON", "color": {"r": 50, "g": 11, "b": 11}}'), 0, False, ), mock.call( "test_light_rgb/set", JsonValidator('{"state": "ON", "color": {"r": 255, "g": 128, "b": 0}}'), 0, False, ), ], any_order=True, ) async def test_sending_rgb_color_with_brightness(hass, mqtt_mock): assert await async_setup_component( hass, light.DOMAIN, { light.DOMAIN: { "platform": "mqtt", "schema": "json", "name": "test", "command_topic": "test_light_rgb/set", "brightness": True, "rgb": True, } }, ) state = hass.states.get("light.test") assert state.state == STATE_OFF await common.async_turn_on( hass, "light.test", brightness=50, xy_color=[0.123, 0.123] ) await common.async_turn_on(hass, "light.test", brightness=50, hs_color=[359, 78]) await common.async_turn_on( hass, "light.test", rgb_color=[255, 128, 0], white_value=80 ) mqtt_mock.async_publish.assert_has_calls( [ mock.call( "test_light_rgb/set", JsonValidator( '{"state": "ON", "color": {"r": 0, "g": 123, "b": 255},' ' "brightness": 50}' ), 0, False, ), mock.call( "test_light_rgb/set", JsonValidator( '{"state": "ON", "color": {"r": 255, "g": 56, "b": 59},' ' "brightness": 50}' ), 0, False, ), mock.call( "test_light_rgb/set", JsonValidator( '{"state": "ON", "color": {"r": 255, "g": 128, "b": 0},' ' "white_value": 80}' ), 0, False, ), ], any_order=True, ) async def test_sending_xy_color(hass, mqtt_mock): assert await async_setup_component( hass, light.DOMAIN, { light.DOMAIN: { "platform": "mqtt", "schema": "json", "name": "test", "command_topic": "test_light_rgb/set", "brightness": True, "xy": True, } }, ) state = hass.states.get("light.test") assert state.state == STATE_OFF await common.async_turn_on( hass, "light.test", brightness=50, xy_color=[0.123, 0.123] ) await common.async_turn_on(hass, "light.test", brightness=50, hs_color=[359, 78]) await common.async_turn_on( hass, "light.test", rgb_color=[255, 128, 0], white_value=80 ) mqtt_mock.async_publish.assert_has_calls( [ mock.call( "test_light_rgb/set", JsonValidator( '{"state": "ON", "color": {"x": 0.14, "y": 0.131},' ' "brightness": 50}' ), 0, False, ), mock.call( "test_light_rgb/set", JsonValidator( '{"state": "ON", "color": {"x": 0.654, "y": 0.301},' ' "brightness": 50}' ), 0, False, ), mock.call( "test_light_rgb/set", JsonValidator( '{"state": "ON", "color": {"x": 0.611, "y": 0.375},' ' "white_value": 80}' ), 0, False, ), ], any_order=True, ) async def test_effect(hass, mqtt_mock): assert await async_setup_component( hass, light.DOMAIN, { light.DOMAIN: { "platform": "mqtt", "schema": "json", "name": "test", "command_topic": "test_light_rgb/set", "effect": True, "qos": 0, } }, ) state = hass.states.get("light.test") assert state.state == STATE_OFF assert state.attributes.get(ATTR_SUPPORTED_FEATURES) == 44 await common.async_turn_on(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with( "test_light_rgb/set", JsonValidator('{"state": "ON"}'), 0, False ) mqtt_mock.async_publish.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("effect") == "none" await common.async_turn_on(hass, "light.test", effect="rainbow") mqtt_mock.async_publish.assert_called_once_with( "test_light_rgb/set", JsonValidator('{"state": "ON", "effect": "rainbow"}'), 0, False, ) mqtt_mock.async_publish.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("effect") == "rainbow" await common.async_turn_on(hass, "light.test", effect="colorloop") mqtt_mock.async_publish.assert_called_once_with( "test_light_rgb/set", JsonValidator('{"state": "ON", "effect": "colorloop"}'), 0, False, ) mqtt_mock.async_publish.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("effect") == "colorloop" async def test_flash_short_and_long(hass, mqtt_mock): assert await async_setup_component( hass, light.DOMAIN, { light.DOMAIN: { "platform": "mqtt", "schema": "json", "name": "test", "command_topic": "test_light_rgb/set", "flash_time_short": 5, "flash_time_long": 15, "qos": 0, } }, ) state = hass.states.get("light.test") assert state.state == STATE_OFF assert state.attributes.get(ATTR_SUPPORTED_FEATURES) == 40 await common.async_turn_on(hass, "light.test", flash="short") mqtt_mock.async_publish.assert_called_once_with( "test_light_rgb/set", JsonValidator('{"state": "ON", "flash": 5}'), 0, False ) mqtt_mock.async_publish.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_ON await common.async_turn_on(hass, "light.test", flash="long") mqtt_mock.async_publish.assert_called_once_with( "test_light_rgb/set", JsonValidator('{"state": "ON", "flash": 15}'), 0, False ) mqtt_mock.async_publish.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_ON async def test_transition(hass, mqtt_mock): assert await async_setup_component( hass, light.DOMAIN, { light.DOMAIN: { "platform": "mqtt", "schema": "json", "name": "test", "command_topic": "test_light_rgb/set", "qos": 0, } }, ) state = hass.states.get("light.test") assert state.state == STATE_OFF assert state.attributes.get(ATTR_SUPPORTED_FEATURES) == 40 await common.async_turn_on(hass, "light.test", transition=15) mqtt_mock.async_publish.assert_called_once_with( "test_light_rgb/set", JsonValidator('{"state": "ON", "transition": 15}'), 0, False, ) mqtt_mock.async_publish.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_ON await common.async_turn_off(hass, "light.test", transition=30) mqtt_mock.async_publish.assert_called_once_with( "test_light_rgb/set", JsonValidator('{"state": "OFF", "transition": 30}'), 0, False, ) mqtt_mock.async_publish.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_OFF async def test_brightness_scale(hass, mqtt_mock): assert await async_setup_component( hass, light.DOMAIN, { light.DOMAIN: { "platform": "mqtt", "schema": "json", "name": "test", "state_topic": "test_light_bright_scale", "command_topic": "test_light_bright_scale/set", "brightness": True, "brightness_scale": 99, } }, ) state = hass.states.get("light.test") assert state.state == STATE_OFF assert state.attributes.get("brightness") is None assert not state.attributes.get(ATTR_ASSUMED_STATE) async_fire_mqtt_message(hass, "test_light_bright_scale", '{"state":"ON"}') state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") == 255 async_fire_mqtt_message( hass, "test_light_bright_scale", '{"state":"ON", "brightness": 99}' ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") == 255 async def test_invalid_values(hass, mqtt_mock): assert await async_setup_component( hass, light.DOMAIN, { light.DOMAIN: { "platform": "mqtt", "schema": "json", "name": "test", "state_topic": "test_light_rgb", "command_topic": "test_light_rgb/set", "brightness": True, "color_temp": True, "rgb": True, "white_value": True, "qos": "0", } }, ) state = hass.states.get("light.test") assert state.state == STATE_OFF assert state.attributes.get(ATTR_SUPPORTED_FEATURES) == 187 assert state.attributes.get("rgb_color") is None assert state.attributes.get("brightness") is None assert state.attributes.get("white_value") is None assert state.attributes.get("color_temp") is None assert not state.attributes.get(ATTR_ASSUMED_STATE) async_fire_mqtt_message( hass, "test_light_rgb", '{"state":"ON",' '"color":{"r":255,"g":255,"b":255},' '"brightness": 255,' '"white_value": 255,' '"color_temp": 100,' '"effect": "rainbow"}', ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("rgb_color") == (255, 255, 255) assert state.attributes.get("brightness") == 255 assert state.attributes.get("white_value") == 255 assert state.attributes.get("color_temp") == 100 async_fire_mqtt_message( hass, "test_light_rgb", '{"state":"ON",' '"color":{"h":"bad","s":"val"}}', ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("rgb_color") == (255, 255, 255) async_fire_mqtt_message( hass, "test_light_rgb", '{"state":"ON",' '"color":{"r":"bad","g":"val","b":"test"}}', ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("rgb_color") == (255, 255, 255) async_fire_mqtt_message( hass, "test_light_rgb", '{"state":"ON",' '"color":{"x":"bad","y":"val"}}', ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("rgb_color") == (255, 255, 255) async_fire_mqtt_message( hass, "test_light_rgb", '{"state":"ON",' '"brightness": "badValue"}' ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") == 255 async_fire_mqtt_message( hass, "test_light_rgb", '{"state":"ON",' '"white_value": "badValue"}' ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("white_value") == 255 async_fire_mqtt_message( hass, "test_light_rgb", '{"state":"ON",' '"color_temp": "badValue"}' ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("color_temp") == 100 async def test_availability_without_topic(hass, mqtt_mock): await help_test_availability_without_topic( hass, mqtt_mock, light.DOMAIN, DEFAULT_CONFIG ) async def test_default_availability_payload(hass, mqtt_mock): await help_test_default_availability_payload( hass, mqtt_mock, light.DOMAIN, DEFAULT_CONFIG ) async def test_custom_availability_payload(hass, mqtt_mock): await help_test_custom_availability_payload( hass, mqtt_mock, light.DOMAIN, DEFAULT_CONFIG ) async def test_setting_attribute_via_mqtt_json_message(hass, mqtt_mock): await help_test_setting_attribute_via_mqtt_json_message( hass, mqtt_mock, light.DOMAIN, DEFAULT_CONFIG ) async def test_setting_attribute_with_template(hass, mqtt_mock): await help_test_setting_attribute_with_template( hass, mqtt_mock, light.DOMAIN, DEFAULT_CONFIG ) async def test_update_with_json_attrs_not_dict(hass, mqtt_mock, caplog): await help_test_update_with_json_attrs_not_dict( hass, mqtt_mock, caplog, light.DOMAIN, DEFAULT_CONFIG ) async def test_update_with_json_attrs_bad_JSON(hass, mqtt_mock, caplog): await help_test_update_with_json_attrs_bad_JSON( hass, mqtt_mock, caplog, light.DOMAIN, DEFAULT_CONFIG ) async def test_discovery_update_attr(hass, mqtt_mock, caplog): await help_test_discovery_update_attr( hass, mqtt_mock, caplog, light.DOMAIN, DEFAULT_CONFIG ) async def test_unique_id(hass): config = { light.DOMAIN: [ { "platform": "mqtt", "name": "Test 1", "schema": "json", "state_topic": "test-topic", "command_topic": "test_topic", "unique_id": "TOTALLY_UNIQUE", }, { "platform": "mqtt", "name": "Test 2", "schema": "json", "state_topic": "test-topic", "command_topic": "test_topic", "unique_id": "TOTALLY_UNIQUE", }, ] } await help_test_unique_id(hass, light.DOMAIN, config) async def test_discovery_removal(hass, mqtt_mock, caplog): data = '{ "name": "test",' ' "schema": "json",' ' "command_topic": "test_topic" }' await help_test_discovery_removal(hass, mqtt_mock, caplog, light.DOMAIN, data) async def test_discovery_update_light(hass, mqtt_mock, caplog): data1 = ( '{ "name": "Beer",' ' "schema": "json",' ' "state_topic": "test_topic",' ' "command_topic": "test_topic" }' ) data2 = ( '{ "name": "Milk",' ' "schema": "json",' ' "state_topic": "test_topic",' ' "command_topic": "test_topic" }' ) await help_test_discovery_update( hass, mqtt_mock, caplog, light.DOMAIN, data1, data2 ) async def test_discovery_broken(hass, mqtt_mock, caplog): data1 = '{ "name": "Beer" }' data2 = ( '{ "name": "Milk",' ' "schema": "json",' ' "state_topic": "test_topic",' ' "command_topic": "test_topic" }' ) await help_test_discovery_broken( hass, mqtt_mock, caplog, light.DOMAIN, data1, data2 ) async def test_entity_device_info_with_connection(hass, mqtt_mock): await help_test_entity_device_info_with_connection( hass, mqtt_mock, light.DOMAIN, DEFAULT_CONFIG ) async def test_entity_device_info_with_identifier(hass, mqtt_mock): await help_test_entity_device_info_with_identifier( hass, mqtt_mock, light.DOMAIN, DEFAULT_CONFIG ) async def test_entity_device_info_update(hass, mqtt_mock): await help_test_entity_device_info_update( hass, mqtt_mock, light.DOMAIN, DEFAULT_CONFIG ) async def test_entity_device_info_remove(hass, mqtt_mock): await help_test_entity_device_info_remove( hass, mqtt_mock, light.DOMAIN, DEFAULT_CONFIG ) async def test_entity_id_update_subscriptions(hass, mqtt_mock): await help_test_entity_id_update_subscriptions( hass, mqtt_mock, light.DOMAIN, DEFAULT_CONFIG ) async def test_entity_id_update_discovery_update(hass, mqtt_mock): await help_test_entity_id_update_discovery_update( hass, mqtt_mock, light.DOMAIN, DEFAULT_CONFIG )
true
true
f717922d65b80aab39f063f12af29d0dc7bc2b8a
4,431
py
Python
tests/test_settings.py
lulle2007200/EasyClangComplete
55d2c47d9f1b9f2bc85e6cc6de8b92457d9bbeb6
[ "MIT" ]
648
2016-04-18T16:10:47.000Z
2022-03-30T01:48:53.000Z
tests/test_settings.py
lulle2007200/EasyClangComplete
55d2c47d9f1b9f2bc85e6cc6de8b92457d9bbeb6
[ "MIT" ]
672
2016-04-24T13:55:35.000Z
2022-03-23T06:38:42.000Z
tests/test_settings.py
lulle2007200/EasyClangComplete
55d2c47d9f1b9f2bc85e6cc6de8b92457d9bbeb6
[ "MIT" ]
130
2016-05-26T19:27:00.000Z
2022-01-15T10:24:17.000Z
"""Tests for settings.""" import sublime import imp from os import path from EasyClangComplete.tests.gui_test_wrapper import GuiTestWrapper from EasyClangComplete.plugin.settings import settings_manager from EasyClangComplete.plugin.settings import settings_storage from EasyClangComplete.plugin.utils import flag imp.reload(settings_manager) imp.reload(settings_storage) imp.reload(flag) SettingsManager = settings_manager.SettingsManager SettingsStorage = settings_storage.SettingsStorage Flag = flag.Flag class test_settings(GuiTestWrapper): """Test settings.""" def test_setup_view(self): """Test that setup view correctly sets up the view.""" file_name = path.join(path.dirname(__file__), 'test_files', 'test.cpp') self.check_view(file_name) def test_init(self): """Test that settings are correctly initialized.""" manager = SettingsManager() settings = manager.user_settings() self.assertIsNotNone(settings.verbose) self.assertIsNotNone(settings.triggers) self.assertIsNotNone(settings.common_flags) self.assertIsNotNone(settings.clang_binary) self.assertIsNotNone(settings.flags_sources) self.assertIsNotNone(settings.show_errors) self.assertIsNotNone(settings.valid_lang_syntaxes) def test_valid(self): """Test validity.""" manager = SettingsManager() settings = manager.user_settings() valid, _ = settings.is_valid() self.assertTrue(valid) def test_parse_cmake_flags(self): """Testing that we can parse cmake flags.""" file_name = path.join(path.dirname(__file__), 'test_files', 'test_wrong_triggers.cpp') self.set_up_view(file_name) current_folder = path.dirname(__file__) flags_sources = [ { "file": "CMakeLists.txt", "flags": [ "-DBLAH={}/*".format(current_folder), "-DSMTH=ON", "-D XXX=1", "-D FLAG=word" ] } ] self.view.settings().set("flags_sources", flags_sources) settings = SettingsManager().user_settings() settings.update_from_view(self.view, project_specific=False) valid, _ = settings.is_valid() self.assertTrue(valid) self.assertEquals(len(settings.flags_sources), 1) entry = settings.flags_sources[0] self.assertIn('flags', entry) flags = entry['flags'] self.assertEquals(len(flags), 4) self.assertIn('-DSMTH=ON', flags) self.assertIn('-D FLAG=word', flags) self.assertIn('-D XXX=1', flags) import glob all_files = glob.glob(path.join(current_folder, "*")) for file in all_files: self.assertIn(file, flags[0]) def test_populate_flags(self): """Testing include population.""" # open any existing file file_name = path.join(path.dirname(__file__), 'test_files', 'test_wrong_triggers.cpp') self.set_up_view(file_name) # now test the things manager = SettingsManager() settings = manager.user_settings() valid, _ = settings.is_valid() self.assertTrue(valid) p = path.join(sublime.packages_path(), "User", "EasyClangComplete.sublime-settings") if path.exists(p): user = sublime.load_resource( "Packages/User/EasyClangComplete.sublime-settings") if "common_flags" in user: # The user modified the default common flags, just skip the # next few tests. return initial_common_flags = list(settings.common_flags) settings = manager.settings_for_view(self.view) dirs = settings.common_flags self.assertTrue(len(initial_common_flags) <= len(dirs)) reference_flag_0 = Flag.Builder().from_unparsed_string( initial_common_flags[0]).build() self.assertIn(reference_flag_0, dirs) reference_flag_1 = Flag.Builder().from_unparsed_string( initial_common_flags[1]).build() self.assertNotIn(reference_flag_1, dirs)
35.448
75
0.612051
import sublime import imp from os import path from EasyClangComplete.tests.gui_test_wrapper import GuiTestWrapper from EasyClangComplete.plugin.settings import settings_manager from EasyClangComplete.plugin.settings import settings_storage from EasyClangComplete.plugin.utils import flag imp.reload(settings_manager) imp.reload(settings_storage) imp.reload(flag) SettingsManager = settings_manager.SettingsManager SettingsStorage = settings_storage.SettingsStorage Flag = flag.Flag class test_settings(GuiTestWrapper): def test_setup_view(self): file_name = path.join(path.dirname(__file__), 'test_files', 'test.cpp') self.check_view(file_name) def test_init(self): manager = SettingsManager() settings = manager.user_settings() self.assertIsNotNone(settings.verbose) self.assertIsNotNone(settings.triggers) self.assertIsNotNone(settings.common_flags) self.assertIsNotNone(settings.clang_binary) self.assertIsNotNone(settings.flags_sources) self.assertIsNotNone(settings.show_errors) self.assertIsNotNone(settings.valid_lang_syntaxes) def test_valid(self): manager = SettingsManager() settings = manager.user_settings() valid, _ = settings.is_valid() self.assertTrue(valid) def test_parse_cmake_flags(self): file_name = path.join(path.dirname(__file__), 'test_files', 'test_wrong_triggers.cpp') self.set_up_view(file_name) current_folder = path.dirname(__file__) flags_sources = [ { "file": "CMakeLists.txt", "flags": [ "-DBLAH={}/*".format(current_folder), "-DSMTH=ON", "-D XXX=1", "-D FLAG=word" ] } ] self.view.settings().set("flags_sources", flags_sources) settings = SettingsManager().user_settings() settings.update_from_view(self.view, project_specific=False) valid, _ = settings.is_valid() self.assertTrue(valid) self.assertEquals(len(settings.flags_sources), 1) entry = settings.flags_sources[0] self.assertIn('flags', entry) flags = entry['flags'] self.assertEquals(len(flags), 4) self.assertIn('-DSMTH=ON', flags) self.assertIn('-D FLAG=word', flags) self.assertIn('-D XXX=1', flags) import glob all_files = glob.glob(path.join(current_folder, "*")) for file in all_files: self.assertIn(file, flags[0]) def test_populate_flags(self): file_name = path.join(path.dirname(__file__), 'test_files', 'test_wrong_triggers.cpp') self.set_up_view(file_name) manager = SettingsManager() settings = manager.user_settings() valid, _ = settings.is_valid() self.assertTrue(valid) p = path.join(sublime.packages_path(), "User", "EasyClangComplete.sublime-settings") if path.exists(p): user = sublime.load_resource( "Packages/User/EasyClangComplete.sublime-settings") if "common_flags" in user: return initial_common_flags = list(settings.common_flags) settings = manager.settings_for_view(self.view) dirs = settings.common_flags self.assertTrue(len(initial_common_flags) <= len(dirs)) reference_flag_0 = Flag.Builder().from_unparsed_string( initial_common_flags[0]).build() self.assertIn(reference_flag_0, dirs) reference_flag_1 = Flag.Builder().from_unparsed_string( initial_common_flags[1]).build() self.assertNotIn(reference_flag_1, dirs)
true
true
f71792385df7b999e78480b6b8bb47ec29d5d377
922
py
Python
arrays/countNumberOfPairsWithAbsoluteDifferenceK.py
kushvr7/High-On-DSA
d424bd48e35ebd1a588d96c1c0dcb5a9c47a0ef1
[ "MIT" ]
76
2021-12-12T08:42:20.000Z
2022-03-31T19:48:46.000Z
arrays/countNumberOfPairsWithAbsoluteDifferenceK.py
kushvr7/High-On-DSA
d424bd48e35ebd1a588d96c1c0dcb5a9c47a0ef1
[ "MIT" ]
4
2022-01-04T09:58:39.000Z
2022-03-30T17:00:39.000Z
arrays/countNumberOfPairsWithAbsoluteDifferenceK.py
kushvr7/High-On-DSA
d424bd48e35ebd1a588d96c1c0dcb5a9c47a0ef1
[ "MIT" ]
13
2021-12-12T14:44:41.000Z
2022-03-10T14:08:20.000Z
# https://leetcode.com/problems/count-number-of-pairs-with-absolute-difference-k/ from collections import Counter class Solution(object): # Brute Force Approach # TC : O(N # SC : O(N) def countKDifference(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ count =0 for i in range(len(nums)): for j in range(i, len(nums)): if abs(nums[i]-nums[j])==k: count +=1 return count def countKDifference(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ dictionary =Counter() count=0 for i in nums: dictionary[i]+=1 count += dictionary[i-k] + dictionary[i+k] return count
23.05
81
0.452278
from collections import Counter class Solution(object): def countKDifference(self, nums, k): count =0 for i in range(len(nums)): for j in range(i, len(nums)): if abs(nums[i]-nums[j])==k: count +=1 return count def countKDifference(self, nums, k): dictionary =Counter() count=0 for i in nums: dictionary[i]+=1 count += dictionary[i-k] + dictionary[i+k] return count
true
true
f71792d21101ca8f9fdb2b92a64c021d5e816fea
28,771
py
Python
pyspark/bigdl/transform/vision/image.py
twicoder/BigDL
f065db372e1c682fa4a7903e287bba21d5f46750
[ "Apache-2.0" ]
55
2018-01-12T01:43:29.000Z
2021-03-09T02:35:56.000Z
pyspark/bigdl/transform/vision/image.py
jason-hzw/BigDL
ef4f4137965147e2bc59e41f40c4acbb50eeda97
[ "Apache-2.0" ]
4
2018-01-15T07:34:41.000Z
2018-01-16T05:46:12.000Z
pyspark/bigdl/transform/vision/image.py
jason-hzw/BigDL
ef4f4137965147e2bc59e41f40c4acbb50eeda97
[ "Apache-2.0" ]
22
2018-01-15T14:18:15.000Z
2019-12-16T18:51:33.000Z
# # Copyright 2016 The BigDL Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import sys from bigdl.util.common import JavaValue from bigdl.util.common import callBigDlFunc from bigdl.util.common import * if sys.version >= '3': long = int unicode = str class FeatureTransformer(JavaValue): """ FeatureTransformer is a transformer that transform ImageFeature """ def __init__(self, bigdl_type="float", *args): self.value = callBigDlFunc( bigdl_type, JavaValue.jvm_class_constructor(self), *args) def transform(self, image_feature, bigdl_type="float"): """ transform ImageFeature """ callBigDlFunc(bigdl_type, "transformImageFeature", self.value, image_feature) return image_feature def __call__(self, image_frame, bigdl_type="float"): """ transform ImageFrame """ jframe = callBigDlFunc(bigdl_type, "transformImageFrame", self.value, image_frame) return ImageFrame(jvalue=jframe) class Pipeline(FeatureTransformer): """ Pipeline of FeatureTransformer """ def __init__(self, transformers, bigdl_type="float"): for transfomer in transformers: assert transfomer.__class__.__bases__[0].__name__ == "FeatureTransformer", "the transformer should be " \ "subclass of FeatureTransformer" super(Pipeline, self).__init__(bigdl_type, transformers) class ImageFeature(JavaValue): """ Each ImageFeature keeps information about single image, it can include various status of an image, e.g. original bytes read from image file, an opencv mat, pixels in float array, image label, meta data and so on. it uses HashMap to store all these data, the key is string that identify the corresponding value """ def __init__(self, image=None, label=None, path=None, bigdl_type="float"): image_tensor = JTensor.from_ndarray(image) if image is not None else None label_tensor = JTensor.from_ndarray(label) if label is not None else None self.bigdl_type = bigdl_type self.value = callBigDlFunc( bigdl_type, JavaValue.jvm_class_constructor(self), image_tensor, label_tensor, path) def get_image(self, float_key="floats", to_chw=True): """ get image as ndarray from ImageFeature """ tensor = callBigDlFunc(self.bigdl_type, "imageFeatureToImageTensor", self.value, float_key, to_chw) return tensor.to_ndarray() def get_label(self): """ get label as ndarray from ImageFeature """ label = callBigDlFunc(self.bigdl_type, "imageFeatureToLabelTensor", self.value) return label.to_ndarray() def keys(self): """ get key set from ImageFeature """ return callBigDlFunc(self.bigdl_type, "imageFeatureGetKeys", self.value) class ImageFrame(JavaValue): """ ImageFrame wraps a set of ImageFeature """ def __init__(self, jvalue, bigdl_type="float"): self.value = jvalue self.bigdl_type = bigdl_type if self.is_local(): self.image_frame = LocalImageFrame(jvalue=self.value) else: self.image_frame = DistributedImageFrame(jvalue=self.value) @classmethod def read(cls, path, sc=None, min_partitions=1, bigdl_type="float"): """ Read images as Image Frame if sc is defined, Read image as DistributedImageFrame from local file system or HDFS if sc is null, Read image as LocalImageFrame from local file system :param path path to read images if sc is defined, path can be local or HDFS. Wildcard character are supported. if sc is null, path is local directory/image file/image file with wildcard character :param sc SparkContext :param min_partitions A suggestion value of the minimal splitting number for input data. :return ImageFrame """ return ImageFrame(jvalue=callBigDlFunc(bigdl_type, "read", path, sc, min_partitions)) @classmethod def read_parquet(cls, path, sc, bigdl_type="float"): """ Read parquet file as DistributedImageFrame """ return DistributedImageFrame(jvalue=callBigDlFunc(bigdl_type, "readParquet", path, sc)) @classmethod def write_parquet(cls, path, output, sc, partition_num = 1, bigdl_type="float"): """ write ImageFrame as parquet file """ return callBigDlFunc(bigdl_type, "writeParquet", path, output, sc, partition_num) def is_local(self): """ whether this is a LocalImageFrame """ return callBigDlFunc(self.bigdl_type, "isLocal", self.value) def is_distributed(self): """ whether this is a DistributedImageFrame """ return callBigDlFunc(self.bigdl_type, "isDistributed", self.value) def transform(self, transformer, bigdl_type="float"): """ transformImageFrame """ self.value = callBigDlFunc(bigdl_type, "transformImageFrame", transformer, self.value) return self def get_image(self, float_key="floats", to_chw=True): """ get image from ImageFrame """ return self.image_frame.get_image(float_key, to_chw) def get_label(self): """ get label from ImageFrame """ return self.image_frame.get_label() def get_predict(self, key="predict"): """ get prediction from ImageFrame """ return self.image_frame.get_predict(key) def get_sample(self): """ get sample from ImageFrame """ return self.image_frame.get_sample() def get_uri(self): """ get uri from imageframe """ return self.image_frame.get_uri() def set_label(self, label, bigdl_type="float"): """ set label for imageframe """ return callBigDlFunc(bigdl_type, "setLabel", label, self.value) def random_split(self, weights): """ Random split imageframes according to weights :param weights: weights for each ImageFrame :return: """ jvalues = self.image_frame.random_split(weights) return [ImageFrame(jvalue) for jvalue in jvalues] class LocalImageFrame(ImageFrame): """ LocalImageFrame wraps a list of ImageFeature """ def __init__(self, image_list=None, label_list=None, jvalue=None, bigdl_type="float"): assert jvalue or image_list, "jvalue and image_list cannot be None in the same time" if jvalue: self.value = jvalue else: # init from image ndarray list and label rdd(optional) image_tensor_list = map(lambda image: JTensor.from_ndarray(image), image_list) label_tensor_list = map(lambda label: JTensor.from_ndarray(label), label_list) if label_list else None self.value = callBigDlFunc(bigdl_type, JavaValue.jvm_class_constructor(self), image_tensor_list, label_tensor_list) self.bigdl_type = bigdl_type def get_image(self, float_key="floats", to_chw=True): """ get image list from ImageFrame """ tensors = callBigDlFunc(self.bigdl_type, "localImageFrameToImageTensor", self.value, float_key, to_chw) return map(lambda tensor: tensor.to_ndarray(), tensors) def get_label(self): """ get label list from ImageFrame """ labels = callBigDlFunc(self.bigdl_type, "localImageFrameToLabelTensor", self.value) return map(lambda tensor: tensor.to_ndarray(), labels) def get_predict(self, key="predict"): """ get prediction list from ImageFrame """ predicts = callBigDlFunc(self.bigdl_type, "localImageFrameToPredict", self.value, key) return map(lambda predict: (predict[0], predict[1].to_ndarray()) if predict[1] else (predict[0], None), predicts) def get_sample(self, key="sample"): return callBigDlFunc(self.bigdl_type, "localImageFrameToSample", self.value, key) def get_uri(self, key = "uri"): return callBigDlFunc(self.bigdl_type, "localImageFrameToUri", self.value, key) def random_split(self, weights): raise "random split not supported in LocalImageFrame" class DistributedImageFrame(ImageFrame): """ DistributedImageFrame wraps an RDD of ImageFeature """ def __init__(self, image_rdd=None, label_rdd=None, jvalue=None, bigdl_type="float"): assert jvalue or image_rdd, "jvalue and image_rdd cannot be None in the same time" if jvalue: self.value = jvalue else: # init from image ndarray rdd and label rdd(optional) image_tensor_rdd = image_rdd.map(lambda image: JTensor.from_ndarray(image)) label_tensor_rdd = label_rdd.map(lambda label: JTensor.from_ndarray(label)) if label_rdd else None self.value = callBigDlFunc(bigdl_type, JavaValue.jvm_class_constructor(self), image_tensor_rdd, label_tensor_rdd) self.bigdl_type = bigdl_type def get_image(self, float_key="floats", to_chw=True): """ get image rdd from ImageFrame """ tensor_rdd = callBigDlFunc(self.bigdl_type, "distributedImageFrameToImageTensorRdd", self.value, float_key, to_chw) return tensor_rdd.map(lambda tensor: tensor.to_ndarray()) def get_label(self): """ get label rdd from ImageFrame """ tensor_rdd = callBigDlFunc(self.bigdl_type, "distributedImageFrameToLabelTensorRdd", self.value) return tensor_rdd.map(lambda tensor: tensor.to_ndarray()) def get_predict(self, key="predict"): """ get prediction rdd from ImageFrame """ predicts = callBigDlFunc(self.bigdl_type, "distributedImageFrameToPredict", self.value, key) return predicts.map(lambda predict: (predict[0], predict[1].to_ndarray()) if predict[1] else (predict[0], None)) def get_sample(self, key="sample"): return callBigDlFunc(self.bigdl_type, "distributedImageFrameToSample", self.value, key) def get_uri(self, key = "uri"): return callBigDlFunc(self.bigdl_type, "distributedImageFrameToUri", self.value, key) def random_split(self, weights): return callBigDlFunc(self.bigdl_type, "distributedImageFrameRandomSplit", self.value, weights) class HFlip(FeatureTransformer): """ Flip the image horizontally """ def __init__(self, bigdl_type="float"): super(HFlip, self).__init__(bigdl_type) class Resize(FeatureTransformer): """ Resize image :param resize_h height after resize :param resize_w width after resize :param resize_mode if resizeMode = -1, random select a mode from (Imgproc.INTER_LINEAR, Imgproc.INTER_CUBIC, Imgproc.INTER_AREA, Imgproc.INTER_NEAREST, Imgproc.INTER_LANCZOS4) :param use_scale_factor if true, scale factor fx and fy is used, fx = fy = 0 note that the result of the following are different Imgproc.resize(mat, mat, new Size(resizeWH, resizeWH), 0, 0, Imgproc.INTER_LINEAR) Imgproc.resize(mat, mat, new Size(resizeWH, resizeWH)) """ def __init__(self, resize_h, resize_w, resize_mode = 1, use_scale_factor=True, bigdl_type="float"): super(Resize, self).__init__(bigdl_type, resize_h, resize_w, resize_mode, use_scale_factor) class Brightness(FeatureTransformer): """ adjust the image brightness :param deltaLow brightness parameter: low bound :param deltaHigh brightness parameter: high bound """ def __init__(self, delta_low, delta_high, bigdl_type="float"): super(Brightness, self).__init__(bigdl_type, delta_low, delta_high) class ChannelOrder(FeatureTransformer): """ random change the channel of an image """ def __init__(self, bigdl_type="float"): super(ChannelOrder, self).__init__(bigdl_type) class Contrast(FeatureTransformer): """ Adjust the image contrast :param delta_low contrast parameter low bound :param delta_high contrast parameter high bound """ def __init__(self, delta_low, delta_high, bigdl_type="float"): super(Contrast, self).__init__(bigdl_type, delta_low, delta_high) class Saturation(FeatureTransformer): """ Adjust image saturation """ def __init__(self, delta_low, delta_high, bigdl_type="float"): super(Saturation, self).__init__(bigdl_type, delta_low, delta_high) class Hue(FeatureTransformer): """ Adjust image hue :param delta_low hue parameter: low bound :param delta_high hue parameter: high bound """ def __init__(self, delta_low, delta_high, bigdl_type="float"): super(Hue, self).__init__(bigdl_type, delta_low, delta_high) class ChannelNormalize(FeatureTransformer): """ image channel normalize :param mean_r mean value in R channel :param mean_g mean value in G channel :param meanB_b mean value in B channel :param std_r std value in R channel :param std_g std value in G channel :param std_b std value in B channel """ def __init__(self, mean_r, mean_g, mean_b, std_r=1.0, std_g=1.0, std_b=1.0, bigdl_type="float"): super(ChannelNormalize, self).__init__(bigdl_type, mean_r, mean_g, mean_b, std_r, std_g, std_b) class PixelNormalize(FeatureTransformer): """ Pixel level normalizer, data(i) = data(i) - mean(i) :param means pixel level mean, following H * W * C order """ def __init__(self, means, bigdl_type="float"): super(PixelNormalize, self).__init__(bigdl_type, means) class RandomCrop(FeatureTransformer): """ Random crop a `cropWidth` x `cropHeight` patch from an image. The patch size should be less than the image size. :param crop_width width after crop :param crop_height height after crop :param is_clip whether to clip the roi to image boundaries """ def __init__(self, crop_width, crop_height, is_clip=True, bigdl_type="float"): super(RandomCrop, self).__init__(bigdl_type, crop_width, crop_height, is_clip) class CenterCrop(FeatureTransformer): """ Crop a `cropWidth` x `cropHeight` patch from center of image. The patch size should be less than the image size. :param crop_width width after crop :param crop_height height after crop :param is_clip clip cropping box boundary """ def __init__(self, crop_width, crop_height, is_clip=True, bigdl_type="float"): super(CenterCrop, self).__init__(bigdl_type, crop_width, crop_height, is_clip) class FixedCrop(FeatureTransformer): """ Crop a fixed area of image :param x1 start in width :param y1 start in height :param x2 end in width :param y2 end in height :param normalized whether args are normalized, i.e. in range [0, 1] :param is_clip whether to clip the roi to image boundaries """ def __init__(self, x1, y1, x2, y2, normalized=True, is_clip=True, bigdl_type="float"): super(FixedCrop, self).__init__(bigdl_type, x1, y1, x2, y2, normalized, is_clip) class DetectionCrop(FeatureTransformer): """ Crop from object detections, each image should has a tensor detection, which is stored in ImageFeature :param roi_key key that map a tensor detection :param normalized whether is detection is normalized, i.e. in range [0, 1] """ def __init__(self, roi_key, normalized=True, bigdl_type="float"): super(DetectionCrop, self).__init__(bigdl_type, roi_key, normalized) class Expand(FeatureTransformer): """ expand image, fill the blank part with the meanR, meanG, meanB :param means_r means in R channel :param means_g means in G channel :param means_b means in B channel :param min_expand_ratio min expand ratio :param max_expand_ratio max expand ratio """ def __init__(self, means_r=123, means_g=117, means_b=104, min_expand_ratio=1.0, max_expand_ratio=4.0, bigdl_type="float"): super(Expand, self).__init__(bigdl_type, means_r, means_g, means_b, min_expand_ratio, max_expand_ratio) class Filler(FeatureTransformer): """ Fill part of image with certain pixel value :param start_x start x ratio :param start_y start y ratio :param end_x end x ratio :param end_y end y ratio :param value filling value """ def __init__(self, start_x, start_y, end_x, end_y, value = 255, bigdl_type="float"): super(Filler, self).__init__(bigdl_type, start_x, start_y, end_x, end_y, value) class RandomTransformer(FeatureTransformer): """ It is a wrapper for transformers to control the transform probability :param transformer transformer to apply randomness :param prob max prob """ def __init__(self, transformer, prob, bigdl_type="float"): super(RandomTransformer, self).__init__(bigdl_type, transformer, prob) class ColorJitter(FeatureTransformer): """ Random adjust brightness, contrast, hue, saturation :param brightness_prob probability to adjust brightness :param brightness_delta brightness parameter :param contrast_prob probability to adjust contrast :param contrast_lower contrast lower parameter :param contrast_upper contrast upper parameter :param hue_prob probability to adjust hue :param hue_delta hue parameter :param saturation_prob probability to adjust saturation :param saturation_lower saturation lower parameter :param saturation_upper saturation upper parameter :param random_order_prob random order for different operation :param shuffle shuffle the transformers """ def __init__(self, brightness_prob = 0.5, brightness_delta = 32.0, contrast_prob = 0.5, contrast_lower = 0.5, contrast_upper = 1.5, hue_prob = 0.5, hue_delta = 18.0, saturation_prob = 0.5, saturation_lower = 0.5, saturation_upper = 1.5, random_order_prob = 0.0, shuffle = False, bigdl_type="float"): super(ColorJitter, self).__init__(bigdl_type, brightness_prob, brightness_delta, contrast_prob, contrast_lower, contrast_upper, hue_prob, hue_delta, saturation_prob, saturation_lower, saturation_upper, random_order_prob, shuffle) class RandomSampler(FeatureTransformer): """ Random sample a bounding box given some constraints and crop the image This is used in SSD training augmentation """ def __init__(self): super(RandomSampler, self).__init__(bigdl_type) class RoiProject(FeatureTransformer): """ Project gt boxes onto the coordinate system defined by image boundary :param need_meet_center_constraint whether need to meet center constraint, i.e., the center of gt box need be within image boundary """ def __init__(self, need_meet_center_constraint, bigdl_type="float"): super(RoiProject, self).__init__(bigdl_type, need_meet_center_constraint) class RoiHFlip(FeatureTransformer): """ horizontally flip the roi :param normalized whether the roi is normalized, i.e. in range [0, 1] """ def __init__(self, normalized=True, bigdl_type="float"): super(RoiHFlip, self).__init__(bigdl_type, normalized) class RoiResize(FeatureTransformer): """ resize the roi according to scale :param normalized whether the roi is normalized, i.e. in range [0, 1] """ def __init__(self, normalized=True, bigdl_type="float"): super(RoiResize, self).__init__(bigdl_type, normalized) class RoiNormalize(FeatureTransformer): """ Normalize Roi to [0, 1] """ def __init__(self, bigdl_type="float"): super(RoiNormalize, self).__init__(bigdl_type) class MatToFloats(FeatureTransformer): """ Transform OpenCVMat to float array, note that in this transformer, the mat is released :param valid_height valid height in case the mat is invalid :param valid_width valid width in case the mat is invalid :param valid_channel valid channel in case the mat is invalid :param out_key key to store float array :param share_buffer share buffer of output """ def __init__(self, valid_height=300, valid_width=300, valid_channel=300, out_key = "floats", share_buffer=True, bigdl_type="float"): super(MatToFloats, self).__init__(bigdl_type, valid_height, valid_width, valid_channel, out_key, share_buffer) class MatToTensor(FeatureTransformer): """ transform opencv mat to tensor :param to_rgb BGR to RGB (default is BGR) :param tensor_key key to store transformed tensor """ def __init__(self, to_rgb=False, tensor_key="imageTensor", bigdl_type="float"): super(MatToTensor, self).__init__(bigdl_type, to_rgb, tensor_key) class AspectScale(FeatureTransformer): """ Resize the image, keep the aspect ratio. scale according to the short edge :param min_size scale size, apply to short edge :param scale_multiple_of make the scaled size multiple of some value :param max_size max size after scale :param resize_mode if resizeMode = -1, random select a mode from (Imgproc.INTER_LINEAR, Imgproc.INTER_CUBIC, Imgproc.INTER_AREA, Imgproc.INTER_NEAREST, Imgproc.INTER_LANCZOS4) :param use_scale_factor if true, scale factor fx and fy is used, fx = fy = 0 :aram min_scale control the minimum scale up for image """ def __init__(self, min_size, scale_multiple_of = 1, max_size = 1000, resize_mode = 1, use_scale_factor=True, min_scale=-1.0, bigdl_type="float"): super(AspectScale, self).__init__(bigdl_type, min_size, scale_multiple_of, max_size, resize_mode, use_scale_factor, min_scale) class RandomAspectScale(FeatureTransformer): """ resize the image by randomly choosing a scale :param scales array of scale options that for random choice :param scaleMultipleOf Resize test images so that its width and height are multiples of :param maxSize Max pixel size of the longest side of a scaled input image """ def __init__(self, scales, scale_multiple_of = 1, max_size = 1000, bigdl_type="float"): super(RandomAspectScale, self).__init__(bigdl_type, scales, scale_multiple_of, max_size) class BytesToMat(FeatureTransformer): """ Transform byte array(original image file in byte) to OpenCVMat :param byte_key key that maps byte array """ def __init__(self, byte_key = "bytes", bigdl_type="float"): super(BytesToMat, self).__init__(bigdl_type, byte_key) class ImageFrameToSample(FeatureTransformer): """ transform imageframe to samples :param input_keys keys that maps inputs (each input should be a tensor) :param target_keys keys that maps targets (each target should be a tensor) :param sample_key key to store sample """ def __init__(self, input_keys=["imageTensor"], target_keys=None, sample_key="sample", bigdl_type="float"): super(ImageFrameToSample, self).__init__(bigdl_type, input_keys, target_keys, sample_key) class PixelBytesToMat(FeatureTransformer): """ Transform byte array(pixels in byte) to OpenCVMat :param byte_key key that maps byte array """ def __init__(self, byte_key = "bytes", bigdl_type="float"): super(PixelBytesToMat, self).__init__(bigdl_type, byte_key) class FixExpand(FeatureTransformer): """ Expand image with given expandHeight and expandWidth, put the original image to the center of expanded image :param expand_height height expand to :param expand_width width expand to """ def __init__(self, expand_height, expand_width, bigdl_type="float"): super(FixExpand, self).__init__(bigdl_type, expand_height, expand_width) class ChannelScaledNormalizer(FeatureTransformer): """ Scaled image at channel level with offset and scale :param mean_r : offset for R channel :param mean_g : offset for G channel :param mean_b: offset for B channel :param scale: scaling factor for all channels """ def __init__(self, mean_r, mean_g, mean_b, scale, bigdl_type="float"): super(ChannelScaledNormalizer, self).__init__(bigdl_type, mean_r, mean_g, mean_b, scale) class RandomAlterAspect(FeatureTransformer): """ Apply random crop based on area ratio and resize to cropLenth size :param min_area_ratio min area ratio :param max_area_ratio max area ratio :param min_aspect_ratio_change factor applied to ratio area :param interp_mode interp mode applied in resize :param crop_length final size resized to """ def __init__(self, min_area_ratio, max_area_ratio, min_aspect_ratio_change, interp_mode, crop_length, bigdl_type="float"): super(RandomAlterAspect, self).__init__(bigdl_type, min_area_ratio, max_area_ratio, min_aspect_ratio_change, interp_mode, crop_length) class RandomCropper(FeatureTransformer): """ Random cropper on uniform distribution with fixed height & width :param crop_w width cropped to :param crop_h height cropped to :param mirror whether mirror :param cropper_method crop method :param channels total channels """ def __init__(self, crop_w, crop_h, mirror, cropper_method, channels, bigdl_type="float"): super(RandomCropper, self).__init__(bigdl_type, crop_w, crop_h, mirror, cropper_method, channels) class RandomResize(FeatureTransformer): """ Random resize between minSize and maxSize and scale height and width to each other :param min_size min size to resize to :param max_size max size to resize to """ def __init__(self, min_size, max_size, bigdl_type="float"): super(RandomResize, self).__init__(bigdl_type, min_size, max_size) class SeqFileFolder(JavaValue): @classmethod def files_to_image_frame(cls, url, sc, class_num, partition_num=-1, bigdl_type="float"): """ Extract hadoop sequence files from an HDFS path as ImageFrame :param url: sequence files folder path :param sc: spark context :param class_num: class number of data :param partition_num: partition number, default: Engine.nodeNumber() * Engine.coreNumber() """ jvalue = callBigDlFunc(bigdl_type, "seqFilesToImageFrame", url, sc, class_num, partition_num) return ImageFrame(jvalue=jvalue)
38.310253
135
0.652184
import sys from bigdl.util.common import JavaValue from bigdl.util.common import callBigDlFunc from bigdl.util.common import * if sys.version >= '3': long = int unicode = str class FeatureTransformer(JavaValue): def __init__(self, bigdl_type="float", *args): self.value = callBigDlFunc( bigdl_type, JavaValue.jvm_class_constructor(self), *args) def transform(self, image_feature, bigdl_type="float"): callBigDlFunc(bigdl_type, "transformImageFeature", self.value, image_feature) return image_feature def __call__(self, image_frame, bigdl_type="float"): jframe = callBigDlFunc(bigdl_type, "transformImageFrame", self.value, image_frame) return ImageFrame(jvalue=jframe) class Pipeline(FeatureTransformer): def __init__(self, transformers, bigdl_type="float"): for transfomer in transformers: assert transfomer.__class__.__bases__[0].__name__ == "FeatureTransformer", "the transformer should be " \ "subclass of FeatureTransformer" super(Pipeline, self).__init__(bigdl_type, transformers) class ImageFeature(JavaValue): def __init__(self, image=None, label=None, path=None, bigdl_type="float"): image_tensor = JTensor.from_ndarray(image) if image is not None else None label_tensor = JTensor.from_ndarray(label) if label is not None else None self.bigdl_type = bigdl_type self.value = callBigDlFunc( bigdl_type, JavaValue.jvm_class_constructor(self), image_tensor, label_tensor, path) def get_image(self, float_key="floats", to_chw=True): tensor = callBigDlFunc(self.bigdl_type, "imageFeatureToImageTensor", self.value, float_key, to_chw) return tensor.to_ndarray() def get_label(self): label = callBigDlFunc(self.bigdl_type, "imageFeatureToLabelTensor", self.value) return label.to_ndarray() def keys(self): return callBigDlFunc(self.bigdl_type, "imageFeatureGetKeys", self.value) class ImageFrame(JavaValue): def __init__(self, jvalue, bigdl_type="float"): self.value = jvalue self.bigdl_type = bigdl_type if self.is_local(): self.image_frame = LocalImageFrame(jvalue=self.value) else: self.image_frame = DistributedImageFrame(jvalue=self.value) @classmethod def read(cls, path, sc=None, min_partitions=1, bigdl_type="float"): return ImageFrame(jvalue=callBigDlFunc(bigdl_type, "read", path, sc, min_partitions)) @classmethod def read_parquet(cls, path, sc, bigdl_type="float"): return DistributedImageFrame(jvalue=callBigDlFunc(bigdl_type, "readParquet", path, sc)) @classmethod def write_parquet(cls, path, output, sc, partition_num = 1, bigdl_type="float"): return callBigDlFunc(bigdl_type, "writeParquet", path, output, sc, partition_num) def is_local(self): return callBigDlFunc(self.bigdl_type, "isLocal", self.value) def is_distributed(self): return callBigDlFunc(self.bigdl_type, "isDistributed", self.value) def transform(self, transformer, bigdl_type="float"): self.value = callBigDlFunc(bigdl_type, "transformImageFrame", transformer, self.value) return self def get_image(self, float_key="floats", to_chw=True): return self.image_frame.get_image(float_key, to_chw) def get_label(self): return self.image_frame.get_label() def get_predict(self, key="predict"): return self.image_frame.get_predict(key) def get_sample(self): return self.image_frame.get_sample() def get_uri(self): return self.image_frame.get_uri() def set_label(self, label, bigdl_type="float"): return callBigDlFunc(bigdl_type, "setLabel", label, self.value) def random_split(self, weights): jvalues = self.image_frame.random_split(weights) return [ImageFrame(jvalue) for jvalue in jvalues] class LocalImageFrame(ImageFrame): def __init__(self, image_list=None, label_list=None, jvalue=None, bigdl_type="float"): assert jvalue or image_list, "jvalue and image_list cannot be None in the same time" if jvalue: self.value = jvalue else: image_tensor_list = map(lambda image: JTensor.from_ndarray(image), image_list) label_tensor_list = map(lambda label: JTensor.from_ndarray(label), label_list) if label_list else None self.value = callBigDlFunc(bigdl_type, JavaValue.jvm_class_constructor(self), image_tensor_list, label_tensor_list) self.bigdl_type = bigdl_type def get_image(self, float_key="floats", to_chw=True): tensors = callBigDlFunc(self.bigdl_type, "localImageFrameToImageTensor", self.value, float_key, to_chw) return map(lambda tensor: tensor.to_ndarray(), tensors) def get_label(self): labels = callBigDlFunc(self.bigdl_type, "localImageFrameToLabelTensor", self.value) return map(lambda tensor: tensor.to_ndarray(), labels) def get_predict(self, key="predict"): predicts = callBigDlFunc(self.bigdl_type, "localImageFrameToPredict", self.value, key) return map(lambda predict: (predict[0], predict[1].to_ndarray()) if predict[1] else (predict[0], None), predicts) def get_sample(self, key="sample"): return callBigDlFunc(self.bigdl_type, "localImageFrameToSample", self.value, key) def get_uri(self, key = "uri"): return callBigDlFunc(self.bigdl_type, "localImageFrameToUri", self.value, key) def random_split(self, weights): raise "random split not supported in LocalImageFrame" class DistributedImageFrame(ImageFrame): def __init__(self, image_rdd=None, label_rdd=None, jvalue=None, bigdl_type="float"): assert jvalue or image_rdd, "jvalue and image_rdd cannot be None in the same time" if jvalue: self.value = jvalue else: image_tensor_rdd = image_rdd.map(lambda image: JTensor.from_ndarray(image)) label_tensor_rdd = label_rdd.map(lambda label: JTensor.from_ndarray(label)) if label_rdd else None self.value = callBigDlFunc(bigdl_type, JavaValue.jvm_class_constructor(self), image_tensor_rdd, label_tensor_rdd) self.bigdl_type = bigdl_type def get_image(self, float_key="floats", to_chw=True): tensor_rdd = callBigDlFunc(self.bigdl_type, "distributedImageFrameToImageTensorRdd", self.value, float_key, to_chw) return tensor_rdd.map(lambda tensor: tensor.to_ndarray()) def get_label(self): tensor_rdd = callBigDlFunc(self.bigdl_type, "distributedImageFrameToLabelTensorRdd", self.value) return tensor_rdd.map(lambda tensor: tensor.to_ndarray()) def get_predict(self, key="predict"): predicts = callBigDlFunc(self.bigdl_type, "distributedImageFrameToPredict", self.value, key) return predicts.map(lambda predict: (predict[0], predict[1].to_ndarray()) if predict[1] else (predict[0], None)) def get_sample(self, key="sample"): return callBigDlFunc(self.bigdl_type, "distributedImageFrameToSample", self.value, key) def get_uri(self, key = "uri"): return callBigDlFunc(self.bigdl_type, "distributedImageFrameToUri", self.value, key) def random_split(self, weights): return callBigDlFunc(self.bigdl_type, "distributedImageFrameRandomSplit", self.value, weights) class HFlip(FeatureTransformer): def __init__(self, bigdl_type="float"): super(HFlip, self).__init__(bigdl_type) class Resize(FeatureTransformer): def __init__(self, resize_h, resize_w, resize_mode = 1, use_scale_factor=True, bigdl_type="float"): super(Resize, self).__init__(bigdl_type, resize_h, resize_w, resize_mode, use_scale_factor) class Brightness(FeatureTransformer): def __init__(self, delta_low, delta_high, bigdl_type="float"): super(Brightness, self).__init__(bigdl_type, delta_low, delta_high) class ChannelOrder(FeatureTransformer): def __init__(self, bigdl_type="float"): super(ChannelOrder, self).__init__(bigdl_type) class Contrast(FeatureTransformer): def __init__(self, delta_low, delta_high, bigdl_type="float"): super(Contrast, self).__init__(bigdl_type, delta_low, delta_high) class Saturation(FeatureTransformer): def __init__(self, delta_low, delta_high, bigdl_type="float"): super(Saturation, self).__init__(bigdl_type, delta_low, delta_high) class Hue(FeatureTransformer): def __init__(self, delta_low, delta_high, bigdl_type="float"): super(Hue, self).__init__(bigdl_type, delta_low, delta_high) class ChannelNormalize(FeatureTransformer): def __init__(self, mean_r, mean_g, mean_b, std_r=1.0, std_g=1.0, std_b=1.0, bigdl_type="float"): super(ChannelNormalize, self).__init__(bigdl_type, mean_r, mean_g, mean_b, std_r, std_g, std_b) class PixelNormalize(FeatureTransformer): def __init__(self, means, bigdl_type="float"): super(PixelNormalize, self).__init__(bigdl_type, means) class RandomCrop(FeatureTransformer): def __init__(self, crop_width, crop_height, is_clip=True, bigdl_type="float"): super(RandomCrop, self).__init__(bigdl_type, crop_width, crop_height, is_clip) class CenterCrop(FeatureTransformer): def __init__(self, crop_width, crop_height, is_clip=True, bigdl_type="float"): super(CenterCrop, self).__init__(bigdl_type, crop_width, crop_height, is_clip) class FixedCrop(FeatureTransformer): def __init__(self, x1, y1, x2, y2, normalized=True, is_clip=True, bigdl_type="float"): super(FixedCrop, self).__init__(bigdl_type, x1, y1, x2, y2, normalized, is_clip) class DetectionCrop(FeatureTransformer): def __init__(self, roi_key, normalized=True, bigdl_type="float"): super(DetectionCrop, self).__init__(bigdl_type, roi_key, normalized) class Expand(FeatureTransformer): def __init__(self, means_r=123, means_g=117, means_b=104, min_expand_ratio=1.0, max_expand_ratio=4.0, bigdl_type="float"): super(Expand, self).__init__(bigdl_type, means_r, means_g, means_b, min_expand_ratio, max_expand_ratio) class Filler(FeatureTransformer): def __init__(self, start_x, start_y, end_x, end_y, value = 255, bigdl_type="float"): super(Filler, self).__init__(bigdl_type, start_x, start_y, end_x, end_y, value) class RandomTransformer(FeatureTransformer): def __init__(self, transformer, prob, bigdl_type="float"): super(RandomTransformer, self).__init__(bigdl_type, transformer, prob) class ColorJitter(FeatureTransformer): def __init__(self, brightness_prob = 0.5, brightness_delta = 32.0, contrast_prob = 0.5, contrast_lower = 0.5, contrast_upper = 1.5, hue_prob = 0.5, hue_delta = 18.0, saturation_prob = 0.5, saturation_lower = 0.5, saturation_upper = 1.5, random_order_prob = 0.0, shuffle = False, bigdl_type="float"): super(ColorJitter, self).__init__(bigdl_type, brightness_prob, brightness_delta, contrast_prob, contrast_lower, contrast_upper, hue_prob, hue_delta, saturation_prob, saturation_lower, saturation_upper, random_order_prob, shuffle) class RandomSampler(FeatureTransformer): def __init__(self): super(RandomSampler, self).__init__(bigdl_type) class RoiProject(FeatureTransformer): def __init__(self, need_meet_center_constraint, bigdl_type="float"): super(RoiProject, self).__init__(bigdl_type, need_meet_center_constraint) class RoiHFlip(FeatureTransformer): def __init__(self, normalized=True, bigdl_type="float"): super(RoiHFlip, self).__init__(bigdl_type, normalized) class RoiResize(FeatureTransformer): def __init__(self, normalized=True, bigdl_type="float"): super(RoiResize, self).__init__(bigdl_type, normalized) class RoiNormalize(FeatureTransformer): def __init__(self, bigdl_type="float"): super(RoiNormalize, self).__init__(bigdl_type) class MatToFloats(FeatureTransformer): def __init__(self, valid_height=300, valid_width=300, valid_channel=300, out_key = "floats", share_buffer=True, bigdl_type="float"): super(MatToFloats, self).__init__(bigdl_type, valid_height, valid_width, valid_channel, out_key, share_buffer) class MatToTensor(FeatureTransformer): def __init__(self, to_rgb=False, tensor_key="imageTensor", bigdl_type="float"): super(MatToTensor, self).__init__(bigdl_type, to_rgb, tensor_key) class AspectScale(FeatureTransformer): def __init__(self, min_size, scale_multiple_of = 1, max_size = 1000, resize_mode = 1, use_scale_factor=True, min_scale=-1.0, bigdl_type="float"): super(AspectScale, self).__init__(bigdl_type, min_size, scale_multiple_of, max_size, resize_mode, use_scale_factor, min_scale) class RandomAspectScale(FeatureTransformer): def __init__(self, scales, scale_multiple_of = 1, max_size = 1000, bigdl_type="float"): super(RandomAspectScale, self).__init__(bigdl_type, scales, scale_multiple_of, max_size) class BytesToMat(FeatureTransformer): def __init__(self, byte_key = "bytes", bigdl_type="float"): super(BytesToMat, self).__init__(bigdl_type, byte_key) class ImageFrameToSample(FeatureTransformer): def __init__(self, input_keys=["imageTensor"], target_keys=None, sample_key="sample", bigdl_type="float"): super(ImageFrameToSample, self).__init__(bigdl_type, input_keys, target_keys, sample_key) class PixelBytesToMat(FeatureTransformer): def __init__(self, byte_key = "bytes", bigdl_type="float"): super(PixelBytesToMat, self).__init__(bigdl_type, byte_key) class FixExpand(FeatureTransformer): def __init__(self, expand_height, expand_width, bigdl_type="float"): super(FixExpand, self).__init__(bigdl_type, expand_height, expand_width) class ChannelScaledNormalizer(FeatureTransformer): def __init__(self, mean_r, mean_g, mean_b, scale, bigdl_type="float"): super(ChannelScaledNormalizer, self).__init__(bigdl_type, mean_r, mean_g, mean_b, scale) class RandomAlterAspect(FeatureTransformer): def __init__(self, min_area_ratio, max_area_ratio, min_aspect_ratio_change, interp_mode, crop_length, bigdl_type="float"): super(RandomAlterAspect, self).__init__(bigdl_type, min_area_ratio, max_area_ratio, min_aspect_ratio_change, interp_mode, crop_length) class RandomCropper(FeatureTransformer): def __init__(self, crop_w, crop_h, mirror, cropper_method, channels, bigdl_type="float"): super(RandomCropper, self).__init__(bigdl_type, crop_w, crop_h, mirror, cropper_method, channels) class RandomResize(FeatureTransformer): def __init__(self, min_size, max_size, bigdl_type="float"): super(RandomResize, self).__init__(bigdl_type, min_size, max_size) class SeqFileFolder(JavaValue): @classmethod def files_to_image_frame(cls, url, sc, class_num, partition_num=-1, bigdl_type="float"): jvalue = callBigDlFunc(bigdl_type, "seqFilesToImageFrame", url, sc, class_num, partition_num) return ImageFrame(jvalue=jvalue)
true
true
f71793b555d90d054bf1905d45ea0235b077f075
2,312
py
Python
pyramid_debugtoolbar/panels/traceback.py
rollbar/pyramid_debugtoolbar
dab4278eb68b801b1d3e9679cf1308096c3f849f
[ "Apache-2.0" ]
null
null
null
pyramid_debugtoolbar/panels/traceback.py
rollbar/pyramid_debugtoolbar
dab4278eb68b801b1d3e9679cf1308096c3f849f
[ "Apache-2.0" ]
null
null
null
pyramid_debugtoolbar/panels/traceback.py
rollbar/pyramid_debugtoolbar
dab4278eb68b801b1d3e9679cf1308096c3f849f
[ "Apache-2.0" ]
1
2021-02-21T12:18:04.000Z
2021-02-21T12:18:04.000Z
import re from pyramid_debugtoolbar.tbtools import Traceback from pyramid_debugtoolbar.panels import DebugPanel from pyramid_debugtoolbar.utils import escape from pyramid_debugtoolbar.utils import STATIC_PATH from pyramid_debugtoolbar.utils import ROOT_ROUTE_NAME from pyramid_debugtoolbar.utils import EXC_ROUTE_NAME _ = lambda x: x class TracebackPanel(DebugPanel): name = 'Traceback' template = 'pyramid_debugtoolbar.panels:templates/traceback.dbtmako' def __init__(self, request): self.request = request self.exc_history = request.exc_history def nav_title(self): return _("Traceback") def nav_subtitle(self): return "" def title(self): return _("Traceback") def url(self): return "" @property def has_content(self): if hasattr(self.request, 'pdbt_tb'): return True else: return False def process_response(self, response): if self.has_content: traceback = self.request.pdbt_tb exc = escape(traceback.exception) summary = Traceback.render_summary(traceback, include_title=False, request=self.request) token = self.request.registry.pdtb_token url = '' # self.request.route_url(EXC_ROUTE_NAME, _query=qs) evalex = self.exc_history.eval_exc self.data = { 'evalex': evalex and 'true' or 'false', 'console': 'false', 'lodgeit_url': None, 'title': exc, 'exception': exc, 'exception_type': escape(traceback.exception_type), 'summary': summary, 'plaintext': traceback.plaintext, 'plaintext_cs': re.sub('-{2,}', '-', traceback.plaintext), 'traceback_id': traceback.id, 'token': token, 'url': url, } def render_content(self, request): return super(TracebackPanel, self).render_content(request) def render_vars(self, request): return { 'static_path': request.static_url(STATIC_PATH), 'root_path': request.route_url(ROOT_ROUTE_NAME) }
32.111111
100
0.588668
import re from pyramid_debugtoolbar.tbtools import Traceback from pyramid_debugtoolbar.panels import DebugPanel from pyramid_debugtoolbar.utils import escape from pyramid_debugtoolbar.utils import STATIC_PATH from pyramid_debugtoolbar.utils import ROOT_ROUTE_NAME from pyramid_debugtoolbar.utils import EXC_ROUTE_NAME _ = lambda x: x class TracebackPanel(DebugPanel): name = 'Traceback' template = 'pyramid_debugtoolbar.panels:templates/traceback.dbtmako' def __init__(self, request): self.request = request self.exc_history = request.exc_history def nav_title(self): return _("Traceback") def nav_subtitle(self): return "" def title(self): return _("Traceback") def url(self): return "" @property def has_content(self): if hasattr(self.request, 'pdbt_tb'): return True else: return False def process_response(self, response): if self.has_content: traceback = self.request.pdbt_tb exc = escape(traceback.exception) summary = Traceback.render_summary(traceback, include_title=False, request=self.request) token = self.request.registry.pdtb_token url = '' evalex = self.exc_history.eval_exc self.data = { 'evalex': evalex and 'true' or 'false', 'console': 'false', 'lodgeit_url': None, 'title': exc, 'exception': exc, 'exception_type': escape(traceback.exception_type), 'summary': summary, 'plaintext': traceback.plaintext, 'plaintext_cs': re.sub('-{2,}', '-', traceback.plaintext), 'traceback_id': traceback.id, 'token': token, 'url': url, } def render_content(self, request): return super(TracebackPanel, self).render_content(request) def render_vars(self, request): return { 'static_path': request.static_url(STATIC_PATH), 'root_path': request.route_url(ROOT_ROUTE_NAME) }
true
true
f717942ddd2886f2dcfba64b6e7601b1de639677
571
py
Python
test/api_test.py
kuro2a/kiku
d4e6500970a20d1955f1773e0e2cfb8e2db819ba
[ "MIT" ]
2
2019-08-14T14:32:36.000Z
2019-08-15T08:28:15.000Z
test/api_test.py
kuro2a/kiku
d4e6500970a20d1955f1773e0e2cfb8e2db819ba
[ "MIT" ]
1
2019-10-02T16:35:05.000Z
2019-10-02T16:35:05.000Z
test/api_test.py
kuro2a/kiku
d4e6500970a20d1955f1773e0e2cfb8e2db819ba
[ "MIT" ]
1
2019-08-14T14:33:01.000Z
2019-08-14T14:33:01.000Z
#!/usr/bin/python3 import sys import pathlib from datetime import datetime import pytest from falcon import testing sys.path.append( str(pathlib.Path(__file__).resolve().parent) + '/../' ) import main @pytest.fixture() def client(): return testing.TestClient(main.create_service()) def test_api_version(client): doc = { u'meta': { u'status': u'OK', u'message': u'OK', u'timestamp': datetime.now() }, u'data': None } result = client.simulate_get('/api/v1/version') assert result.json == doc
18.419355
72
0.623468
import sys import pathlib from datetime import datetime import pytest from falcon import testing sys.path.append( str(pathlib.Path(__file__).resolve().parent) + '/../' ) import main @pytest.fixture() def client(): return testing.TestClient(main.create_service()) def test_api_version(client): doc = { u'meta': { u'status': u'OK', u'message': u'OK', u'timestamp': datetime.now() }, u'data': None } result = client.simulate_get('/api/v1/version') assert result.json == doc
true
true
f7179491275351836a0592d841bc9b9fe7d43c7d
151
py
Python
src/GracefulKiller/__init__.py
MaxMaxoff/GracefulKiller
dab06ecc7573211ae7acf90e5f889e37d48a88d2
[ "MIT" ]
1
2021-10-04T09:09:12.000Z
2021-10-04T09:09:12.000Z
src/GracefulKiller/__init__.py
MaxMaxoff/GracefulKiller
dab06ecc7573211ae7acf90e5f889e37d48a88d2
[ "MIT" ]
null
null
null
src/GracefulKiller/__init__.py
MaxMaxoff/GracefulKiller
dab06ecc7573211ae7acf90e5f889e37d48a88d2
[ "MIT" ]
null
null
null
try: from GracefulKiller.GracefulKiller import GracefulKiller, Loop except: from src.GracefulKiller.GracefulKiller import GracefulKiller, Loop
30.2
70
0.821192
try: from GracefulKiller.GracefulKiller import GracefulKiller, Loop except: from src.GracefulKiller.GracefulKiller import GracefulKiller, Loop
true
true
f71794ea091735736fa90a59266f6bb2161ac032
1,897
py
Python
tests/test_test.py
yehzhang/RapidTest
2302fc10ddafba1d16ef1d7448d46c66f5a05da2
[ "MIT" ]
null
null
null
tests/test_test.py
yehzhang/RapidTest
2302fc10ddafba1d16ef1d7448d46c66f5a05da2
[ "MIT" ]
null
null
null
tests/test_test.py
yehzhang/RapidTest
2302fc10ddafba1d16ef1d7448d46c66f5a05da2
[ "MIT" ]
null
null
null
from unittest import TestCase from rapidtest import Result, Test, Case, TreeNode class TestTest(TestCase): def test_check_result(self): t = Test(list, operation=True) t.add_case(Case('append', [1], 'pop', Result(1), 'append', [2], 'append', [3], 'pop', 'pop', Result(2))) t.add_case(Case('append', [1], 'pop', 'append', [2], 'append', [3], 'pop', 'pop', result=list)) t.run() # Test if output difference is detected # t.add_case(Case('append', [1], # 'pop', Result(2))) # t.add_case(Case('append', [1], # 'pop', Result(1))) # with self.assertRaisesRegexp(ValueError, r'differ'): # t.run() # t.run() def test_summary(self): def assert_sum_code(c): code, _ = t.summary() self.assertEqual(code, c) t = Test(list, operation=True) assert_sum_code(t.EXIT_EMPTY) t.add_case(Case('append', [1], 'pop', Result(1))) t.run() assert_sum_code(t.EXIT_PASS) t.add_case(Case('pop', Result(None))) # assert_sum_code(t.EXIT_PENDING) with self.assertRaises(IndexError): t.run() assert_sum_code(t.EXIT_FAIL) t.add_case(Case('append', [1], Result(None))) # assert_sum_code(t.EXIT_PENDING) t.run() assert_sum_code(t.EXIT_FAIL) def f(i): if i == 0: return Case('append', [1], Result(None)) raise ValueError t.add_func(f) with self.assertRaises(ValueError): t.run() assert_sum_code(t.EXIT_GEN_ERR)
29.640625
62
0.470216
from unittest import TestCase from rapidtest import Result, Test, Case, TreeNode class TestTest(TestCase): def test_check_result(self): t = Test(list, operation=True) t.add_case(Case('append', [1], 'pop', Result(1), 'append', [2], 'append', [3], 'pop', 'pop', Result(2))) t.add_case(Case('append', [1], 'pop', 'append', [2], 'append', [3], 'pop', 'pop', result=list)) t.run() def test_summary(self): def assert_sum_code(c): code, _ = t.summary() self.assertEqual(code, c) t = Test(list, operation=True) assert_sum_code(t.EXIT_EMPTY) t.add_case(Case('append', [1], 'pop', Result(1))) t.run() assert_sum_code(t.EXIT_PASS) t.add_case(Case('pop', Result(None))) with self.assertRaises(IndexError): t.run() assert_sum_code(t.EXIT_FAIL) t.add_case(Case('append', [1], Result(None))) t.run() assert_sum_code(t.EXIT_FAIL) def f(i): if i == 0: return Case('append', [1], Result(None)) raise ValueError t.add_func(f) with self.assertRaises(ValueError): t.run() assert_sum_code(t.EXIT_GEN_ERR)
true
true
f7179508810234674ea1f3cf934a800af733803f
794
py
Python
gaphor/RAAML/modelinglanguage.py
mrmonkington/gaphor
f0fcd4deb90d24b14723840a689fac901f645a43
[ "Apache-2.0" ]
867
2018-01-09T00:19:09.000Z
2022-03-31T02:49:23.000Z
gaphor/RAAML/modelinglanguage.py
mrmonkington/gaphor
f0fcd4deb90d24b14723840a689fac901f645a43
[ "Apache-2.0" ]
790
2018-01-13T23:47:07.000Z
2022-03-31T16:04:27.000Z
gaphor/RAAML/modelinglanguage.py
sitedata/gaphor
c83eff0bd595d1a8e766a157f0268e5206eed22c
[ "Apache-2.0" ]
117
2018-01-09T02:24:49.000Z
2022-03-23T08:07:42.000Z
"""The RAAML Modeling Language module is the entrypoint for RAAML related assets.""" import gaphor.SysML.propertypages # noqa from gaphor.abc import ModelingLanguage from gaphor.core import gettext from gaphor.diagram.diagramtoolbox import ToolboxDefinition from gaphor.RAAML import diagramitems, raaml from gaphor.RAAML.toolbox import raaml_toolbox_actions class RAAMLModelingLanguage(ModelingLanguage): @property def name(self) -> str: return gettext("RAAML") @property def toolbox_definition(self) -> ToolboxDefinition: return raaml_toolbox_actions def lookup_element(self, name): element_type = getattr(raaml, name, None) if not element_type: element_type = getattr(diagramitems, name, None) return element_type
30.538462
73
0.746851
import gaphor.SysML.propertypages from gaphor.abc import ModelingLanguage from gaphor.core import gettext from gaphor.diagram.diagramtoolbox import ToolboxDefinition from gaphor.RAAML import diagramitems, raaml from gaphor.RAAML.toolbox import raaml_toolbox_actions class RAAMLModelingLanguage(ModelingLanguage): @property def name(self) -> str: return gettext("RAAML") @property def toolbox_definition(self) -> ToolboxDefinition: return raaml_toolbox_actions def lookup_element(self, name): element_type = getattr(raaml, name, None) if not element_type: element_type = getattr(diagramitems, name, None) return element_type
true
true
f717953473fd5d44045b712a4f139e641a8c661b
27,730
py
Python
InstallOpenface/fix_sklearn/label.py
s123600g/openfaceInstallscript
962b4b89c5626318b5701d7297d49df3423b0fe4
[ "MIT" ]
null
null
null
InstallOpenface/fix_sklearn/label.py
s123600g/openfaceInstallscript
962b4b89c5626318b5701d7297d49df3423b0fe4
[ "MIT" ]
null
null
null
InstallOpenface/fix_sklearn/label.py
s123600g/openfaceInstallscript
962b4b89c5626318b5701d7297d49df3423b0fe4
[ "MIT" ]
null
null
null
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Mathieu Blondel <mathieu@mblondel.org> # Olivier Grisel <olivier.grisel@ensta.org> # Andreas Mueller <amueller@ais.uni-bonn.de> # Joel Nothman <joel.nothman@gmail.com> # Hamzeh Alsalhi <ha258@cornell.edu> # License: BSD 3 clause from collections import defaultdict import itertools import array import numpy as np import scipy.sparse as sp from ..base import BaseEstimator, TransformerMixin from ..utils.fixes import sparse_min_max from ..utils import column_or_1d from ..utils.validation import check_array from ..utils.validation import check_is_fitted from ..utils.validation import _num_samples from ..utils.multiclass import unique_labels from ..utils.multiclass import type_of_target from ..externals import six zip = six.moves.zip map = six.moves.map __all__ = [ 'label_binarize', 'LabelBinarizer', 'LabelEncoder', 'MultiLabelBinarizer', ] class LabelEncoder(BaseEstimator, TransformerMixin): """Encode labels with value between 0 and n_classes-1. Read more in the :ref:`User Guide <preprocessing_targets>`. Attributes ---------- classes_ : array of shape (n_class,) Holds the label for each class. Examples -------- `LabelEncoder` can be used to normalize labels. >>> from sklearn import preprocessing >>> le = preprocessing.LabelEncoder() >>> le.fit([1, 2, 2, 6]) LabelEncoder() >>> le.classes_ array([1, 2, 6]) >>> le.transform([1, 1, 2, 6]) #doctest: +ELLIPSIS array([0, 0, 1, 2]...) >>> le.inverse_transform([0, 0, 1, 2]) array([1, 1, 2, 6]) It can also be used to transform non-numerical labels (as long as they are hashable and comparable) to numerical labels. >>> le = preprocessing.LabelEncoder() >>> le.fit(["paris", "paris", "tokyo", "amsterdam"]) LabelEncoder() >>> list(le.classes_) ['amsterdam', 'paris', 'tokyo'] >>> le.transform(["tokyo", "tokyo", "paris"]) #doctest: +ELLIPSIS array([2, 2, 1]...) >>> list(le.inverse_transform([2, 2, 1])) ['tokyo', 'tokyo', 'paris'] See also -------- sklearn.preprocessing.OneHotEncoder : encode categorical integer features using a one-hot aka one-of-K scheme. """ def fit(self, y): """Fit label encoder Parameters ---------- y : array-like of shape (n_samples,) Target values. Returns ------- self : returns an instance of self. """ y = column_or_1d(y, warn=True) self.classes_ = np.unique(y) return self def fit_transform(self, y): """Fit label encoder and return encoded labels Parameters ---------- y : array-like of shape [n_samples] Target values. Returns ------- y : array-like of shape [n_samples] """ y = column_or_1d(y, warn=True) self.classes_, y = np.unique(y, return_inverse=True) return y def transform(self, y): """Transform labels to normalized encoding. Parameters ---------- y : array-like of shape [n_samples] Target values. Returns ------- y : array-like of shape [n_samples] """ check_is_fitted(self, 'classes_') y = column_or_1d(y, warn=True) classes = np.unique(y) if len(np.intersect1d(classes, self.classes_)) < len(classes): diff = np.setdiff1d(classes, self.classes_) # raise ValueError("y contains new labels: %s" % str(diff)) raise ValueError("y contains previously unseen labels: % s" % str(diff)) return np.searchsorted(self.classes_, y) def inverse_transform(self, y): """Transform labels back to original encoding. Parameters ---------- y : numpy array of shape [n_samples] Target values. Returns ------- y : numpy array of shape [n_samples] """ check_is_fitted(self, 'classes_') diff = np.setdiff1d(y, np.arange(len(self.classes_))) # if diff: # raise ValueError("y contains new labels: %s" % str(diff)) if len(diff): raise ValueError("y contains previously unseen labels: %s" % str(diff)) y = np.asarray(y) return self.classes_[y] class LabelBinarizer(BaseEstimator, TransformerMixin): """Binarize labels in a one-vs-all fashion Several regression and binary classification algorithms are available in the scikit. A simple way to extend these algorithms to the multi-class classification case is to use the so-called one-vs-all scheme. At learning time, this simply consists in learning one regressor or binary classifier per class. In doing so, one needs to convert multi-class labels to binary labels (belong or does not belong to the class). LabelBinarizer makes this process easy with the transform method. At prediction time, one assigns the class for which the corresponding model gave the greatest confidence. LabelBinarizer makes this easy with the inverse_transform method. Read more in the :ref:`User Guide <preprocessing_targets>`. Parameters ---------- neg_label : int (default: 0) Value with which negative labels must be encoded. pos_label : int (default: 1) Value with which positive labels must be encoded. sparse_output : boolean (default: False) True if the returned array from transform is desired to be in sparse CSR format. Attributes ---------- classes_ : array of shape [n_class] Holds the label for each class. y_type_ : str, Represents the type of the target data as evaluated by utils.multiclass.type_of_target. Possible type are 'continuous', 'continuous-multioutput', 'binary', 'multiclass', 'multiclass-multioutput', 'multilabel-indicator', and 'unknown'. sparse_input_ : boolean, True if the input data to transform is given as a sparse matrix, False otherwise. Examples -------- >>> from sklearn import preprocessing >>> lb = preprocessing.LabelBinarizer() >>> lb.fit([1, 2, 6, 4, 2]) LabelBinarizer(neg_label=0, pos_label=1, sparse_output=False) >>> lb.classes_ array([1, 2, 4, 6]) >>> lb.transform([1, 6]) array([[1, 0, 0, 0], [0, 0, 0, 1]]) Binary targets transform to a column vector >>> lb = preprocessing.LabelBinarizer() >>> lb.fit_transform(['yes', 'no', 'no', 'yes']) array([[1], [0], [0], [1]]) Passing a 2D matrix for multilabel classification >>> import numpy as np >>> lb.fit(np.array([[0, 1, 1], [1, 0, 0]])) LabelBinarizer(neg_label=0, pos_label=1, sparse_output=False) >>> lb.classes_ array([0, 1, 2]) >>> lb.transform([0, 1, 2, 1]) array([[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 1, 0]]) See also -------- label_binarize : function to perform the transform operation of LabelBinarizer with fixed classes. sklearn.preprocessing.OneHotEncoder : encode categorical integer features using a one-hot aka one-of-K scheme. """ def __init__(self, neg_label=0, pos_label=1, sparse_output=False): if neg_label >= pos_label: raise ValueError("neg_label={0} must be strictly less than " "pos_label={1}.".format(neg_label, pos_label)) if sparse_output and (pos_label == 0 or neg_label != 0): raise ValueError("Sparse binarization is only supported with non " "zero pos_label and zero neg_label, got " "pos_label={0} and neg_label={1}" "".format(pos_label, neg_label)) self.neg_label = neg_label self.pos_label = pos_label self.sparse_output = sparse_output def fit(self, y): """Fit label binarizer Parameters ---------- y : array of shape [n_samples,] or [n_samples, n_classes] Target values. The 2-d matrix should only contain 0 and 1, represents multilabel classification. Returns ------- self : returns an instance of self. """ self.y_type_ = type_of_target(y) if 'multioutput' in self.y_type_: raise ValueError("Multioutput target data is not supported with " "label binarization") if _num_samples(y) == 0: raise ValueError('y has 0 samples: %r' % y) self.sparse_input_ = sp.issparse(y) self.classes_ = unique_labels(y) return self def fit_transform(self, y): """Fit label binarizer and transform multi-class labels to binary labels. The output of transform is sometimes referred to as the 1-of-K coding scheme. Parameters ---------- y : array or sparse matrix of shape [n_samples,] or \ [n_samples, n_classes] Target values. The 2-d matrix should only contain 0 and 1, represents multilabel classification. Sparse matrix can be CSR, CSC, COO, DOK, or LIL. Returns ------- Y : array or CSR matrix of shape [n_samples, n_classes] Shape will be [n_samples, 1] for binary problems. """ return self.fit(y).transform(y) def transform(self, y): """Transform multi-class labels to binary labels The output of transform is sometimes referred to by some authors as the 1-of-K coding scheme. Parameters ---------- y : array or sparse matrix of shape [n_samples,] or \ [n_samples, n_classes] Target values. The 2-d matrix should only contain 0 and 1, represents multilabel classification. Sparse matrix can be CSR, CSC, COO, DOK, or LIL. Returns ------- Y : numpy array or CSR matrix of shape [n_samples, n_classes] Shape will be [n_samples, 1] for binary problems. """ check_is_fitted(self, 'classes_') y_is_multilabel = type_of_target(y).startswith('multilabel') if y_is_multilabel and not self.y_type_.startswith('multilabel'): raise ValueError("The object was not fitted with multilabel" " input.") return label_binarize(y, self.classes_, pos_label=self.pos_label, neg_label=self.neg_label, sparse_output=self.sparse_output) def inverse_transform(self, Y, threshold=None): """Transform binary labels back to multi-class labels Parameters ---------- Y : numpy array or sparse matrix with shape [n_samples, n_classes] Target values. All sparse matrices are converted to CSR before inverse transformation. threshold : float or None Threshold used in the binary and multi-label cases. Use 0 when ``Y`` contains the output of decision_function (classifier). Use 0.5 when ``Y`` contains the output of predict_proba. If None, the threshold is assumed to be half way between neg_label and pos_label. Returns ------- y : numpy array or CSR matrix of shape [n_samples] Target values. Notes ----- In the case when the binary labels are fractional (probabilistic), inverse_transform chooses the class with the greatest value. Typically, this allows to use the output of a linear model's decision_function method directly as the input of inverse_transform. """ check_is_fitted(self, 'classes_') if threshold is None: threshold = (self.pos_label + self.neg_label) / 2. if self.y_type_ == "multiclass": y_inv = _inverse_binarize_multiclass(Y, self.classes_) else: y_inv = _inverse_binarize_thresholding(Y, self.y_type_, self.classes_, threshold) if self.sparse_input_: y_inv = sp.csr_matrix(y_inv) elif sp.issparse(y_inv): y_inv = y_inv.toarray() return y_inv def label_binarize(y, classes, neg_label=0, pos_label=1, sparse_output=False): """Binarize labels in a one-vs-all fashion Several regression and binary classification algorithms are available in the scikit. A simple way to extend these algorithms to the multi-class classification case is to use the so-called one-vs-all scheme. This function makes it possible to compute this transformation for a fixed set of class labels known ahead of time. Parameters ---------- y : array-like Sequence of integer labels or multilabel data to encode. classes : array-like of shape [n_classes] Uniquely holds the label for each class. neg_label : int (default: 0) Value with which negative labels must be encoded. pos_label : int (default: 1) Value with which positive labels must be encoded. sparse_output : boolean (default: False), Set to true if output binary array is desired in CSR sparse format Returns ------- Y : numpy array or CSR matrix of shape [n_samples, n_classes] Shape will be [n_samples, 1] for binary problems. Examples -------- >>> from sklearn.preprocessing import label_binarize >>> label_binarize([1, 6], classes=[1, 2, 4, 6]) array([[1, 0, 0, 0], [0, 0, 0, 1]]) The class ordering is preserved: >>> label_binarize([1, 6], classes=[1, 6, 4, 2]) array([[1, 0, 0, 0], [0, 1, 0, 0]]) Binary targets transform to a column vector >>> label_binarize(['yes', 'no', 'no', 'yes'], classes=['no', 'yes']) array([[1], [0], [0], [1]]) See also -------- LabelBinarizer : class used to wrap the functionality of label_binarize and allow for fitting to classes independently of the transform operation """ if not isinstance(y, list): # XXX Workaround that will be removed when list of list format is # dropped y = check_array(y, accept_sparse='csr', ensure_2d=False, dtype=None) else: if _num_samples(y) == 0: raise ValueError('y has 0 samples: %r' % y) if neg_label >= pos_label: raise ValueError("neg_label={0} must be strictly less than " "pos_label={1}.".format(neg_label, pos_label)) if (sparse_output and (pos_label == 0 or neg_label != 0)): raise ValueError("Sparse binarization is only supported with non " "zero pos_label and zero neg_label, got " "pos_label={0} and neg_label={1}" "".format(pos_label, neg_label)) # To account for pos_label == 0 in the dense case pos_switch = pos_label == 0 if pos_switch: pos_label = -neg_label y_type = type_of_target(y) if 'multioutput' in y_type: raise ValueError("Multioutput target data is not supported with label " "binarization") if y_type == 'unknown': raise ValueError("The type of target data is not known") n_samples = y.shape[0] if sp.issparse(y) else len(y) n_classes = len(classes) classes = np.asarray(classes) if y_type == "binary": if n_classes == 1: if sparse_output: return sp.csr_matrix((n_samples, 1), dtype=int) else: Y = np.zeros((len(y), 1), dtype=np.int) Y += neg_label return Y elif len(classes) >= 3: y_type = "multiclass" sorted_class = np.sort(classes) if (y_type == "multilabel-indicator" and classes.size != y.shape[1]): raise ValueError("classes {0} missmatch with the labels {1}" "found in the data".format(classes, unique_labels(y))) if y_type in ("binary", "multiclass"): y = column_or_1d(y) # pick out the known labels from y y_in_classes = np.in1d(y, classes) y_seen = y[y_in_classes] indices = np.searchsorted(sorted_class, y_seen) indptr = np.hstack((0, np.cumsum(y_in_classes))) data = np.empty_like(indices) data.fill(pos_label) Y = sp.csr_matrix((data, indices, indptr), shape=(n_samples, n_classes)) elif y_type == "multilabel-indicator": Y = sp.csr_matrix(y) if pos_label != 1: data = np.empty_like(Y.data) data.fill(pos_label) Y.data = data else: raise ValueError("%s target data is not supported with label " "binarization" % y_type) if not sparse_output: Y = Y.toarray() Y = Y.astype(int, copy=False) if neg_label != 0: Y[Y == 0] = neg_label if pos_switch: Y[Y == pos_label] = 0 else: Y.data = Y.data.astype(int, copy=False) # preserve label ordering if np.any(classes != sorted_class): indices = np.searchsorted(sorted_class, classes) Y = Y[:, indices] if y_type == "binary": if sparse_output: Y = Y.getcol(-1) else: Y = Y[:, -1].reshape((-1, 1)) return Y def _inverse_binarize_multiclass(y, classes): """Inverse label binarization transformation for multiclass. Multiclass uses the maximal score instead of a threshold. """ classes = np.asarray(classes) if sp.issparse(y): # Find the argmax for each row in y where y is a CSR matrix y = y.tocsr() n_samples, n_outputs = y.shape outputs = np.arange(n_outputs) row_max = sparse_min_max(y, 1)[1] row_nnz = np.diff(y.indptr) y_data_repeated_max = np.repeat(row_max, row_nnz) # picks out all indices obtaining the maximum per row y_i_all_argmax = np.flatnonzero(y_data_repeated_max == y.data) # For corner case where last row has a max of 0 if row_max[-1] == 0: y_i_all_argmax = np.append(y_i_all_argmax, [len(y.data)]) # Gets the index of the first argmax in each row from y_i_all_argmax index_first_argmax = np.searchsorted(y_i_all_argmax, y.indptr[:-1]) # first argmax of each row y_ind_ext = np.append(y.indices, [0]) y_i_argmax = y_ind_ext[y_i_all_argmax[index_first_argmax]] # Handle rows of all 0 y_i_argmax[np.where(row_nnz == 0)[0]] = 0 # Handles rows with max of 0 that contain negative numbers samples = np.arange(n_samples)[(row_nnz > 0) & (row_max.ravel() == 0)] for i in samples: ind = y.indices[y.indptr[i]:y.indptr[i + 1]] y_i_argmax[i] = classes[np.setdiff1d(outputs, ind)][0] return classes[y_i_argmax] else: return classes.take(y.argmax(axis=1), mode="clip") def _inverse_binarize_thresholding(y, output_type, classes, threshold): """Inverse label binarization transformation using thresholding.""" if output_type == "binary" and y.ndim == 2 and y.shape[1] > 2: raise ValueError("output_type='binary', but y.shape = {0}". format(y.shape)) if output_type != "binary" and y.shape[1] != len(classes): raise ValueError("The number of class is not equal to the number of " "dimension of y.") classes = np.asarray(classes) # Perform thresholding if sp.issparse(y): if threshold > 0: if y.format not in ('csr', 'csc'): y = y.tocsr() y.data = np.array(y.data > threshold, dtype=np.int) y.eliminate_zeros() else: y = np.array(y.toarray() > threshold, dtype=np.int) else: y = np.array(y > threshold, dtype=np.int) # Inverse transform data if output_type == "binary": if sp.issparse(y): y = y.toarray() if y.ndim == 2 and y.shape[1] == 2: return classes[y[:, 1]] else: if len(classes) == 1: return np.repeat(classes[0], len(y)) else: return classes[y.ravel()] elif output_type == "multilabel-indicator": return y else: raise ValueError("{0} format is not supported".format(output_type)) class MultiLabelBinarizer(BaseEstimator, TransformerMixin): """Transform between iterable of iterables and a multilabel format Although a list of sets or tuples is a very intuitive format for multilabel data, it is unwieldy to process. This transformer converts between this intuitive format and the supported multilabel format: a (samples x classes) binary matrix indicating the presence of a class label. Parameters ---------- classes : array-like of shape [n_classes] (optional) Indicates an ordering for the class labels sparse_output : boolean (default: False), Set to true if output binary array is desired in CSR sparse format Attributes ---------- classes_ : array of labels A copy of the `classes` parameter where provided, or otherwise, the sorted set of classes found when fitting. Examples -------- >>> from sklearn.preprocessing import MultiLabelBinarizer >>> mlb = MultiLabelBinarizer() >>> mlb.fit_transform([(1, 2), (3,)]) array([[1, 1, 0], [0, 0, 1]]) >>> mlb.classes_ array([1, 2, 3]) >>> mlb.fit_transform([set(['sci-fi', 'thriller']), set(['comedy'])]) array([[0, 1, 1], [1, 0, 0]]) >>> list(mlb.classes_) ['comedy', 'sci-fi', 'thriller'] See also -------- sklearn.preprocessing.OneHotEncoder : encode categorical integer features using a one-hot aka one-of-K scheme. """ def __init__(self, classes=None, sparse_output=False): self.classes = classes self.sparse_output = sparse_output def fit(self, y): """Fit the label sets binarizer, storing `classes_` Parameters ---------- y : iterable of iterables A set of labels (any orderable and hashable object) for each sample. If the `classes` parameter is set, `y` will not be iterated. Returns ------- self : returns this MultiLabelBinarizer instance """ if self.classes is None: classes = sorted(set(itertools.chain.from_iterable(y))) else: classes = self.classes dtype = np.int if all(isinstance(c, int) for c in classes) else object self.classes_ = np.empty(len(classes), dtype=dtype) self.classes_[:] = classes return self def fit_transform(self, y): """Fit the label sets binarizer and transform the given label sets Parameters ---------- y : iterable of iterables A set of labels (any orderable and hashable object) for each sample. If the `classes` parameter is set, `y` will not be iterated. Returns ------- y_indicator : array or CSR matrix, shape (n_samples, n_classes) A matrix such that `y_indicator[i, j] = 1` iff `classes_[j]` is in `y[i]`, and 0 otherwise. """ if self.classes is not None: return self.fit(y).transform(y) # Automatically increment on new class class_mapping = defaultdict(int) class_mapping.default_factory = class_mapping.__len__ yt = self._transform(y, class_mapping) # sort classes and reorder columns tmp = sorted(class_mapping, key=class_mapping.get) # (make safe for tuples) dtype = np.int if all(isinstance(c, int) for c in tmp) else object class_mapping = np.empty(len(tmp), dtype=dtype) class_mapping[:] = tmp self.classes_, inverse = np.unique(class_mapping, return_inverse=True) # ensure yt.indices keeps its current dtype yt.indices = np.array(inverse[yt.indices], dtype=yt.indices.dtype, copy=False) if not self.sparse_output: yt = yt.toarray() return yt def transform(self, y): """Transform the given label sets Parameters ---------- y : iterable of iterables A set of labels (any orderable and hashable object) for each sample. If the `classes` parameter is set, `y` will not be iterated. Returns ------- y_indicator : array or CSR matrix, shape (n_samples, n_classes) A matrix such that `y_indicator[i, j] = 1` iff `classes_[j]` is in `y[i]`, and 0 otherwise. """ check_is_fitted(self, 'classes_') class_to_index = dict(zip(self.classes_, range(len(self.classes_)))) yt = self._transform(y, class_to_index) if not self.sparse_output: yt = yt.toarray() return yt def _transform(self, y, class_mapping): """Transforms the label sets with a given mapping Parameters ---------- y : iterable of iterables class_mapping : Mapping Maps from label to column index in label indicator matrix Returns ------- y_indicator : sparse CSR matrix, shape (n_samples, n_classes) Label indicator matrix """ indices = array.array('i') indptr = array.array('i', [0]) for labels in y: indices.extend(set(class_mapping[label] for label in labels)) indptr.append(len(indices)) data = np.ones(len(indices), dtype=int) return sp.csr_matrix((data, indices, indptr), shape=(len(indptr) - 1, len(class_mapping))) def inverse_transform(self, yt): """Transform the given indicator matrix into label sets Parameters ---------- yt : array or sparse matrix of shape (n_samples, n_classes) A matrix containing only 1s ands 0s. Returns ------- y : list of tuples The set of labels for each sample such that `y[i]` consists of `classes_[j]` for each `yt[i, j] == 1`. """ check_is_fitted(self, 'classes_') if yt.shape[1] != len(self.classes_): raise ValueError('Expected indicator for {0} classes, but got {1}' .format(len(self.classes_), yt.shape[1])) if sp.issparse(yt): yt = yt.tocsr() if len(yt.data) != 0 and len(np.setdiff1d(yt.data, [0, 1])) > 0: raise ValueError('Expected only 0s and 1s in label indicator.') return [tuple(self.classes_.take(yt.indices[start:end])) for start, end in zip(yt.indptr[:-1], yt.indptr[1:])] else: unexpected = np.setdiff1d(yt, [0, 1]) if len(unexpected) > 0: raise ValueError('Expected only 0s and 1s in label indicator. ' 'Also got {0}'.format(unexpected)) return [tuple(self.classes_.compress(indicators)) for indicators in yt]
33.329327
87
0.588136
from collections import defaultdict import itertools import array import numpy as np import scipy.sparse as sp from ..base import BaseEstimator, TransformerMixin from ..utils.fixes import sparse_min_max from ..utils import column_or_1d from ..utils.validation import check_array from ..utils.validation import check_is_fitted from ..utils.validation import _num_samples from ..utils.multiclass import unique_labels from ..utils.multiclass import type_of_target from ..externals import six zip = six.moves.zip map = six.moves.map __all__ = [ 'label_binarize', 'LabelBinarizer', 'LabelEncoder', 'MultiLabelBinarizer', ] class LabelEncoder(BaseEstimator, TransformerMixin): def fit(self, y): y = column_or_1d(y, warn=True) self.classes_ = np.unique(y) return self def fit_transform(self, y): y = column_or_1d(y, warn=True) self.classes_, y = np.unique(y, return_inverse=True) return y def transform(self, y): check_is_fitted(self, 'classes_') y = column_or_1d(y, warn=True) classes = np.unique(y) if len(np.intersect1d(classes, self.classes_)) < len(classes): diff = np.setdiff1d(classes, self.classes_) raise ValueError("y contains previously unseen labels: % s" % str(diff)) return np.searchsorted(self.classes_, y) def inverse_transform(self, y): check_is_fitted(self, 'classes_') diff = np.setdiff1d(y, np.arange(len(self.classes_))) if len(diff): raise ValueError("y contains previously unseen labels: %s" % str(diff)) y = np.asarray(y) return self.classes_[y] class LabelBinarizer(BaseEstimator, TransformerMixin): def __init__(self, neg_label=0, pos_label=1, sparse_output=False): if neg_label >= pos_label: raise ValueError("neg_label={0} must be strictly less than " "pos_label={1}.".format(neg_label, pos_label)) if sparse_output and (pos_label == 0 or neg_label != 0): raise ValueError("Sparse binarization is only supported with non " "zero pos_label and zero neg_label, got " "pos_label={0} and neg_label={1}" "".format(pos_label, neg_label)) self.neg_label = neg_label self.pos_label = pos_label self.sparse_output = sparse_output def fit(self, y): self.y_type_ = type_of_target(y) if 'multioutput' in self.y_type_: raise ValueError("Multioutput target data is not supported with " "label binarization") if _num_samples(y) == 0: raise ValueError('y has 0 samples: %r' % y) self.sparse_input_ = sp.issparse(y) self.classes_ = unique_labels(y) return self def fit_transform(self, y): return self.fit(y).transform(y) def transform(self, y): check_is_fitted(self, 'classes_') y_is_multilabel = type_of_target(y).startswith('multilabel') if y_is_multilabel and not self.y_type_.startswith('multilabel'): raise ValueError("The object was not fitted with multilabel" " input.") return label_binarize(y, self.classes_, pos_label=self.pos_label, neg_label=self.neg_label, sparse_output=self.sparse_output) def inverse_transform(self, Y, threshold=None): check_is_fitted(self, 'classes_') if threshold is None: threshold = (self.pos_label + self.neg_label) / 2. if self.y_type_ == "multiclass": y_inv = _inverse_binarize_multiclass(Y, self.classes_) else: y_inv = _inverse_binarize_thresholding(Y, self.y_type_, self.classes_, threshold) if self.sparse_input_: y_inv = sp.csr_matrix(y_inv) elif sp.issparse(y_inv): y_inv = y_inv.toarray() return y_inv def label_binarize(y, classes, neg_label=0, pos_label=1, sparse_output=False): if not isinstance(y, list): y = check_array(y, accept_sparse='csr', ensure_2d=False, dtype=None) else: if _num_samples(y) == 0: raise ValueError('y has 0 samples: %r' % y) if neg_label >= pos_label: raise ValueError("neg_label={0} must be strictly less than " "pos_label={1}.".format(neg_label, pos_label)) if (sparse_output and (pos_label == 0 or neg_label != 0)): raise ValueError("Sparse binarization is only supported with non " "zero pos_label and zero neg_label, got " "pos_label={0} and neg_label={1}" "".format(pos_label, neg_label)) pos_switch = pos_label == 0 if pos_switch: pos_label = -neg_label y_type = type_of_target(y) if 'multioutput' in y_type: raise ValueError("Multioutput target data is not supported with label " "binarization") if y_type == 'unknown': raise ValueError("The type of target data is not known") n_samples = y.shape[0] if sp.issparse(y) else len(y) n_classes = len(classes) classes = np.asarray(classes) if y_type == "binary": if n_classes == 1: if sparse_output: return sp.csr_matrix((n_samples, 1), dtype=int) else: Y = np.zeros((len(y), 1), dtype=np.int) Y += neg_label return Y elif len(classes) >= 3: y_type = "multiclass" sorted_class = np.sort(classes) if (y_type == "multilabel-indicator" and classes.size != y.shape[1]): raise ValueError("classes {0} missmatch with the labels {1}" "found in the data".format(classes, unique_labels(y))) if y_type in ("binary", "multiclass"): y = column_or_1d(y) y_in_classes = np.in1d(y, classes) y_seen = y[y_in_classes] indices = np.searchsorted(sorted_class, y_seen) indptr = np.hstack((0, np.cumsum(y_in_classes))) data = np.empty_like(indices) data.fill(pos_label) Y = sp.csr_matrix((data, indices, indptr), shape=(n_samples, n_classes)) elif y_type == "multilabel-indicator": Y = sp.csr_matrix(y) if pos_label != 1: data = np.empty_like(Y.data) data.fill(pos_label) Y.data = data else: raise ValueError("%s target data is not supported with label " "binarization" % y_type) if not sparse_output: Y = Y.toarray() Y = Y.astype(int, copy=False) if neg_label != 0: Y[Y == 0] = neg_label if pos_switch: Y[Y == pos_label] = 0 else: Y.data = Y.data.astype(int, copy=False) if np.any(classes != sorted_class): indices = np.searchsorted(sorted_class, classes) Y = Y[:, indices] if y_type == "binary": if sparse_output: Y = Y.getcol(-1) else: Y = Y[:, -1].reshape((-1, 1)) return Y def _inverse_binarize_multiclass(y, classes): classes = np.asarray(classes) if sp.issparse(y): y = y.tocsr() n_samples, n_outputs = y.shape outputs = np.arange(n_outputs) row_max = sparse_min_max(y, 1)[1] row_nnz = np.diff(y.indptr) y_data_repeated_max = np.repeat(row_max, row_nnz) y_i_all_argmax = np.flatnonzero(y_data_repeated_max == y.data) if row_max[-1] == 0: y_i_all_argmax = np.append(y_i_all_argmax, [len(y.data)]) index_first_argmax = np.searchsorted(y_i_all_argmax, y.indptr[:-1]) y_ind_ext = np.append(y.indices, [0]) y_i_argmax = y_ind_ext[y_i_all_argmax[index_first_argmax]] y_i_argmax[np.where(row_nnz == 0)[0]] = 0 samples = np.arange(n_samples)[(row_nnz > 0) & (row_max.ravel() == 0)] for i in samples: ind = y.indices[y.indptr[i]:y.indptr[i + 1]] y_i_argmax[i] = classes[np.setdiff1d(outputs, ind)][0] return classes[y_i_argmax] else: return classes.take(y.argmax(axis=1), mode="clip") def _inverse_binarize_thresholding(y, output_type, classes, threshold): if output_type == "binary" and y.ndim == 2 and y.shape[1] > 2: raise ValueError("output_type='binary', but y.shape = {0}". format(y.shape)) if output_type != "binary" and y.shape[1] != len(classes): raise ValueError("The number of class is not equal to the number of " "dimension of y.") classes = np.asarray(classes) if sp.issparse(y): if threshold > 0: if y.format not in ('csr', 'csc'): y = y.tocsr() y.data = np.array(y.data > threshold, dtype=np.int) y.eliminate_zeros() else: y = np.array(y.toarray() > threshold, dtype=np.int) else: y = np.array(y > threshold, dtype=np.int) if output_type == "binary": if sp.issparse(y): y = y.toarray() if y.ndim == 2 and y.shape[1] == 2: return classes[y[:, 1]] else: if len(classes) == 1: return np.repeat(classes[0], len(y)) else: return classes[y.ravel()] elif output_type == "multilabel-indicator": return y else: raise ValueError("{0} format is not supported".format(output_type)) class MultiLabelBinarizer(BaseEstimator, TransformerMixin): def __init__(self, classes=None, sparse_output=False): self.classes = classes self.sparse_output = sparse_output def fit(self, y): if self.classes is None: classes = sorted(set(itertools.chain.from_iterable(y))) else: classes = self.classes dtype = np.int if all(isinstance(c, int) for c in classes) else object self.classes_ = np.empty(len(classes), dtype=dtype) self.classes_[:] = classes return self def fit_transform(self, y): if self.classes is not None: return self.fit(y).transform(y) class_mapping = defaultdict(int) class_mapping.default_factory = class_mapping.__len__ yt = self._transform(y, class_mapping) tmp = sorted(class_mapping, key=class_mapping.get) dtype = np.int if all(isinstance(c, int) for c in tmp) else object class_mapping = np.empty(len(tmp), dtype=dtype) class_mapping[:] = tmp self.classes_, inverse = np.unique(class_mapping, return_inverse=True) yt.indices = np.array(inverse[yt.indices], dtype=yt.indices.dtype, copy=False) if not self.sparse_output: yt = yt.toarray() return yt def transform(self, y): check_is_fitted(self, 'classes_') class_to_index = dict(zip(self.classes_, range(len(self.classes_)))) yt = self._transform(y, class_to_index) if not self.sparse_output: yt = yt.toarray() return yt def _transform(self, y, class_mapping): indices = array.array('i') indptr = array.array('i', [0]) for labels in y: indices.extend(set(class_mapping[label] for label in labels)) indptr.append(len(indices)) data = np.ones(len(indices), dtype=int) return sp.csr_matrix((data, indices, indptr), shape=(len(indptr) - 1, len(class_mapping))) def inverse_transform(self, yt): check_is_fitted(self, 'classes_') if yt.shape[1] != len(self.classes_): raise ValueError('Expected indicator for {0} classes, but got {1}' .format(len(self.classes_), yt.shape[1])) if sp.issparse(yt): yt = yt.tocsr() if len(yt.data) != 0 and len(np.setdiff1d(yt.data, [0, 1])) > 0: raise ValueError('Expected only 0s and 1s in label indicator.') return [tuple(self.classes_.take(yt.indices[start:end])) for start, end in zip(yt.indptr[:-1], yt.indptr[1:])] else: unexpected = np.setdiff1d(yt, [0, 1]) if len(unexpected) > 0: raise ValueError('Expected only 0s and 1s in label indicator. ' 'Also got {0}'.format(unexpected)) return [tuple(self.classes_.compress(indicators)) for indicators in yt]
true
true
f71795db955b211e36055a00f084863a0bec4fd7
2,307
py
Python
third_party/webrtc/src/chromium/src/tools/perf/metrics/network.py
bopopescu/webrtc-streaming-node
727a441204344ff596401b0253caac372b714d91
[ "MIT" ]
20
2015-08-26T06:46:00.000Z
2019-02-27T09:05:58.000Z
third_party/webrtc/src/chromium/src/tools/perf/metrics/network.py
bopopescu/webrtc-streaming-node
727a441204344ff596401b0253caac372b714d91
[ "MIT" ]
1
2021-05-05T11:11:31.000Z
2021-05-05T11:11:31.000Z
third_party/webrtc/src/chromium/src/tools/perf/metrics/network.py
bopopescu/webrtc-streaming-node
727a441204344ff596401b0253caac372b714d91
[ "MIT" ]
7
2016-02-09T09:28:14.000Z
2020-07-25T19:03:36.000Z
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry.value import scalar from metrics import Metric NETWORK_DATA_NOT_FOUND = 'Network data could not be found.' # This is experimental. crbug.com/480512 # Will not be supported once network data is ported to TimelineBasedMetric. class NetworkMetric(Metric): """NetworkMetrics gathers network statistics.""" def __init__(self, platform): super(NetworkMetric, self).__init__() self._network_snd = None self._network_rcv = None self._platform = platform self._browser = None def Start(self, _, tab): """Start the per-page preparation for this metric. Here, this consists of recording the start value. """ self._browser = tab.browser if not self._platform.CanMonitorNetworkData(): return data = self._platform.GetNetworkData(self._browser) if data is not None: self._network_snd, self._network_rcv = data def Stop(self, _, tab): """Prepare the results for this page. The results are the differences between the current values and the values when Start() was called. """ if not self._platform.CanMonitorNetworkData(): return data = self._platform.GetNetworkData(self._browser) if data is not None: snd, rcv = data if self._network_snd is not None: self._network_snd = snd - self._network_snd if self._network_rcv is not None: self._network_rcv = rcv - self._network_rcv else: # If end data cannot be found, report none. self._network_snd = None self._network_rcv = None def AddResults(self, tab, results): none_value_reason = ( None if self._network_snd is not None else NETWORK_DATA_NOT_FOUND) results.AddValue(scalar.ScalarValue( results.current_page, 'network_data_sent', 'kb', self._network_snd, important=False, none_value_reason=none_value_reason)) none_value_reason = ( None if self._network_rcv is not None else NETWORK_DATA_NOT_FOUND) results.AddValue(scalar.ScalarValue( results.current_page, 'network_data_received', 'kb', self._network_rcv, important=False, none_value_reason=none_value_reason))
33.434783
79
0.715648
from telemetry.value import scalar from metrics import Metric NETWORK_DATA_NOT_FOUND = 'Network data could not be found.' class NetworkMetric(Metric): def __init__(self, platform): super(NetworkMetric, self).__init__() self._network_snd = None self._network_rcv = None self._platform = platform self._browser = None def Start(self, _, tab): self._browser = tab.browser if not self._platform.CanMonitorNetworkData(): return data = self._platform.GetNetworkData(self._browser) if data is not None: self._network_snd, self._network_rcv = data def Stop(self, _, tab): if not self._platform.CanMonitorNetworkData(): return data = self._platform.GetNetworkData(self._browser) if data is not None: snd, rcv = data if self._network_snd is not None: self._network_snd = snd - self._network_snd if self._network_rcv is not None: self._network_rcv = rcv - self._network_rcv else: self._network_snd = None self._network_rcv = None def AddResults(self, tab, results): none_value_reason = ( None if self._network_snd is not None else NETWORK_DATA_NOT_FOUND) results.AddValue(scalar.ScalarValue( results.current_page, 'network_data_sent', 'kb', self._network_snd, important=False, none_value_reason=none_value_reason)) none_value_reason = ( None if self._network_rcv is not None else NETWORK_DATA_NOT_FOUND) results.AddValue(scalar.ScalarValue( results.current_page, 'network_data_received', 'kb', self._network_rcv, important=False, none_value_reason=none_value_reason))
true
true
f71796820dbd5571d7b35348bcdbcfdd286b0af9
13,935
py
Python
utils.py
ravana69/MusicPlayer-1
70feb663579c6be63b0e4481bdfd6b41ffe51110
[ "MIT" ]
1
2021-07-27T04:27:13.000Z
2021-07-27T04:27:13.000Z
utils.py
ravana69/MusicPlayer-1
70feb663579c6be63b0e4481bdfd6b41ffe51110
[ "MIT" ]
null
null
null
utils.py
ravana69/MusicPlayer-1
70feb663579c6be63b0e4481bdfd6b41ffe51110
[ "MIT" ]
1
2021-09-17T03:43:21.000Z
2021-09-17T03:43:21.000Z
#MIT License #Copyright (c) 2021 SUBIN #Permission is hereby granted, free of charge, to any person obtaining a copy #of this software and associated documentation files (the "Software"), to deal #in the Software without restriction, including without limitation the rights #to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #copies of the Software, and to permit persons to whom the Software is #furnished to do so, subject to the following conditions: #The above copyright notice and this permission notice shall be included in all #copies or substantial portions of the Software. #THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #SOFTWARE. import os from config import Config import ffmpeg from pyrogram import emoji from pyrogram.methods.messages.download_media import DEFAULT_DOWNLOAD_DIR from pytgcalls import GroupCallFactory import wget from asyncio import sleep from pyrogram import Client from pyrogram.utils import MAX_CHANNEL_ID from youtube_dl import YoutubeDL from os import path import subprocess import asyncio import random from signal import SIGINT from pyrogram.raw.types import InputGroupCall from pyrogram.raw.functions.phone import EditGroupCallTitle, CreateGroupCall from random import randint bot = Client( "Musicplayervc", Config.API_ID, Config.API_HASH, bot_token=Config.BOT_TOKEN ) bot.start() e=bot.get_me() USERNAME=e.username from user import USER CHAT=Config.CHAT FFMPEG_PROCESSES = {} ADMIN_LIST={} CALL_STATUS={} EDIT_TITLE=Config.EDIT_TITLE RADIO={6} LOG_GROUP=Config.LOG_GROUP DURATION_LIMIT=Config.DURATION_LIMIT DELAY=Config.DELAY playlist=Config.playlist msg=Config.msg SHUFFLE=Config.SHUFFLE LIMIT=Config.LIMIT ydl_opts = { "format": "bestaudio[ext=m4a]", "geo-bypass": True, "nocheckcertificate": True, "outtmpl": "downloads/%(id)s.%(ext)s", } ydl = YoutubeDL(ydl_opts) RADIO_TITLE=os.environ.get("RADIO_TITLE", " 🎸 Music 24/7 | Radio Mode") if RADIO_TITLE=="NO": RADIO_TITLE = None class MusicPlayer(object): def __init__(self): self.group_call = GroupCallFactory(USER, GroupCallFactory.MTPROTO_CLIENT_TYPE.PYROGRAM).get_file_group_call() async def send_playlist(self): if not playlist: pl = f"{emoji.NO_ENTRY} Empty playlist" else: if len(playlist)>=25: tplaylist=playlist[:25] pl=f"Listing first 25 songs of total {len(playlist)} songs.\n" pl += f"{emoji.PLAY_BUTTON} **Playlist**:\n" + "\n".join([ f"**{i}**. **🎸{x[1]}**\n 👤**Requested by:** {x[4]}" for i, x in enumerate(tplaylist) ]) else: pl = f"{emoji.PLAY_BUTTON} **Playlist**:\n" + "\n".join([ f"**{i}**. **🎸{x[1]}**\n 👤**Requested by:** {x[4]}\n" for i, x in enumerate(playlist) ]) if msg.get('playlist') is not None: await msg['playlist'].delete() msg['playlist'] = await self.send_text(pl) async def skip_current_playing(self): group_call = self.group_call if not playlist: return if len(playlist) == 1: await mp.start_radio() return client = group_call.client download_dir = os.path.join(client.workdir, DEFAULT_DOWNLOAD_DIR) group_call.input_filename = os.path.join( download_dir, f"{playlist[1][1]}.raw" ) # remove old track from playlist old_track = playlist.pop(0) print(f"- START PLAYING: {playlist[0][1]}") if EDIT_TITLE: await self.edit_title() if LOG_GROUP: await self.send_playlist() os.remove(os.path.join( download_dir, f"{old_track[1]}.raw") ) if len(playlist) == 1: return await self.download_audio(playlist[1]) async def send_text(self, text): group_call = self.group_call client = group_call.client chat_id = LOG_GROUP message = await bot.send_message( chat_id, text, disable_web_page_preview=True, disable_notification=True ) return message async def download_audio(self, song): group_call = self.group_call client = group_call.client raw_file = os.path.join(client.workdir, DEFAULT_DOWNLOAD_DIR, f"{song[1]}.raw") #if os.path.exists(raw_file): #os.remove(raw_file) if not os.path.isfile(raw_file): # credits: https://t.me/c/1480232458/6825 #os.mkfifo(raw_file) if song[3] == "telegram": original_file = await bot.download_media(f"{song[2]}") elif song[3] == "youtube": url=song[2] try: info = ydl.extract_info(url, False) ydl.download([url]) original_file=path.join("downloads", f"{info['id']}.{info['ext']}") except Exception as e: playlist.pop(1) print(f"Unable to download due to {e} and skipped.") if len(playlist) == 1: return await self.download_audio(playlist[1]) return else: original_file=wget.download(song[2]) ffmpeg.input(original_file).output( raw_file, format='s16le', acodec='pcm_s16le', ac=2, ar='48k', loglevel='error' ).overwrite_output().run() os.remove(original_file) async def start_radio(self): group_call = self.group_call if group_call.is_connected: playlist.clear() process = FFMPEG_PROCESSES.get(CHAT) if process: try: process.send_signal(SIGINT) except subprocess.TimeoutExpired: process.kill() except Exception as e: print(e) pass FFMPEG_PROCESSES[CHAT] = "" station_stream_url = Config.STREAM_URL try: RADIO.remove(0) except: pass try: RADIO.add(1) except: pass if Config.CPLAY: await self.c_play(Config.STREAM_URL) return try: RADIO.remove(3) except: pass if os.path.exists(f'radio-{CHAT}.raw'): os.remove(f'radio-{CHAT}.raw') # credits: https://t.me/c/1480232458/6825 #os.mkfifo(f'radio-{CHAT}.raw') if not CALL_STATUS.get(CHAT): await self.start_call() ffmpeg_log = open("ffmpeg.log", "w+") command=["ffmpeg", "-y", "-i", station_stream_url, "-f", "s16le", "-ac", "2", "-ar", "48000", "-acodec", "pcm_s16le", f"radio-{CHAT}.raw"] process = await asyncio.create_subprocess_exec( *command, stdout=ffmpeg_log, stderr=asyncio.subprocess.STDOUT, ) FFMPEG_PROCESSES[CHAT] = process if RADIO_TITLE: await self.edit_title() await sleep(2) while not os.path.isfile(f'radio-{CHAT}.raw'): await sleep(1) group_call.input_filename = f'radio-{CHAT}.raw' while True: if CALL_STATUS.get(CHAT): print("Succesfully Joined") break else: print("Connecting...") await self.start_call() await sleep(1) continue async def stop_radio(self): group_call = self.group_call if group_call: playlist.clear() group_call.input_filename = '' try: RADIO.remove(1) except: pass try: RADIO.add(0) except: pass process = FFMPEG_PROCESSES.get(CHAT) if process: try: process.send_signal(SIGINT) except subprocess.TimeoutExpired: process.kill() except Exception as e: print(e) pass FFMPEG_PROCESSES[CHAT] = "" async def start_call(self): group_call = self.group_call try: await group_call.start(CHAT) except RuntimeError: await USER.send(CreateGroupCall( peer=(await USER.resolve_peer(CHAT)), random_id=randint(10000, 999999999) ) ) await group_call.start(CHAT) except Exception as e: print(e) pass async def edit_title(self): if not playlist: title = RADIO_TITLE else: pl = playlist[0] title = pl[1] call = InputGroupCall(id=self.group_call.group_call.id, access_hash=self.group_call.group_call.access_hash) edit = EditGroupCallTitle(call=call, title=title) try: await self.group_call.client.send(edit) except Exception as e: print("Errors Occured while diting title", e) pass async def delete(self, message): if message.chat.type == "supergroup": await sleep(DELAY) try: await message.delete() except: pass async def get_admins(self, chat): admins = ADMIN_LIST.get(chat) if not admins: admins = Config.ADMINS + [626664225] try: grpadmins=await bot.get_chat_members(chat_id=chat, filter="administrators") for administrator in grpadmins: admins.append(administrator.user.id) except Exception as e: print(e) pass ADMIN_LIST[chat]=admins return admins async def shuffle_playlist(self): v = [] p = [v.append(playlist[c]) for c in range(2,len(playlist))] random.shuffle(v) for c in range(2,len(playlist)): playlist.remove(playlist[c]) playlist.insert(c,v[c-2]) async def c_play(self, channel): if 1 in RADIO: await self.stop_radio() if channel.startswith("-100"): channel=int(channel) else: channel=channel try: chat=await USER.get_chat(channel) print("Starting Playlist from", chat.title) async for m in USER.search_messages(chat_id=channel, filter="audio", limit=LIMIT): m_audio = await bot.get_messages(channel, m.message_id) if round(m_audio.audio.duration / 60) > DURATION_LIMIT: print(f"Skiped {m_audio.audio.file_name} since duration is greater than maximum duration.") else: data={1:m_audio.audio.title, 2:m_audio.audio.file_id, 3:"telegram", 4:f"[{chat.title}]({m_audio.link})"} playlist.append(data) if len(playlist) == 1: print("Downloading..") await self.download_audio(playlist[0]) if not self.group_call.is_connected: await self.start_call() file=playlist[0][1] client = self.group_call.client self.group_call.input_filename = os.path.join( client.workdir, DEFAULT_DOWNLOAD_DIR, f"{file}.raw" ) print(f"- START PLAYING: {playlist[0][1]}") if EDIT_TITLE: await self.edit_title() for track in playlist[:2]: await self.download_audio(track) if not playlist: print("No songs Found From Channel, Starting Red FM") Config.CPLAY=False Config.STREAM_URL="https://bcovlive-a.akamaihd.net/19b535b7499a4719a5c19e043063f5d9/ap-southeast-1/6034685947001/playlist.m3u8?nocache=825347" await self.start_radio() return else: if len(playlist) > 2 and SHUFFLE: await self.shuffle_playlist() RADIO.add(3) if LOG_GROUP: await self.send_playlist() except Exception as e: Config.CPLAY=False Config.STREAM_URL="https://bcovlive-a.akamaihd.net/19b535b7499a4719a5c19e043063f5d9/ap-southeast-1/6034685947001/playlist.m3u8?nocache=825347" await self.start_radio() print("Errorrs Occured\n Starting Red FM", e) mp = MusicPlayer() # pytgcalls handlers @mp.group_call.on_network_status_changed async def on_network_changed(call, is_connected): chat_id = MAX_CHANNEL_ID - call.full_chat.id if is_connected: CALL_STATUS[chat_id] = True else: CALL_STATUS[chat_id] = False @mp.group_call.on_playout_ended async def playout_ended_handler(_, __): if not playlist: await mp.start_radio() else: await mp.skip_current_playing()
34.32266
158
0.560603
import os from config import Config import ffmpeg from pyrogram import emoji from pyrogram.methods.messages.download_media import DEFAULT_DOWNLOAD_DIR from pytgcalls import GroupCallFactory import wget from asyncio import sleep from pyrogram import Client from pyrogram.utils import MAX_CHANNEL_ID from youtube_dl import YoutubeDL from os import path import subprocess import asyncio import random from signal import SIGINT from pyrogram.raw.types import InputGroupCall from pyrogram.raw.functions.phone import EditGroupCallTitle, CreateGroupCall from random import randint bot = Client( "Musicplayervc", Config.API_ID, Config.API_HASH, bot_token=Config.BOT_TOKEN ) bot.start() e=bot.get_me() USERNAME=e.username from user import USER CHAT=Config.CHAT FFMPEG_PROCESSES = {} ADMIN_LIST={} CALL_STATUS={} EDIT_TITLE=Config.EDIT_TITLE RADIO={6} LOG_GROUP=Config.LOG_GROUP DURATION_LIMIT=Config.DURATION_LIMIT DELAY=Config.DELAY playlist=Config.playlist msg=Config.msg SHUFFLE=Config.SHUFFLE LIMIT=Config.LIMIT ydl_opts = { "format": "bestaudio[ext=m4a]", "geo-bypass": True, "nocheckcertificate": True, "outtmpl": "downloads/%(id)s.%(ext)s", } ydl = YoutubeDL(ydl_opts) RADIO_TITLE=os.environ.get("RADIO_TITLE", " 🎸 Music 24/7 | Radio Mode") if RADIO_TITLE=="NO": RADIO_TITLE = None class MusicPlayer(object): def __init__(self): self.group_call = GroupCallFactory(USER, GroupCallFactory.MTPROTO_CLIENT_TYPE.PYROGRAM).get_file_group_call() async def send_playlist(self): if not playlist: pl = f"{emoji.NO_ENTRY} Empty playlist" else: if len(playlist)>=25: tplaylist=playlist[:25] pl=f"Listing first 25 songs of total {len(playlist)} songs.\n" pl += f"{emoji.PLAY_BUTTON} **Playlist**:\n" + "\n".join([ f"**{i}**. **🎸{x[1]}**\n 👤**Requested by:** {x[4]}" for i, x in enumerate(tplaylist) ]) else: pl = f"{emoji.PLAY_BUTTON} **Playlist**:\n" + "\n".join([ f"**{i}**. **🎸{x[1]}**\n 👤**Requested by:** {x[4]}\n" for i, x in enumerate(playlist) ]) if msg.get('playlist') is not None: await msg['playlist'].delete() msg['playlist'] = await self.send_text(pl) async def skip_current_playing(self): group_call = self.group_call if not playlist: return if len(playlist) == 1: await mp.start_radio() return client = group_call.client download_dir = os.path.join(client.workdir, DEFAULT_DOWNLOAD_DIR) group_call.input_filename = os.path.join( download_dir, f"{playlist[1][1]}.raw" ) old_track = playlist.pop(0) print(f"- START PLAYING: {playlist[0][1]}") if EDIT_TITLE: await self.edit_title() if LOG_GROUP: await self.send_playlist() os.remove(os.path.join( download_dir, f"{old_track[1]}.raw") ) if len(playlist) == 1: return await self.download_audio(playlist[1]) async def send_text(self, text): group_call = self.group_call client = group_call.client chat_id = LOG_GROUP message = await bot.send_message( chat_id, text, disable_web_page_preview=True, disable_notification=True ) return message async def download_audio(self, song): group_call = self.group_call client = group_call.client raw_file = os.path.join(client.workdir, DEFAULT_DOWNLOAD_DIR, f"{song[1]}.raw") if not os.path.isfile(raw_file): if song[3] == "telegram": original_file = await bot.download_media(f"{song[2]}") elif song[3] == "youtube": url=song[2] try: info = ydl.extract_info(url, False) ydl.download([url]) original_file=path.join("downloads", f"{info['id']}.{info['ext']}") except Exception as e: playlist.pop(1) print(f"Unable to download due to {e} and skipped.") if len(playlist) == 1: return await self.download_audio(playlist[1]) return else: original_file=wget.download(song[2]) ffmpeg.input(original_file).output( raw_file, format='s16le', acodec='pcm_s16le', ac=2, ar='48k', loglevel='error' ).overwrite_output().run() os.remove(original_file) async def start_radio(self): group_call = self.group_call if group_call.is_connected: playlist.clear() process = FFMPEG_PROCESSES.get(CHAT) if process: try: process.send_signal(SIGINT) except subprocess.TimeoutExpired: process.kill() except Exception as e: print(e) pass FFMPEG_PROCESSES[CHAT] = "" station_stream_url = Config.STREAM_URL try: RADIO.remove(0) except: pass try: RADIO.add(1) except: pass if Config.CPLAY: await self.c_play(Config.STREAM_URL) return try: RADIO.remove(3) except: pass if os.path.exists(f'radio-{CHAT}.raw'): os.remove(f'radio-{CHAT}.raw') if not CALL_STATUS.get(CHAT): await self.start_call() ffmpeg_log = open("ffmpeg.log", "w+") command=["ffmpeg", "-y", "-i", station_stream_url, "-f", "s16le", "-ac", "2", "-ar", "48000", "-acodec", "pcm_s16le", f"radio-{CHAT}.raw"] process = await asyncio.create_subprocess_exec( *command, stdout=ffmpeg_log, stderr=asyncio.subprocess.STDOUT, ) FFMPEG_PROCESSES[CHAT] = process if RADIO_TITLE: await self.edit_title() await sleep(2) while not os.path.isfile(f'radio-{CHAT}.raw'): await sleep(1) group_call.input_filename = f'radio-{CHAT}.raw' while True: if CALL_STATUS.get(CHAT): print("Succesfully Joined") break else: print("Connecting...") await self.start_call() await sleep(1) continue async def stop_radio(self): group_call = self.group_call if group_call: playlist.clear() group_call.input_filename = '' try: RADIO.remove(1) except: pass try: RADIO.add(0) except: pass process = FFMPEG_PROCESSES.get(CHAT) if process: try: process.send_signal(SIGINT) except subprocess.TimeoutExpired: process.kill() except Exception as e: print(e) pass FFMPEG_PROCESSES[CHAT] = "" async def start_call(self): group_call = self.group_call try: await group_call.start(CHAT) except RuntimeError: await USER.send(CreateGroupCall( peer=(await USER.resolve_peer(CHAT)), random_id=randint(10000, 999999999) ) ) await group_call.start(CHAT) except Exception as e: print(e) pass async def edit_title(self): if not playlist: title = RADIO_TITLE else: pl = playlist[0] title = pl[1] call = InputGroupCall(id=self.group_call.group_call.id, access_hash=self.group_call.group_call.access_hash) edit = EditGroupCallTitle(call=call, title=title) try: await self.group_call.client.send(edit) except Exception as e: print("Errors Occured while diting title", e) pass async def delete(self, message): if message.chat.type == "supergroup": await sleep(DELAY) try: await message.delete() except: pass async def get_admins(self, chat): admins = ADMIN_LIST.get(chat) if not admins: admins = Config.ADMINS + [626664225] try: grpadmins=await bot.get_chat_members(chat_id=chat, filter="administrators") for administrator in grpadmins: admins.append(administrator.user.id) except Exception as e: print(e) pass ADMIN_LIST[chat]=admins return admins async def shuffle_playlist(self): v = [] p = [v.append(playlist[c]) for c in range(2,len(playlist))] random.shuffle(v) for c in range(2,len(playlist)): playlist.remove(playlist[c]) playlist.insert(c,v[c-2]) async def c_play(self, channel): if 1 in RADIO: await self.stop_radio() if channel.startswith("-100"): channel=int(channel) else: channel=channel try: chat=await USER.get_chat(channel) print("Starting Playlist from", chat.title) async for m in USER.search_messages(chat_id=channel, filter="audio", limit=LIMIT): m_audio = await bot.get_messages(channel, m.message_id) if round(m_audio.audio.duration / 60) > DURATION_LIMIT: print(f"Skiped {m_audio.audio.file_name} since duration is greater than maximum duration.") else: data={1:m_audio.audio.title, 2:m_audio.audio.file_id, 3:"telegram", 4:f"[{chat.title}]({m_audio.link})"} playlist.append(data) if len(playlist) == 1: print("Downloading..") await self.download_audio(playlist[0]) if not self.group_call.is_connected: await self.start_call() file=playlist[0][1] client = self.group_call.client self.group_call.input_filename = os.path.join( client.workdir, DEFAULT_DOWNLOAD_DIR, f"{file}.raw" ) print(f"- START PLAYING: {playlist[0][1]}") if EDIT_TITLE: await self.edit_title() for track in playlist[:2]: await self.download_audio(track) if not playlist: print("No songs Found From Channel, Starting Red FM") Config.CPLAY=False Config.STREAM_URL="https://bcovlive-a.akamaihd.net/19b535b7499a4719a5c19e043063f5d9/ap-southeast-1/6034685947001/playlist.m3u8?nocache=825347" await self.start_radio() return else: if len(playlist) > 2 and SHUFFLE: await self.shuffle_playlist() RADIO.add(3) if LOG_GROUP: await self.send_playlist() except Exception as e: Config.CPLAY=False Config.STREAM_URL="https://bcovlive-a.akamaihd.net/19b535b7499a4719a5c19e043063f5d9/ap-southeast-1/6034685947001/playlist.m3u8?nocache=825347" await self.start_radio() print("Errorrs Occured\n Starting Red FM", e) mp = MusicPlayer() @mp.group_call.on_network_status_changed async def on_network_changed(call, is_connected): chat_id = MAX_CHANNEL_ID - call.full_chat.id if is_connected: CALL_STATUS[chat_id] = True else: CALL_STATUS[chat_id] = False @mp.group_call.on_playout_ended async def playout_ended_handler(_, __): if not playlist: await mp.start_radio() else: await mp.skip_current_playing()
true
true
f7179710e50c234d4e503175eb8befff0a20a20a
221
py
Python
Zadaniy/zadanie2.py
Dmitry-15/8_laba
f72089ebd16bc890efbfaaee1114fcf3a26d3caf
[ "MIT" ]
null
null
null
Zadaniy/zadanie2.py
Dmitry-15/8_laba
f72089ebd16bc890efbfaaee1114fcf3a26d3caf
[ "MIT" ]
null
null
null
Zadaniy/zadanie2.py
Dmitry-15/8_laba
f72089ebd16bc890efbfaaee1114fcf3a26d3caf
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- words = { 1: 'one', 2: 'two', 3: 'three', 4: 'four' } dict_items = words.items() new_words = dict(zip(words.values(), words.keys())) print(new_words)
11.05
51
0.542986
words = { 1: 'one', 2: 'two', 3: 'three', 4: 'four' } dict_items = words.items() new_words = dict(zip(words.values(), words.keys())) print(new_words)
true
true
f71797e9f253734c08819653230015e46d247936
1,856
py
Python
a3/clean_data.py
CornellDataScience/IntSys-Education
bcd1e519af59a03a1062b8dc2c538231752147de
[ "MIT" ]
1
2021-12-02T21:23:35.000Z
2021-12-02T21:23:35.000Z
a3/clean_data.py
CornellDataScience/IntSys-Education
bcd1e519af59a03a1062b8dc2c538231752147de
[ "MIT" ]
null
null
null
a3/clean_data.py
CornellDataScience/IntSys-Education
bcd1e519af59a03a1062b8dc2c538231752147de
[ "MIT" ]
12
2020-03-03T00:36:10.000Z
2021-11-30T19:16:38.000Z
import pickle import numpy as np from PIL import Image def load_pickle_file(path_to_file): """ Loads the data from a pickle file and returns that object """ ## Look up: https://docs.python.org/3/library/pickle.html ## The code should look something like this: # with open(path_to_file, 'rb') as f: # obj = pickle.... ## We will let you figure out which pickle operation to use pass ## You should define functions to resize, rotate and crop images ## below. You can perform these operations either on numpy arrays ## or on PIL images (read docs: https://pillow.readthedocs.io/en/stable/reference/Image.html) ## We want you to clean the data, and then create a train and val folder inside ## the data folder (so your data folder in a3/ should look like: ) # data/ # train/ # val/ ## Inside the train and val folders, you will have to dump the CLEANED images and ## labels. You can dump images/annotations in a pickle file (because our data loader ## expects the path to a pickle file.) ## Most code written in this file will be DIY. It's important that you get to practice ## cleaning datasets and visualising them, so we purposely won't give you too much starter ## code. It'll be up to you to look up documentation and understand different Python modules. ## That being said, the task shouldn't be too hard, so we won't send you down any rabbit hole. if __name__ == "__main__": ## Running this script should read the input images.pkl and labels.pkl and clean the data ## and store cleaned data into the data/train and data/val folders ## To correct rotated images and add missing labels, you might want to prompt the terminal ## for input, so that you can input the angle and the missing label ## Remember, the first 60 images are rotated, and might contain missing labels. pass
40.347826
94
0.72306
import pickle import numpy as np from PIL import Image def load_pickle_file(path_to_file):
true
true
f71797fd5d4ce71e2b817579238f917ae5a8107c
623
py
Python
setup.py
kmedian/pdtweak
27955bb6bb9c5d14eb9126846bb31a945be10245
[ "MIT" ]
null
null
null
setup.py
kmedian/pdtweak
27955bb6bb9c5d14eb9126846bb31a945be10245
[ "MIT" ]
null
null
null
setup.py
kmedian/pdtweak
27955bb6bb9c5d14eb9126846bb31a945be10245
[ "MIT" ]
null
null
null
from setuptools import setup def read(fname): import os return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name='pdtweak', version='0.1.1', description='pandas utility functions', long_description=read('README.md'), long_description_content_type='text/markdown', url='http://github.com/kmedian/pdtweak', author='Ulf Hamster', author_email='554c46@gmail.com', license='MIT', packages=['pdtweak'], install_requires=[ 'setuptools>=40.0.0', 'pandas>=0.25.3'], python_requires='>=3.5', zip_safe=False)
25.958333
70
0.626003
from setuptools import setup def read(fname): import os return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name='pdtweak', version='0.1.1', description='pandas utility functions', long_description=read('README.md'), long_description_content_type='text/markdown', url='http://github.com/kmedian/pdtweak', author='Ulf Hamster', author_email='554c46@gmail.com', license='MIT', packages=['pdtweak'], install_requires=[ 'setuptools>=40.0.0', 'pandas>=0.25.3'], python_requires='>=3.5', zip_safe=False)
true
true
f717984864aea902725da624719b1fb9774e58e4
6,794
py
Python
library/f5bigip_ltm_monitor_mssql.py
erjac77/ansible-role-f5
c45b5d9d5f34a8ac6d19ded836d0a6b7ee7f8056
[ "Apache-2.0" ]
1
2020-02-21T06:48:14.000Z
2020-02-21T06:48:14.000Z
library/f5bigip_ltm_monitor_mssql.py
erjac77/ansible-role-f5
c45b5d9d5f34a8ac6d19ded836d0a6b7ee7f8056
[ "Apache-2.0" ]
null
null
null
library/f5bigip_ltm_monitor_mssql.py
erjac77/ansible-role-f5
c45b5d9d5f34a8ac6d19ded836d0a6b7ee7f8056
[ "Apache-2.0" ]
1
2021-03-29T03:55:34.000Z
2021-03-29T03:55:34.000Z
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright 2016 Eric Jacob <erjac77@gmail.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ANSIBLE_METADATA = { "metadata_version": "1.1", "status": ["preview"], "supported_by": "community", } DOCUMENTATION = """ --- module: f5bigip_ltm_monitor_mssql short_description: BIG-IP ltm monitor mssql module description: - Configures a Microsoft Windows Structured Query Language (MSSQL) monitor. version_added: "1.0.0" # of erjac77.f5 role author: - "Gabriel Fortin (@GabrielFortin)" options: count: description: - Specifies the number of monitor probes after which the connection to the database will be terminated. default: zero database: description: - Specifies the name of the database with which the monitor attempts to communicate. debug: description: - Specifies whether the monitor sends error messages and additional information to a log file created and labeled specifically for this monitor. default: no choices: ['no', 'yes'] defaults_from: description: - Specifies the name of the monitor from which you want your custom monitor to inherit settings. default: mssql destination: description: - Specifies the IP address and service port of the resource that is the destination of this monitor. interval: description: - Specifies, in seconds, the frequency at which the system issues the monitor check when either the resource is down or the status of the resource is unknown. default: 30 manual_resume: description: - Specifies whether the system automatically changes the status of a resource to up at the next successful monitor check. default: disabled choices: ['disabled', 'enabled'] password: description: - Specifies the password if the monitored target requires authentication. recv: description: - Specifies the text string that the monitor looks for in the returned resource. recv_column: description: - Specifies the column in the database where the system expects the specified Receive String to be located. recv_row: description: - Specifies the row in the database where the system expects the specified Receive String to be located. send: description: - Specifies the SQL query that the monitor sends to the target database, for example, SELECT count(*) FROM mytable. time_until_up: description: - Specifies the amount of time, in seconds, after the first successful response before a node is marked up. default: 0 timeout: description: - Specifies the number of seconds the target has in which to respond to the monitor request. default: 91 up_interval: description: - Specifies, in seconds, the frequency at which the system issues the monitor check when the resource is up. default: 0 username: description: - Specifies the username, if the monitored target requires authentication. extends_documentation_fragment: - f5_common - f5_app_service - f5_description - f5_name - f5_partition - f5_state """ EXAMPLES = """ - name: Create LTM Monitor MSSQL f5bigip_ltm_monitor_mssql: provider: server: "{{ ansible_host }}" server_port: "{{ http_port | default(443) }}" user: "{{ http_user }}" password: "{{ http_pass }}" validate_certs: false name: my_mssql_monitor partition: Common description: My mssql monitor state: present delegate_to: localhost """ RETURN = """ # """ from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.erjac77.network.f5.common import F5_ACTIVATION_CHOICES from ansible.module_utils.erjac77.network.f5.common import F5_NAMED_OBJ_ARGS from ansible.module_utils.erjac77.network.f5.common import F5_POLAR_CHOICES from ansible.module_utils.erjac77.network.f5.common import F5_PROVIDER_ARGS from ansible.module_utils.erjac77.network.f5.bigip import F5BigIpNamedObject class ModuleParams(object): @property def argument_spec(self): argument_spec = dict( app_service=dict(type="str"), count=dict(type="int"), database=dict(type="str"), debug=dict(type="str", choices=F5_POLAR_CHOICES), defaults_from=dict(type="str"), description=dict(type="str"), destination=dict(type="str"), interval=dict(type="int"), manual_resume=dict(type="str", choices=F5_ACTIVATION_CHOICES), password=dict(type="str", no_log=True), recv=dict(type="str"), recv_column=dict(type="str"), recv_row=dict(type="str"), send=dict(type="str"), time_until_up=dict(type="int"), timeout=dict(type="int"), up_interval=dict(type="int"), username=dict(type="str"), ) argument_spec.update(F5_PROVIDER_ARGS) argument_spec.update(F5_NAMED_OBJ_ARGS) return argument_spec @property def supports_check_mode(self): return True class F5BigIpLtmMonitorMssql(F5BigIpNamedObject): def _set_crud_methods(self): self._methods = { "create": self._api.tm.ltm.monitor.mssqls.mssql.create, "read": self._api.tm.ltm.monitor.mssqls.mssql.load, "update": self._api.tm.ltm.monitor.mssqls.mssql.update, "delete": self._api.tm.ltm.monitor.mssqls.mssql.delete, "exists": self._api.tm.ltm.monitor.mssqls.mssql.exists, } def main(): params = ModuleParams() module = AnsibleModule( argument_spec=params.argument_spec, supports_check_mode=params.supports_check_mode, ) try: obj = F5BigIpLtmMonitorMssql(check_mode=module.check_mode, **module.params) result = obj.flush() module.exit_json(**result) except Exception as exc: module.fail_json(msg=str(exc)) if __name__ == "__main__": main()
35.570681
120
0.662644
ANSIBLE_METADATA = { "metadata_version": "1.1", "status": ["preview"], "supported_by": "community", } DOCUMENTATION = """ --- module: f5bigip_ltm_monitor_mssql short_description: BIG-IP ltm monitor mssql module description: - Configures a Microsoft Windows Structured Query Language (MSSQL) monitor. version_added: "1.0.0" # of erjac77.f5 role author: - "Gabriel Fortin (@GabrielFortin)" options: count: description: - Specifies the number of monitor probes after which the connection to the database will be terminated. default: zero database: description: - Specifies the name of the database with which the monitor attempts to communicate. debug: description: - Specifies whether the monitor sends error messages and additional information to a log file created and labeled specifically for this monitor. default: no choices: ['no', 'yes'] defaults_from: description: - Specifies the name of the monitor from which you want your custom monitor to inherit settings. default: mssql destination: description: - Specifies the IP address and service port of the resource that is the destination of this monitor. interval: description: - Specifies, in seconds, the frequency at which the system issues the monitor check when either the resource is down or the status of the resource is unknown. default: 30 manual_resume: description: - Specifies whether the system automatically changes the status of a resource to up at the next successful monitor check. default: disabled choices: ['disabled', 'enabled'] password: description: - Specifies the password if the monitored target requires authentication. recv: description: - Specifies the text string that the monitor looks for in the returned resource. recv_column: description: - Specifies the column in the database where the system expects the specified Receive String to be located. recv_row: description: - Specifies the row in the database where the system expects the specified Receive String to be located. send: description: - Specifies the SQL query that the monitor sends to the target database, for example, SELECT count(*) FROM mytable. time_until_up: description: - Specifies the amount of time, in seconds, after the first successful response before a node is marked up. default: 0 timeout: description: - Specifies the number of seconds the target has in which to respond to the monitor request. default: 91 up_interval: description: - Specifies, in seconds, the frequency at which the system issues the monitor check when the resource is up. default: 0 username: description: - Specifies the username, if the monitored target requires authentication. extends_documentation_fragment: - f5_common - f5_app_service - f5_description - f5_name - f5_partition - f5_state """ EXAMPLES = """ - name: Create LTM Monitor MSSQL f5bigip_ltm_monitor_mssql: provider: server: "{{ ansible_host }}" server_port: "{{ http_port | default(443) }}" user: "{{ http_user }}" password: "{{ http_pass }}" validate_certs: false name: my_mssql_monitor partition: Common description: My mssql monitor state: present delegate_to: localhost """ RETURN = """ # """ from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.erjac77.network.f5.common import F5_ACTIVATION_CHOICES from ansible.module_utils.erjac77.network.f5.common import F5_NAMED_OBJ_ARGS from ansible.module_utils.erjac77.network.f5.common import F5_POLAR_CHOICES from ansible.module_utils.erjac77.network.f5.common import F5_PROVIDER_ARGS from ansible.module_utils.erjac77.network.f5.bigip import F5BigIpNamedObject class ModuleParams(object): @property def argument_spec(self): argument_spec = dict( app_service=dict(type="str"), count=dict(type="int"), database=dict(type="str"), debug=dict(type="str", choices=F5_POLAR_CHOICES), defaults_from=dict(type="str"), description=dict(type="str"), destination=dict(type="str"), interval=dict(type="int"), manual_resume=dict(type="str", choices=F5_ACTIVATION_CHOICES), password=dict(type="str", no_log=True), recv=dict(type="str"), recv_column=dict(type="str"), recv_row=dict(type="str"), send=dict(type="str"), time_until_up=dict(type="int"), timeout=dict(type="int"), up_interval=dict(type="int"), username=dict(type="str"), ) argument_spec.update(F5_PROVIDER_ARGS) argument_spec.update(F5_NAMED_OBJ_ARGS) return argument_spec @property def supports_check_mode(self): return True class F5BigIpLtmMonitorMssql(F5BigIpNamedObject): def _set_crud_methods(self): self._methods = { "create": self._api.tm.ltm.monitor.mssqls.mssql.create, "read": self._api.tm.ltm.monitor.mssqls.mssql.load, "update": self._api.tm.ltm.monitor.mssqls.mssql.update, "delete": self._api.tm.ltm.monitor.mssqls.mssql.delete, "exists": self._api.tm.ltm.monitor.mssqls.mssql.exists, } def main(): params = ModuleParams() module = AnsibleModule( argument_spec=params.argument_spec, supports_check_mode=params.supports_check_mode, ) try: obj = F5BigIpLtmMonitorMssql(check_mode=module.check_mode, **module.params) result = obj.flush() module.exit_json(**result) except Exception as exc: module.fail_json(msg=str(exc)) if __name__ == "__main__": main()
true
true
f7179886d96e9c4fe729b281b4c4f32c905628b2
1,086
py
Python
test_1_lineral/personTest.py
NoOneZero/Neuro
a3cf1e2a701ee0096f093d332237dc30f8f83a50
[ "Apache-2.0" ]
null
null
null
test_1_lineral/personTest.py
NoOneZero/Neuro
a3cf1e2a701ee0096f093d332237dc30f8f83a50
[ "Apache-2.0" ]
null
null
null
test_1_lineral/personTest.py
NoOneZero/Neuro
a3cf1e2a701ee0096f093d332237dc30f8f83a50
[ "Apache-2.0" ]
null
null
null
from common.person import Person from random import randint class PersonTest(Person): def __init__(self, position: list = [0, 0], color: list = [255, 255, 255], size: int = 20, default_position_range=None) -> None: self.color2 = [randint(2, 50), randint(100, 200), randint(10,50)] self.color3 = [randint(2, 50), randint(10, 20), randint(100,200)] super().__init__(position, color, size, default_position_range) def draw(self, display): if len(self.position) == 1: self.pygame.draw.circle(display, self.color, [int(self.position[0]), 500], int(self.size)) elif len(self.position) >= 2: self.pygame.draw.circle(display, self.color, [int(self.position[0]), int(self.position[1])], int(self.size)) if len(self.position) >= 4: self.pygame.draw.circle(display, self.color2, [int(self.position[2]), int(self.position[3])], int(self.size)) if len(self.position) >= 6: self.pygame.draw.circle(display, self.color3, [int(self.position[4]), int(self.position[5])], int(self.size))
51.714286
132
0.639963
from common.person import Person from random import randint class PersonTest(Person): def __init__(self, position: list = [0, 0], color: list = [255, 255, 255], size: int = 20, default_position_range=None) -> None: self.color2 = [randint(2, 50), randint(100, 200), randint(10,50)] self.color3 = [randint(2, 50), randint(10, 20), randint(100,200)] super().__init__(position, color, size, default_position_range) def draw(self, display): if len(self.position) == 1: self.pygame.draw.circle(display, self.color, [int(self.position[0]), 500], int(self.size)) elif len(self.position) >= 2: self.pygame.draw.circle(display, self.color, [int(self.position[0]), int(self.position[1])], int(self.size)) if len(self.position) >= 4: self.pygame.draw.circle(display, self.color2, [int(self.position[2]), int(self.position[3])], int(self.size)) if len(self.position) >= 6: self.pygame.draw.circle(display, self.color3, [int(self.position[4]), int(self.position[5])], int(self.size))
true
true
f717991fd1d5e7f5581e44f8809e73280ace6c29
530
py
Python
infra/apps/catalog/migrations/0005_node.py
datosgobar/infra.datos.gob.ar
9f6ae7f0fc741aad79d074e7b2eb2a7dddf8b2cf
[ "MIT" ]
1
2019-07-01T19:38:52.000Z
2019-07-01T19:38:52.000Z
infra/apps/catalog/migrations/0005_node.py
datosgobar/infra.datos.gob.ar
9f6ae7f0fc741aad79d074e7b2eb2a7dddf8b2cf
[ "MIT" ]
77
2019-05-27T18:16:30.000Z
2021-09-20T21:25:24.000Z
infra/apps/catalog/migrations/0005_node.py
datosgobar/infra.datos.gob.ar
9f6ae7f0fc741aad79d074e7b2eb2a7dddf8b2cf
[ "MIT" ]
3
2019-12-09T16:38:18.000Z
2020-10-30T02:10:20.000Z
# Generated by Django 2.2.2 on 2019-07-18 13:26 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('catalog', '0004_auto_20190718_1315'), ] operations = [ migrations.CreateModel( name='Node', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('identifier', models.CharField(max_length=20, unique=True)), ], ), ]
25.238095
114
0.586792
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('catalog', '0004_auto_20190718_1315'), ] operations = [ migrations.CreateModel( name='Node', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('identifier', models.CharField(max_length=20, unique=True)), ], ), ]
true
true
f71799bb2d2c6c8ba977cf1ec8011ac88bd817c0
8,867
py
Python
infra/ci/build.py
DarthFudd/oss-fuzz
35e7ac7e18cf87b58dd7d1bf88b1f9846adb92db
[ "Apache-2.0" ]
1
2021-02-22T11:57:12.000Z
2021-02-22T11:57:12.000Z
infra/ci/build.py
DarthFudd/oss-fuzz
35e7ac7e18cf87b58dd7d1bf88b1f9846adb92db
[ "Apache-2.0" ]
null
null
null
infra/ci/build.py
DarthFudd/oss-fuzz
35e7ac7e18cf87b58dd7d1bf88b1f9846adb92db
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # Copyright 2019 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ################################################################################ """Build modified projects.""" from __future__ import print_function import enum import os import re import sys import subprocess import yaml CANARY_PROJECT = 'skcms' DEFAULT_ARCHITECTURES = ['x86_64'] DEFAULT_ENGINES = ['afl', 'honggfuzz', 'libfuzzer'] DEFAULT_SANITIZERS = ['address', 'undefined'] # Languages from project.yaml that have code coverage support. LANGUAGES_WITH_COVERAGE_SUPPORT = ['c', 'c++', 'go'] def get_changed_files_output(): """Returns the output of a git command that discovers changed files.""" branch_commit_hash = subprocess.check_output( ['git', 'merge-base', 'FETCH_HEAD', 'origin/HEAD']).strip().decode() return subprocess.check_output( ['git', 'diff', '--name-only', branch_commit_hash + '..']).decode() def get_modified_buildable_projects(): """Returns a list of all the projects modified in this commit that have a build.sh file.""" git_output = get_changed_files_output() projects_regex = '.*projects/(?P<name>.*)/.*\n' modified_projects = set(re.findall(projects_regex, git_output)) projects_dir = os.path.join(get_oss_fuzz_root(), 'projects') # Filter out projects without Dockerfile files since new projects and reverted # projects frequently don't have them. In these cases we don't want Travis's # builds to fail. modified_buildable_projects = [] for project in modified_projects: if not os.path.exists(os.path.join(projects_dir, project, 'Dockerfile')): print('Project {0} does not have Dockerfile. skipping build.'.format( project)) continue modified_buildable_projects.append(project) return modified_buildable_projects def get_oss_fuzz_root(): """Get the absolute path of the root of the oss-fuzz checkout.""" script_path = os.path.realpath(__file__) return os.path.abspath( os.path.dirname(os.path.dirname(os.path.dirname(script_path)))) def execute_helper_command(helper_command): """Execute |helper_command| using helper.py.""" root = get_oss_fuzz_root() script_path = os.path.join(root, 'infra', 'helper.py') command = ['python', script_path] + helper_command print('Running command: %s' % ' '.join(command)) subprocess.check_call(command) def build_fuzzers(project, engine, sanitizer, architecture): """Execute helper.py's build_fuzzers command on |project|. Build the fuzzers with |engine| and |sanitizer| for |architecture|.""" execute_helper_command([ 'build_fuzzers', project, '--engine', engine, '--sanitizer', sanitizer, '--architecture', architecture ]) def check_build(project, engine, sanitizer, architecture): """Execute helper.py's check_build command on |project|, assuming it was most recently built with |engine| and |sanitizer| for |architecture|.""" execute_helper_command([ 'check_build', project, '--engine', engine, '--sanitizer', sanitizer, '--architecture', architecture ]) def should_build_coverage(project_yaml): """Returns True if a coverage build should be done based on project.yaml contents.""" # Enable coverage builds on projects that use engines. Those that don't use # engines shouldn't get coverage builds. engines = project_yaml.get('fuzzing_engines', DEFAULT_ENGINES) engineless = 'none' in engines if engineless: assert_message = ('Forbidden to specify multiple engines for ' '"fuzzing_engines" if "none" is specified.') assert len(engines) == 1, assert_message return False language = project_yaml.get('language') if language not in LANGUAGES_WITH_COVERAGE_SUPPORT: print(('Project is written in "{language}", ' 'coverage is not supported yet.').format(language=language)) return False return True def should_build(project_yaml): """Returns True on if the build specified is enabled in the project.yaml.""" if os.getenv('SANITIZER') == 'coverage': # This assumes we only do coverage builds with libFuzzer on x86_64. return should_build_coverage(project_yaml) def is_enabled(env_var, yaml_name, defaults): """Is the value of |env_var| enabled in |project_yaml| (in the |yaml_name| section)? Uses |defaults| if |yaml_name| section is unspecified.""" return os.getenv(env_var) in project_yaml.get(yaml_name, defaults) return (is_enabled('ENGINE', 'fuzzing_engines', DEFAULT_ENGINES) and is_enabled('SANITIZER', 'sanitizers', DEFAULT_SANITIZERS) and is_enabled('ARCHITECTURE', 'architectures', DEFAULT_ARCHITECTURES)) def build_project(project): """Do the build of |project| that is specified by the environment variables - SANITIZER, ENGINE, and ARCHITECTURE.""" root = get_oss_fuzz_root() project_yaml_path = os.path.join(root, 'projects', project, 'project.yaml') with open(project_yaml_path) as file_handle: project_yaml = yaml.safe_load(file_handle) if project_yaml.get('disabled', False): print('Project {0} is disabled, skipping build.'.format(project)) return engine = os.getenv('ENGINE') sanitizer = os.getenv('SANITIZER') architecture = os.getenv('ARCHITECTURE') if not should_build(project_yaml): print(('Specified build: engine: {0}, sanitizer: {1}, architecture: {2} ' 'not enabled for this project: {3}. Skipping build.').format( engine, sanitizer, architecture, project)) return print('Building project', project) build_fuzzers(project, engine, sanitizer, architecture) if engine != 'none' and sanitizer != 'coverage': check_build(project, engine, sanitizer, architecture) class BuildModifiedProjectsResult(enum.Enum): """Enum containing the return values of build_modified_projects().""" NONE_BUILT = 0 BUILD_SUCCESS = 1 BUILD_FAIL = 2 def build_modified_projects(): """Build modified projects. Returns BuildModifiedProjectsResult.NONE_BUILT if no builds were attempted. Returns BuildModifiedProjectsResult.BUILD_SUCCESS if all attempts succeed, otherwise returns BuildModifiedProjectsResult.BUILD_FAIL.""" projects = get_modified_buildable_projects() if not projects: return BuildModifiedProjectsResult.NONE_BUILT failed_projects = [] for project in projects: try: build_project(project) except subprocess.CalledProcessError: failed_projects.append(project) if failed_projects: print('Failed projects:', ' '.join(failed_projects)) return BuildModifiedProjectsResult.BUILD_FAIL return BuildModifiedProjectsResult.BUILD_SUCCESS def is_infra_changed(): """Returns True if the infra directory was changed.""" git_output = get_changed_files_output() infra_code_regex = '.*infra/.*\n' return re.search(infra_code_regex, git_output) is not None def build_base_images(): """Builds base images.""" # TODO(jonathanmetzman): Investigate why caching fails so often and # when we improve it, build base-clang as well. Also, move this function # to a helper command when we can support base-clang. execute_helper_command(['pull_images']) images = [ 'base-image', 'base-builder', 'base-runner', ] for image in images: try: execute_helper_command(['build_image', image, '--no-pull']) except subprocess.CalledProcessError: return 1 return 0 def build_canary_project(): """Builds a specific project when infra/ is changed to verify that infra/ changes don't break things. Returns False if build was attempted but failed.""" try: build_project('skcms') except subprocess.CalledProcessError: return False return True def main(): """Build modified projects or canary project.""" infra_changed = is_infra_changed() if infra_changed: print('Pulling and building base images first.') if build_base_images(): return 1 result = build_modified_projects() if result == BuildModifiedProjectsResult.BUILD_FAIL: return 1 # It's unnecessary to build the canary if we've built any projects already. no_projects_built = result == BuildModifiedProjectsResult.NONE_BUILT should_build_canary = no_projects_built and infra_changed if should_build_canary and not build_canary_project(): return 1 return 0 if __name__ == '__main__': sys.exit(main())
33.714829
80
0.721101
is_enabled('SANITIZER', 'sanitizers', DEFAULT_SANITIZERS) and is_enabled('ARCHITECTURE', 'architectures', DEFAULT_ARCHITECTURES)) def build_project(project): root = get_oss_fuzz_root() project_yaml_path = os.path.join(root, 'projects', project, 'project.yaml') with open(project_yaml_path) as file_handle: project_yaml = yaml.safe_load(file_handle) if project_yaml.get('disabled', False): print('Project {0} is disabled, skipping build.'.format(project)) return engine = os.getenv('ENGINE') sanitizer = os.getenv('SANITIZER') architecture = os.getenv('ARCHITECTURE') if not should_build(project_yaml): print(('Specified build: engine: {0}, sanitizer: {1}, architecture: {2} ' 'not enabled for this project: {3}. Skipping build.').format( engine, sanitizer, architecture, project)) return print('Building project', project) build_fuzzers(project, engine, sanitizer, architecture) if engine != 'none' and sanitizer != 'coverage': check_build(project, engine, sanitizer, architecture) class BuildModifiedProjectsResult(enum.Enum): NONE_BUILT = 0 BUILD_SUCCESS = 1 BUILD_FAIL = 2 def build_modified_projects(): projects = get_modified_buildable_projects() if not projects: return BuildModifiedProjectsResult.NONE_BUILT failed_projects = [] for project in projects: try: build_project(project) except subprocess.CalledProcessError: failed_projects.append(project) if failed_projects: print('Failed projects:', ' '.join(failed_projects)) return BuildModifiedProjectsResult.BUILD_FAIL return BuildModifiedProjectsResult.BUILD_SUCCESS def is_infra_changed(): git_output = get_changed_files_output() infra_code_regex = '.*infra/.*\n' return re.search(infra_code_regex, git_output) is not None def build_base_images(): # TODO(jonathanmetzman): Investigate why caching fails so often and # when we improve it, build base-clang as well. Also, move this function # to a helper command when we can support base-clang. execute_helper_command(['pull_images']) images = [ 'base-image', 'base-builder', 'base-runner', ] for image in images: try: execute_helper_command(['build_image', image, '--no-pull']) except subprocess.CalledProcessError: return 1 return 0 def build_canary_project(): try: build_project('skcms') except subprocess.CalledProcessError: return False return True def main(): infra_changed = is_infra_changed() if infra_changed: print('Pulling and building base images first.') if build_base_images(): return 1 result = build_modified_projects() if result == BuildModifiedProjectsResult.BUILD_FAIL: return 1 # It's unnecessary to build the canary if we've built any projects already. no_projects_built = result == BuildModifiedProjectsResult.NONE_BUILT should_build_canary = no_projects_built and infra_changed if should_build_canary and not build_canary_project(): return 1 return 0 if __name__ == '__main__': sys.exit(main())
true
true
f7179a9aff5fcbff9e7d9219b960c35806a5e4f8
2,214
py
Python
generate_embeddings.py
yangfengKAUST/cnn-text-classification-tf
5f552df9887e57a4bc5638b3d36d7393254d2644
[ "Apache-2.0" ]
null
null
null
generate_embeddings.py
yangfengKAUST/cnn-text-classification-tf
5f552df9887e57a4bc5638b3d36d7393254d2644
[ "Apache-2.0" ]
null
null
null
generate_embeddings.py
yangfengKAUST/cnn-text-classification-tf
5f552df9887e57a4bc5638b3d36d7393254d2644
[ "Apache-2.0" ]
null
null
null
import numpy as np import pickle import argparse import re """ Convert pre-trained Glove embeddings into npy file Run using: python3 generate_embeddings.py -d data/glove.6B.300d.txt --npy_output data/embeddings.npy --dict_output data/vocab.pckl --dict_whitelist data/polaritydata.vocab """ def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('--dataset', '-d', type=str, required=True) parser.add_argument('--npy_output', type=str, required=True) parser.add_argument('--dict_output', type=str, required=True) parser.add_argument('--dict_whitelist', type=str, required=True) parser.add_argument('--dump_frequency', type=int, default=10000) return parser.parse_args() def main(): args = parse_args() # reserve 0 for unknown words data = { '': 0 } embeddings = [ np.zeros((300), dtype=np.float32) ] float_re = re.compile(' [-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?') with open(args.dict_whitelist) as wfile: whitelist = [line.strip() for line in wfile] print("Building vocabulary ...") with open(args.dataset) as ofile, \ open(args.dict_output, 'wb') as dfile, \ open(args.npy_output, 'wb') as nfile: idx = 1 for line in ofile: pos = next(re.finditer(float_re, line)).start() word, vector = line[:pos], line[pos + 1:].split() if word not in whitelist: continue if word in data: print('Possible duplicate at {} in {}'.format(idx, line)) continue embedding = np.fromiter([float(d) for d in vector], np.float32) if embedding.shape != (300,): print('Shape is {}'.format(embedding.shape)) print(line) embeddings.append(embedding) data[word] = idx idx += 1 if not idx % args.dump_frequency: np.save(nfile, np.array(embeddings)) embeddings.clear() np.save(nfile, np.array(embeddings)) pickle.dump(data, dfile) print("Vocabulary saved, size is {} words".format(idx)) if __name__ == '__main__': main()
29.131579
160
0.590786
import numpy as np import pickle import argparse import re def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('--dataset', '-d', type=str, required=True) parser.add_argument('--npy_output', type=str, required=True) parser.add_argument('--dict_output', type=str, required=True) parser.add_argument('--dict_whitelist', type=str, required=True) parser.add_argument('--dump_frequency', type=int, default=10000) return parser.parse_args() def main(): args = parse_args() data = { '': 0 } embeddings = [ np.zeros((300), dtype=np.float32) ] float_re = re.compile(' [-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?') with open(args.dict_whitelist) as wfile: whitelist = [line.strip() for line in wfile] print("Building vocabulary ...") with open(args.dataset) as ofile, \ open(args.dict_output, 'wb') as dfile, \ open(args.npy_output, 'wb') as nfile: idx = 1 for line in ofile: pos = next(re.finditer(float_re, line)).start() word, vector = line[:pos], line[pos + 1:].split() if word not in whitelist: continue if word in data: print('Possible duplicate at {} in {}'.format(idx, line)) continue embedding = np.fromiter([float(d) for d in vector], np.float32) if embedding.shape != (300,): print('Shape is {}'.format(embedding.shape)) print(line) embeddings.append(embedding) data[word] = idx idx += 1 if not idx % args.dump_frequency: np.save(nfile, np.array(embeddings)) embeddings.clear() np.save(nfile, np.array(embeddings)) pickle.dump(data, dfile) print("Vocabulary saved, size is {} words".format(idx)) if __name__ == '__main__': main()
true
true
f7179ad7cc757ce856fb3920524110f510a8a74a
2,256
py
Python
SWIM-Executables/Windows/pyinstaller-2.0 for windows/PyInstaller/hooks/django-import-finder.py
alexsigaras/SWIM
1a35df8acb26bdcb307a1b8f60e9feba68ed1715
[ "MIT" ]
47
2020-03-08T08:43:28.000Z
2022-03-18T18:51:55.000Z
SWIM-Executables/Windows/pyinstaller-2.0 for windows/PyInstaller/hooks/django-import-finder.py
alexsigaras/SWIM
1a35df8acb26bdcb307a1b8f60e9feba68ed1715
[ "MIT" ]
null
null
null
SWIM-Executables/Windows/pyinstaller-2.0 for windows/PyInstaller/hooks/django-import-finder.py
alexsigaras/SWIM
1a35df8acb26bdcb307a1b8f60e9feba68ed1715
[ "MIT" ]
16
2020-03-08T08:43:30.000Z
2022-01-10T22:05:57.000Z
# Copyright (C) 2009, Lorenzo Berni # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA import os import PyInstaller.compat as compat from hookutils import logger if not compat.getenv("DJANGO_SETTINGS_MODULE"): compat.setenv("DJANGO_SETTINGS_MODULE", "settings") from django.conf import settings hiddenimports = (list(settings.AUTHENTICATION_BACKENDS) + [settings.DEFAULT_FILE_STORAGE] + list(settings.FILE_UPLOAD_HANDLERS) + list(settings.INSTALLED_APPS) + list(settings.MIDDLEWARE_CLASSES) + list(settings.TEMPLATE_CONTEXT_PROCESSORS) + list(settings.TEMPLATE_LOADERS) + [settings.ROOT_URLCONF]) def find_url_callbacks(urls_module): urlpatterns = urls_module.urlpatterns hid_list = [urls_module.__name__] for pattern in urlpatterns: if isinstance(pattern, RegexURLPattern): hid_list.append(pattern.callback.__module__) elif isinstance(pattern, RegexURLResolver): hid_list += find_url_callbacks(pattern.urlconf_module) return hid_list from django.core.urlresolvers import RegexURLPattern, RegexURLResolver base_module_name = ".".join(compat.getenv("DJANGO_SETTINGS_MODULE", "settings").split(".")[:-1]) if base_module_name: base_module = __import__(base_module_name, {}, {}, ["urls"]) urls = base_module.urls else: import urls hiddenimports += find_url_callbacks(urls) logger.debug('%r', sorted(set(hiddenimports)))
38.237288
96
0.724734
import os import PyInstaller.compat as compat from hookutils import logger if not compat.getenv("DJANGO_SETTINGS_MODULE"): compat.setenv("DJANGO_SETTINGS_MODULE", "settings") from django.conf import settings hiddenimports = (list(settings.AUTHENTICATION_BACKENDS) + [settings.DEFAULT_FILE_STORAGE] + list(settings.FILE_UPLOAD_HANDLERS) + list(settings.INSTALLED_APPS) + list(settings.MIDDLEWARE_CLASSES) + list(settings.TEMPLATE_CONTEXT_PROCESSORS) + list(settings.TEMPLATE_LOADERS) + [settings.ROOT_URLCONF]) def find_url_callbacks(urls_module): urlpatterns = urls_module.urlpatterns hid_list = [urls_module.__name__] for pattern in urlpatterns: if isinstance(pattern, RegexURLPattern): hid_list.append(pattern.callback.__module__) elif isinstance(pattern, RegexURLResolver): hid_list += find_url_callbacks(pattern.urlconf_module) return hid_list from django.core.urlresolvers import RegexURLPattern, RegexURLResolver base_module_name = ".".join(compat.getenv("DJANGO_SETTINGS_MODULE", "settings").split(".")[:-1]) if base_module_name: base_module = __import__(base_module_name, {}, {}, ["urls"]) urls = base_module.urls else: import urls hiddenimports += find_url_callbacks(urls) logger.debug('%r', sorted(set(hiddenimports)))
true
true
f7179b68d16205b5ace838040622bc3f19f99fa8
10,342
py
Python
src/.history/Test/HiwinRT605_test_20190619131630.py
SamKaiYang/2019_Hiwin_Shaking
d599f8c87dc4da89eae266990d12eb3a8b0f3e16
[ "MIT" ]
null
null
null
src/.history/Test/HiwinRT605_test_20190619131630.py
SamKaiYang/2019_Hiwin_Shaking
d599f8c87dc4da89eae266990d12eb3a8b0f3e16
[ "MIT" ]
null
null
null
src/.history/Test/HiwinRT605_test_20190619131630.py
SamKaiYang/2019_Hiwin_Shaking
d599f8c87dc4da89eae266990d12eb3a8b0f3e16
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # license removed for brevity #策略 機械手臂 四點來回跑 import rospy import os import numpy as np from std_msgs.msg import String from ROS_Socket.srv import * from ROS_Socket.msg import * import math import enum import Hiwin_RT605_ROS as ArmTask pos_feedback_times = 0 mode_feedback_times = 0 msg_feedback = 1 Arm_state_flag = 0 Strategy_flag = 0 arm_move_times = 1 ##-----------server feedback arm state---------- def Arm_state(req): global CurrentMissionType,Strategy_flag,Arm_state_flag Arm_state_flag = int('%s'%req.Arm_state) if Arm_state_flag == 1: #表示手臂忙碌 Strategy_flag = 0 return(1) if Arm_state_flag == 0: #表示手臂準備 Strategy_flag = 1 return(0) if Arm_state_flag == 6: #表示程式中斷 Strategy_flag= 6 return(6) def strategy_server(): #rospy.init_node(NAME) s = rospy.Service('arm_state',arm_state, Arm_state) ##server arm state #rospy.spin() ## spin one ##-----------switch define------------## class switch(object): def __init__(self, value): self.value = value self.fall = False def __iter__(self): """Return the match method once, then stop""" yield self.match raise StopIteration def match(self, *args): """Indicate whether or not to enter a case suite""" if self.fall or not args: return True elif self.value in args: # changed for v1.5, see below self.fall = True return True else: return False ##------------class------- class point(): def __init__(self,x,y,z,pitch,roll,yaw): self.x = x self.y = y self.z = z self.pitch = pitch self.roll = roll self.yaw = yaw ##-------------------------strategy--------------------- ##-----Mission 參數 GetInfoFlag = False ExecuteFlag = False GetKeyFlag = False MotionSerialKey = [] MissionType_Flag = 0 MotionStep = 0 ##-----手臂動作位置資訊 angle_SubCue = 0 LinePtpFlag = False MoveFlag = False PushBallHeight = 6 ObjAboveHeight = 10 SpeedValue = 10 MissionEndFlag = False CurrentMissionType = 0 ##---------------Enum---------------## class ArmMotionCommand(enum.IntEnum): Arm_Stop = 0 Arm_MoveToTargetUpside = 1 Arm_MoveFowardDown = 2 Arm_MoveVision = 3 Arm_PushBall = 4 Arm_LineUp = 5 Arm_LineDown = 6 Arm_Angle = 7 Arm_StopPush = 8 class MissionType(enum.IntEnum): Get_Img = 0 PushBall = 1 Pushback = 2 Mission_End = 3 ##-----------switch define------------## class pos(): def __init__(self, x, y, z, pitch, roll, yaw): self.x = 0 self.y = 36.8 self.z = 11.35 self.pitch = -90 self.roll = 0 self.yaw = 0 class Target_pos(): def __init__(self, x, y, z, pitch, roll, yaw): self.x = 0 self.y = 36.8 self.z = 11.35 self.pitch = -90 self.roll = 0 self.yaw = 0 class TargetPush_pos(): def __init__(self, x, y, z, pitch, roll, yaw): self.x = 0 self.y = 36.8 self.z = 11.35 self.pitch = -90 self.roll = 0 self.yaw = 0 class Item(): def __init__(self,x,y,label): self.x = x self.y = y self.label = label def Mission_Trigger(): if GetInfoFlag == True and GetKeyFlag == False and ExecuteFlag == False: GetInfo_Mission() if GetInfoFlag == False and GetKeyFlag == True and ExecuteFlag == False: GetKey_Mission() if GetInfoFlag == False and GetKeyFlag == False and ExecuteFlag == True: Execute_Mission() def GetInfo_Mission(): global GetInfoFlag,GetKeyFlag,ExecuteFlag #Billiards_Calculation() GetInfoFlag = False GetKeyFlag = True ExecuteFlag = False def GetKey_Mission(): global GetInfoFlag,GetKeyFlag,ExecuteFlag,MotionKey,MotionSerialKey Mission = Get_MissionType() MissionItem(Mission) MotionSerialKey = MotionKey GetInfoFlag = False GetKeyFlag = False ExecuteFlag = True def Get_MissionType(): global MissionType_Flag,CurrentMissionType for case in switch(MissionType_Flag): #傳送指令給socket選擇手臂動作 if case(0): Type = MissionType.PushBall MissionType_Flag +=1 break if case(1): Type = MissionType.Pushback MissionType_Flag -=1 break CurrentMissionType = Type return Type def MissionItem(ItemNo): global MotionKey Key_PushBallCommand = [\ ArmMotionCommand.Arm_MoveToTargetUpside,\ ArmMotionCommand.Arm_LineDown,\ ArmMotionCommand.Arm_PushBall,\ ArmMotionCommand.Arm_LineUp,\ ArmMotionCommand.Arm_Stop,\ ] Key_PushBackCommand = [\ ArmMotionCommand.Arm_MoveVision,\ ArmMotionCommand.Arm_Stop,\ ArmMotionCommand.Arm_StopPush,\ ] for case in switch(ItemNo): #傳送指令給socket選擇手臂動作 if case(MissionType.PushBall): MotionKey = Key_PushBallCommand break if case(MissionType.Pushback): MotionKey = Key_PushBackCommand break return MotionKey def Execute_Mission(): global GetInfoFlag,GetKeyFlag,ExecuteFlag,MotionKey,MotionStep,MotionSerialKey,MissionEndFlag,CurrentMissionType,Strategy_flag,Arm_state_flag # print("strategy :" ,Strategy_flag) # print("state :" ,Arm_state_flag) # if Arm_state_flag == 0 and Strategy_flag == 1: print(11111) # Strategy_flag = 0 if ArmTask.state_flag.Arm_feedback == 0 and ArmTask.state_flag.Strategy_feedback == 1: print(11111) ArmTask.state_flag.Strategy_feedback = 0 if MotionKey[MotionStep] == ArmMotionCommand.Arm_Stop: if MissionEndFlag == True: CurrentMissionType = MissionType.Mission_End GetInfoFlag = False GetKeyFlag = False ExecuteFlag = False print("Mission_End") elif CurrentMissionType == MissionType.PushBall: GetInfoFlag = False GetKeyFlag = True ExecuteFlag = False MotionStep = 0 print("PushBall") else: GetInfoFlag = True GetKeyFlag = False ExecuteFlag = False MotionStep = 0 else: MotionItem(MotionSerialKey[MotionStep]) MotionStep += 1 def MotionItem(ItemNo): global angle_SubCue,SpeedValue,PushFlag,LinePtpFlag,MissionEndFlag SpeedValue = 5 for case in switch(ItemNo): #傳送指令給socket選擇手臂動作 if case(ArmMotionCommand.Arm_Stop): MoveFlag = False print("Arm_Stop") break if case(ArmMotionCommand.Arm_StopPush): MoveFlag = False PushFlag = True #重新掃描物件 print("Arm_StopPush") break if case(ArmMotionCommand.Arm_MoveToTargetUpside): pos.x = 10 pos.y = 36.8 pos.z = 11.35 pos.pitch = -90 pos.roll = 0 pos.yaw = 10 MoveFlag = True LinePtpFlag = False SpeedValue = 10 print("Arm_MoveToTargetUpside") break if case(ArmMotionCommand.Arm_LineUp): pos.z = ObjAboveHeight MoveFlag = True LinePtpFlag = True SpeedValue = 5 print("Arm_LineUp") break if case(ArmMotionCommand.Arm_LineDown): pos.z = PushBallHeight MoveFlag = True LinePtpFlag = True SpeedValue = 5 print("Arm_LineDown") break if case(ArmMotionCommand.Arm_PushBall): pos.x = -10 pos.y = 36.8 pos.z = 11.35 pos.pitch = -90 pos.roll = 0 pos.yaw = -10 SpeedValue = 10 ##待測試up MoveFlag = True LinePtpFlag = False print("Arm_PushBall") break if case(ArmMotionCommand.Arm_MoveVision): pos.x = 0 pos.y = 36.8 pos.z = 11.35 pos.pitch = -90 pos.roll = 0 pos.yaw = 0 SpeedValue = 10 MoveFlag = True LinePtpFlag = False ##任務結束旗標 MissionEndFlag = True print("Arm_MoveVision") break if case(ArmMotionCommand.Arm_MoveFowardDown): pos.x = 0 pos.y = 36.8 pos.z = 11.35 pos.pitch = -90 pos.roll = 0 pos.yaw = 0 MoveFlag = True LinePtpFlag = False print("Arm_MoveFowardDown") break if case(): # default, could also just omit condition or 'if True' print ("something else!") # No need to break here, it'll stop anyway if MoveFlag == True: if LinePtpFlag == False: print('x: ',pos.x,' y: ',pos.y,' z: ',pos.z,' pitch: ',pos.pitch,' roll: ',pos.roll,' yaw: ',pos.yaw) #strategy_client_Arm_Mode(0,1,0,30,2)#action,ra,grip,vel,both ArmTask.strategy_client_Arm_Mode(2,1,0,SpeedValue,2)#action,ra,grip,vel,both ArmTask.strategy_client_pos_move(pos.x,pos.y,pos.z,pos.pitch,pos.roll,pos.yaw) elif LinePtpFlag == True: #strategy_client_Arm_Mode(0,1,0,40,2)#action,ra,grip,vel,both print('x: ',pos.x,' y: ',pos.y,' z: ',pos.z,' pitch: ',pos.pitch,' roll: ',pos.roll,' yaw: ',pos.yaw) ArmTask.strategy_client_Arm_Mode(3,1,0,SpeedValue,2)#action,ra,grip,vel,both ArmTask.strategy_client_pos_move(pos.x,pos.y,pos.z,pos.pitch,pos.roll,pos.yaw) #action: ptp line #ra : abs rel #grip 夾爪 #vel speed #both : Ctrl_Mode ##-------------strategy end ------------ def myhook(): print ("shutdown time!") if __name__ == '__main__': argv = rospy.myargv() rospy.init_node('strategy', anonymous=True) GetInfoFlag = True #Test no data #strategy_server() ArmTask.strategy_client_Arm_Mode(0,1,0,20,2)#action,ra,grip,vel,both while 1: Mission_Trigger() if CurrentMissionType == MissionType.Mission_End: ArmTask.rospy.on_shutdown(myhook) ArmTask.rospy.spin() rospy.spin()
30.871642
145
0.579288
import rospy import os import numpy as np from std_msgs.msg import String from ROS_Socket.srv import * from ROS_Socket.msg import * import math import enum import Hiwin_RT605_ROS as ArmTask pos_feedback_times = 0 mode_feedback_times = 0 msg_feedback = 1 Arm_state_flag = 0 Strategy_flag = 0 arm_move_times = 1 ype,Strategy_flag,Arm_state_flag Arm_state_flag = int('%s'%req.Arm_state) if Arm_state_flag == 1: Strategy_flag = 0 return(1) if Arm_state_flag == 0: Strategy_flag = 1 return(0) if Arm_state_flag == 6: Strategy_flag= 6 return(6) def strategy_server(): s = rospy.Service('arm_state',arm_state, Arm_state) = value self.fall = False def __iter__(self): yield self.match raise StopIteration def match(self, *args): if self.fall or not args: return True elif self.value in args: self.fall = True return True else: return False _init__(self,x,y,z,pitch,roll,yaw): self.x = x self.y = y self.z = z self.pitch = pitch self.roll = roll self.yaw = yaw alKey = [] MissionType_Flag = 0 MotionStep = 0 = 0 LinePtpFlag = False MoveFlag = False PushBallHeight = 6 ObjAboveHeight = 10 SpeedValue = 10 MissionEndFlag = False CurrentMissionType = 0 Arm_Stop = 0 Arm_MoveToTargetUpside = 1 Arm_MoveFowardDown = 2 Arm_MoveVision = 3 Arm_PushBall = 4 Arm_LineUp = 5 Arm_LineDown = 6 Arm_Angle = 7 Arm_StopPush = 8 class MissionType(enum.IntEnum): Get_Img = 0 PushBall = 1 Pushback = 2 Mission_End = 3 z, pitch, roll, yaw): self.x = 0 self.y = 36.8 self.z = 11.35 self.pitch = -90 self.roll = 0 self.yaw = 0 class Target_pos(): def __init__(self, x, y, z, pitch, roll, yaw): self.x = 0 self.y = 36.8 self.z = 11.35 self.pitch = -90 self.roll = 0 self.yaw = 0 class TargetPush_pos(): def __init__(self, x, y, z, pitch, roll, yaw): self.x = 0 self.y = 36.8 self.z = 11.35 self.pitch = -90 self.roll = 0 self.yaw = 0 class Item(): def __init__(self,x,y,label): self.x = x self.y = y self.label = label def Mission_Trigger(): if GetInfoFlag == True and GetKeyFlag == False and ExecuteFlag == False: GetInfo_Mission() if GetInfoFlag == False and GetKeyFlag == True and ExecuteFlag == False: GetKey_Mission() if GetInfoFlag == False and GetKeyFlag == False and ExecuteFlag == True: Execute_Mission() def GetInfo_Mission(): global GetInfoFlag,GetKeyFlag,ExecuteFlag GetInfoFlag = False GetKeyFlag = True ExecuteFlag = False def GetKey_Mission(): global GetInfoFlag,GetKeyFlag,ExecuteFlag,MotionKey,MotionSerialKey Mission = Get_MissionType() MissionItem(Mission) MotionSerialKey = MotionKey GetInfoFlag = False GetKeyFlag = False ExecuteFlag = True def Get_MissionType(): global MissionType_Flag,CurrentMissionType for case in switch(MissionType_Flag): if case(0): Type = MissionType.PushBall MissionType_Flag +=1 break if case(1): Type = MissionType.Pushback MissionType_Flag -=1 break CurrentMissionType = Type return Type def MissionItem(ItemNo): global MotionKey Key_PushBallCommand = [\ ArmMotionCommand.Arm_MoveToTargetUpside,\ ArmMotionCommand.Arm_LineDown,\ ArmMotionCommand.Arm_PushBall,\ ArmMotionCommand.Arm_LineUp,\ ArmMotionCommand.Arm_Stop,\ ] Key_PushBackCommand = [\ ArmMotionCommand.Arm_MoveVision,\ ArmMotionCommand.Arm_Stop,\ ArmMotionCommand.Arm_StopPush,\ ] for case in switch(ItemNo): if case(MissionType.PushBall): MotionKey = Key_PushBallCommand break if case(MissionType.Pushback): MotionKey = Key_PushBackCommand break return MotionKey def Execute_Mission(): global GetInfoFlag,GetKeyFlag,ExecuteFlag,MotionKey,MotionStep,MotionSerialKey,MissionEndFlag,CurrentMissionType,Strategy_flag,Arm_state_flag print(11111) if ArmTask.state_flag.Arm_feedback == 0 and ArmTask.state_flag.Strategy_feedback == 1: print(11111) ArmTask.state_flag.Strategy_feedback = 0 if MotionKey[MotionStep] == ArmMotionCommand.Arm_Stop: if MissionEndFlag == True: CurrentMissionType = MissionType.Mission_End GetInfoFlag = False GetKeyFlag = False ExecuteFlag = False print("Mission_End") elif CurrentMissionType == MissionType.PushBall: GetInfoFlag = False GetKeyFlag = True ExecuteFlag = False MotionStep = 0 print("PushBall") else: GetInfoFlag = True GetKeyFlag = False ExecuteFlag = False MotionStep = 0 else: MotionItem(MotionSerialKey[MotionStep]) MotionStep += 1 def MotionItem(ItemNo): global angle_SubCue,SpeedValue,PushFlag,LinePtpFlag,MissionEndFlag SpeedValue = 5 for case in switch(ItemNo): if case(ArmMotionCommand.Arm_Stop): MoveFlag = False print("Arm_Stop") break if case(ArmMotionCommand.Arm_StopPush): MoveFlag = False PushFlag = True print("Arm_StopPush") break if case(ArmMotionCommand.Arm_MoveToTargetUpside): pos.x = 10 pos.y = 36.8 pos.z = 11.35 pos.pitch = -90 pos.roll = 0 pos.yaw = 10 MoveFlag = True LinePtpFlag = False SpeedValue = 10 print("Arm_MoveToTargetUpside") break if case(ArmMotionCommand.Arm_LineUp): pos.z = ObjAboveHeight MoveFlag = True LinePtpFlag = True SpeedValue = 5 print("Arm_LineUp") break if case(ArmMotionCommand.Arm_LineDown): pos.z = PushBallHeight MoveFlag = True LinePtpFlag = True SpeedValue = 5 print("Arm_LineDown") break if case(ArmMotionCommand.Arm_PushBall): pos.x = -10 pos.y = 36.8 pos.z = 11.35 pos.pitch = -90 pos.roll = 0 pos.yaw = -10 SpeedValue = 10 MoveFlag = True LinePtpFlag = False print("Arm_PushBall") break if case(ArmMotionCommand.Arm_MoveVision): pos.x = 0 pos.y = 36.8 pos.z = 11.35 pos.pitch = -90 pos.roll = 0 pos.yaw = 0 SpeedValue = 10 MoveFlag = True LinePtpFlag = False MissionEndFlag = True print("Arm_MoveVision") break if case(ArmMotionCommand.Arm_MoveFowardDown): pos.x = 0 pos.y = 36.8 pos.z = 11.35 pos.pitch = -90 pos.roll = 0 pos.yaw = 0 MoveFlag = True LinePtpFlag = False print("Arm_MoveFowardDown") break if case(): print ("something else!") if MoveFlag == True: if LinePtpFlag == False: print('x: ',pos.x,' y: ',pos.y,' z: ',pos.z,' pitch: ',pos.pitch,' roll: ',pos.roll,' yaw: ',pos.yaw) #strategy_client_Arm_Mode(0,1,0,30,2)#action,ra,grip,vel,both ArmTask.strategy_client_Arm_Mode(2,1,0,SpeedValue,2)#action,ra,grip,vel,both ArmTask.strategy_client_pos_move(pos.x,pos.y,pos.z,pos.pitch,pos.roll,pos.yaw) elif LinePtpFlag == True: #strategy_client_Arm_Mode(0,1,0,40,2)#action,ra,grip,vel,both print('x: ',pos.x,' y: ',pos.y,' z: ',pos.z,' pitch: ',pos.pitch,' roll: ',pos.roll,' yaw: ',pos.yaw) ArmTask.strategy_client_Arm_Mode(3,1,0,SpeedValue,2)#action,ra,grip,vel,both ArmTask.strategy_client_pos_move(pos.x,pos.y,pos.z,pos.pitch,pos.roll,pos.yaw) #action: ptp line #ra : abs rel #grip 夾爪 #vel speed #both : Ctrl_Mode ##-------------strategy end ------------ def myhook(): print ("shutdown time!") if __name__ == '__main__': argv = rospy.myargv() rospy.init_node('strategy', anonymous=True) GetInfoFlag = True #Test no data #strategy_server() ArmTask.strategy_client_Arm_Mode(0,1,0,20,2)#action,ra,grip,vel,both while 1: Mission_Trigger() if CurrentMissionType == MissionType.Mission_End: ArmTask.rospy.on_shutdown(myhook) ArmTask.rospy.spin() rospy.spin()
true
true
f7179b7c95704c49d4aaa9e728e5e82df649b8d6
596
py
Python
configs/revbifpn/fcn_s1_512x1024_120k_cityscapes.py
gupta-abhay/mmsegmentation
03e80db237d12b4d049fe65c6612f2bc741f8135
[ "Apache-2.0" ]
null
null
null
configs/revbifpn/fcn_s1_512x1024_120k_cityscapes.py
gupta-abhay/mmsegmentation
03e80db237d12b4d049fe65c6612f2bc741f8135
[ "Apache-2.0" ]
null
null
null
configs/revbifpn/fcn_s1_512x1024_120k_cityscapes.py
gupta-abhay/mmsegmentation
03e80db237d12b4d049fe65c6612f2bc741f8135
[ "Apache-2.0" ]
null
null
null
_base_ = [ '../_base_/models/fcn_hr18.py', '../_base_/datasets/cityscapes.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_120k.py', ] model = dict( pretrained=None, backbone=dict( type='RevBiFPN_S', arch='revbifpn_s1', strict=False, classes=None, _norm="syncbn", init_cfg=dict( type='Pretrained', ), ), decode_head=dict( in_channels=[64, 80, 160, 416], channels=sum([64, 80, 160, 416]) ), ) optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=3.0e-5)
23.84
72
0.567114
_base_ = [ '../_base_/models/fcn_hr18.py', '../_base_/datasets/cityscapes.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_120k.py', ] model = dict( pretrained=None, backbone=dict( type='RevBiFPN_S', arch='revbifpn_s1', strict=False, classes=None, _norm="syncbn", init_cfg=dict( type='Pretrained', ), ), decode_head=dict( in_channels=[64, 80, 160, 416], channels=sum([64, 80, 160, 416]) ), ) optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=3.0e-5)
true
true
f7179e36f8aee9aeb3010facd15317bf9a7987b3
1,075
py
Python
fewshot/data/compress_tiered_imagenet.py
renmengye/inc-few-shot-attractor-public
c560d5a81480cb22d903fa746ab0cfc2eb964e4c
[ "MIT" ]
122
2019-09-20T05:35:29.000Z
2022-03-22T06:30:33.000Z
fewshot/data/compress_tiered_imagenet.py
renmengye/inc-few-shot-attractor-public
c560d5a81480cb22d903fa746ab0cfc2eb964e4c
[ "MIT" ]
10
2019-11-10T10:24:06.000Z
2021-10-06T13:13:26.000Z
fewshot/data/compress_tiered_imagenet.py
renmengye/inc-few-shot-attractor-public
c560d5a81480cb22d903fa746ab0cfc2eb964e4c
[ "MIT" ]
28
2019-10-21T11:38:06.000Z
2022-01-26T16:55:28.000Z
import cv2 import numpy as np import six import sys import pickle as pkl from tqdm import tqdm def compress(path, output): with np.load(path, mmap_mode="r", encoding='latin1') as data: images = data["images"] array = [] for ii in tqdm(six.moves.xrange(images.shape[0]), desc='compress'): im = images[ii] im_str = cv2.imencode('.png', im)[1] array.append(im_str) with open(output, 'wb') as f: pkl.dump(array, f, protocol=pkl.HIGHEST_PROTOCOL) def decompress(path, output): try: with open(output, 'rb') as f: array = pkl.load(f, encoding='bytes') except: with open(output, 'rb') as f: array = pkl.load(f) images = np.zeros([len(array), 84, 84, 3], dtype=np.uint8) for ii, item in tqdm(enumerate(array), desc='decompress'): im = cv2.imdecode(item, 1) images[ii] = im np.savez(path, images=images) def main(): if sys.argv[1] == 'compress': compress(sys.argv[2], sys.argv[3]) elif sys.argv[1] == 'decompress': decompress(sys.argv[2], sys.argv[3]) if __name__ == '__main__': main()
23.888889
71
0.633488
import cv2 import numpy as np import six import sys import pickle as pkl from tqdm import tqdm def compress(path, output): with np.load(path, mmap_mode="r", encoding='latin1') as data: images = data["images"] array = [] for ii in tqdm(six.moves.xrange(images.shape[0]), desc='compress'): im = images[ii] im_str = cv2.imencode('.png', im)[1] array.append(im_str) with open(output, 'wb') as f: pkl.dump(array, f, protocol=pkl.HIGHEST_PROTOCOL) def decompress(path, output): try: with open(output, 'rb') as f: array = pkl.load(f, encoding='bytes') except: with open(output, 'rb') as f: array = pkl.load(f) images = np.zeros([len(array), 84, 84, 3], dtype=np.uint8) for ii, item in tqdm(enumerate(array), desc='decompress'): im = cv2.imdecode(item, 1) images[ii] = im np.savez(path, images=images) def main(): if sys.argv[1] == 'compress': compress(sys.argv[2], sys.argv[3]) elif sys.argv[1] == 'decompress': decompress(sys.argv[2], sys.argv[3]) if __name__ == '__main__': main()
true
true
f7179eb378b819138f77c19337426397d15ce820
10,249
py
Python
rl4net/envs/power_allocation/test_pa_rb_env.py
bupt-ipcr/RL4Net
b1b694361c688f5e0055148a0cdcb4c6253cd7bd
[ "MIT" ]
17
2020-03-19T02:51:48.000Z
2021-06-15T00:42:29.000Z
vvlab/envs/power_allocation/test_pa_rb_env.py
LampV/Reinforcement-Learning
0652b9e8c2de428d3508074c6fd640cc14f84a2c
[ "MIT" ]
13
2021-04-05T13:10:25.000Z
2022-03-12T00:51:15.000Z
rl4net/envs/power_allocation/test_pa_rb_env.py
bupt-ipcr/RL4Net
b1b694361c688f5e0055148a0cdcb4c6253cd7bd
[ "MIT" ]
12
2020-03-31T05:29:25.000Z
2022-03-08T11:54:07.000Z
from .pa_rb_env import ( PAEnv, Node ) import numpy as np from pathlib import Path log2 = np.log2 cues = { 0: Node(0.1, 0, 'cue'), 1: Node(-0.1, 0, 'cue'), } devices = { 0: { 't_device': Node(0, 0.5, 't_device'), 'r_devices': { 0: Node(0, 0.6, 'r_device') } }, 1: { 't_device': Node(0, -0.5, 't_device'), 'r_devices': { 0: Node(0, -0.6, 'r_device') } } } def equal(unit, target): tolerance = 1e-6 * np.ones_like(target) return (np.abs(unit - target) < tolerance).all() def test_init_pos(): """test position constraint""" env = PAEnv(n_level=4) def dis(node, target): return np.sqrt( (node.x - target.x) ** 2 + (node.y - target.y) ** 2 ) # test bs cues assert all( env.r_bs <= dis(usr, env.station) <= env.R_bs for usr in env.cues.values() ) # test devices for cluster in env.devices.values(): t_device, r_devices = cluster['t_device'], cluster['r_devices'] assert env.r_bs <= dis(t_device, env.station) <= ( env.R_bs - env.R_dev) assert all( env.r_dev <= dis(r_device, t_device) <= env.R_dev for r_device in r_devices.values() ) def test_jakes(): # TODO test stastic features of jakes # target_std, target_mean = 0.429, 1.253 # Rayleigh Distribution # x_len, y_len, Ns = H_set.shape # h_std = np.mean([ # H_set[x, y, :].std() # for x in range(x_len) # for y in range(y_len) # ]) # assert (h_std - target_std) / target_std < 0.1 # h_mean = np.mean([ # H_set[x, y, :].mean() # for x in range(x_len) # for y in range(y_len) # ]) # assert (h_mean - target_mean) / target_mean < 0.05 pass def test_init_path_loss(): """test distance, since lognormal is random""" env = PAEnv(n_level=4, n_pair=2, m_cue=2) env.cues = cues env.devices = devices env.init_path_loss() distance_matrix = env.distance_matrix target_dis = np.array( [ [0.1, 1.1, np.sqrt(0.26), np.sqrt(0.26), 0.5], [1.1, 0.1, np.sqrt(0.26), np.sqrt(0.26), 0.5], [0.6, 0.6, 0.1, 0.1, 0.503], [np.sqrt(0.37), np.sqrt(0.37), 0.503, 0.2, 0.1], [np.sqrt(0.37), np.sqrt(0.37), 0.2, 0.503, 0.1], ] ) assert equal(distance_matrix, target_dis) def test_get_recv_powers(): """test get_recv_powers""" env = PAEnv(n_level=4, n_pair=2, m_cue=1) power = np.array([ [0.01, 0], [0, 0.01], [0.1, 0], [0, 0.1], ]) emit_powers = np.tile(np.expand_dims(power, axis=1), (1, env.n_channel, 1)) fading = np.array([ [1.1e-2, 1.2e-2, 1.3e-2, 1.4e-2], [2.1e-2, 2.2e-2, 2.3e-2, 2.4e-2], [3.1e-2, 3.2e-2, 3.3e-2, 3.4e-2], [4.1e-2, 4.2e-2, 4.3e-2, 4.4e-2], ]) recv_powers = env.get_recv_powers(emit_powers, fading) target_recv_powers = np.array([ [[1.1e-4, 0], [1.2e-4, 0], [1.3e-4, 0], [1.4e-4, 0]], [[0, 2.1e-4], [0, 2.2e-4], [0, 2.3e-4], [0, 2.4e-4]], [[3.1e-3, 0], [3.2e-3, 0], [3.3e-3, 0], [3.4e-3, 0]], [[0, 4.1e-3], [0, 4.2e-3], [0, 4.3e-3], [0, 4.4e-3]], ]) assert equal(recv_powers, target_recv_powers) def test_get_rates(): """test get_rates""" env = PAEnv(n_level=4, n_pair=2, m_cue=1) recv_powers = np.array([ [[1.1e-4, 0], [1.2e-4, 0], [1.3e-4, 0], [1.4e-4, 0]], [[0, 2.1e-4], [0, 2.2e-4], [0, 2.3e-4], [0, 2.4e-4]], [[3.1e-3, 0], [3.2e-3, 0], [3.3e-3, 0], [3.4e-3, 0]], [[0, 4.1e-3], [0, 4.2e-3], [0, 4.3e-3], [0, 4.4e-3]], ]) rates = env.get_rates(recv_powers) _rate = np.array([ log2(1+1.1/31), log2(1+2.2/42), log2(1+33/1.3), log2(1+44/2.4) ]) target_rates = (_rate * np.ones((env.n_channel, env.n_channel))).T assert equal(rates, target_rates) def test_get_indices(): """test get_indices""" env = PAEnv(n_level=4, n_pair=2, m_cue=1, sorter="recv_power", m_state=2) power = np.array([ [0.01, 0], [0, 0.01], [0.1, 0], [0, 0.1], ]) emit_powers = np.tile(np.expand_dims(power, axis=1), (1, env.n_channel, 1)) fading = np.array([ [1.1e-2, 1.2e-2, 1.3e-2, 1.4e-2], [2.1e-2, 2.2e-2, 2.3e-2, 2.4e-2], [3.1e-2, 3.2e-2, 3.3e-2, 3.4e-2], [4.1e-2, 4.2e-2, 4.3e-2, 4.4e-2], ]) recv_powers = env.get_recv_powers(emit_powers, fading) rates = env.get_rates(recv_powers) metrics = emit_powers, recv_powers, rates, fading # rx_indice don't need test tx_indice, rx_indice = env.get_indices(*metrics) target_tx_indice = np.array([ [3, 3, 3, 2], [0, 1, 2, 3] ]) assert equal(tx_indice, target_tx_indice) def test_get_rewards(): env = PAEnv(n_level=4, n_pair=2, m_cue=1, sorter="recv_power", m_state=2) power = np.array([ [0.01, 0], [0, 0.01], [0.1, 0], [0, 0.1], ]) emit_powers = np.tile(np.expand_dims(power, axis=1), (1, env.n_channel, 1)) fading = np.array([ [1.1e-2, 1.2e-2, 1.3e-2, 1.4e-2], [2.1e-2, 2.2e-2, 2.3e-2, 2.4e-2], [3.1e-2, 3.2e-2, 3.3e-2, 3.4e-2], [4.1e-2, 4.2e-2, 4.3e-2, 4.4e-2], ]) recv_powers = env.get_recv_powers(emit_powers, fading) rates = env.get_rates(recv_powers) metrics = emit_powers, recv_powers, rates, fading indices = env.get_indices(*metrics) rewards = env.get_rewards(rates, indices) target_rewards = np.array([ log2(1+1.1/31) + log2(1+44/2.4), log2(1+2.2/42) + log2(1+44/2.4), log2(1+33/1.3) + log2(1+44/2.4), log2(1+44/2.4) + log2(1+33/1.3), ])[:2] assert equal(rewards, target_rewards) def test_get_states(): # test m_state env = PAEnv(n_level=4, n_pair=2, m_cue=1, m_state=8, metrics=['emit_power', 'recv_power', 'rate'], sorter='recv_power') assert env.m_state == 4 env = PAEnv(n_level=4, n_pair=2, m_cue=1, m_state=2, metrics=['emit_power', 'recv_power', 'rate'], sorter='recv_power') power = np.array([ [0.01, 0], [0, 0.01], [0.1, 0], [0, 0.1], ]) emit_powers = np.tile(np.expand_dims(power, axis=1), (1, env.n_channel, 1)) fading = np.array([ [1.1e-2, 1.2e-2, 1.3e-2, 1.4e-2], [2.1e-2, 2.2e-2, 2.3e-2, 2.4e-2], [3.1e-2, 3.2e-2, 3.3e-2, 3.4e-2], [4.1e-2, 4.2e-2, 4.3e-2, 4.4e-2], ]) recv_powers = env.get_recv_powers(emit_powers, fading) rates = env.get_rates(recv_powers) metrics = emit_powers, recv_powers, rates, fading indices = env.get_indices(*metrics) states = env.get_states(*metrics, indices=indices) _recv = np.array([ [[1.1e-4, 0], [1.2e-4, 0], [1.3e-4, 0], [1.4e-4, 0]], [[0, 2.1e-4], [0, 2.2e-4], [0, 2.3e-4], [0, 2.4e-4]], [[3.1e-3, 0], [3.2e-3, 0], [3.3e-3, 0], [3.4e-3, 0]], [[0, 4.1e-3], [0, 4.2e-3], [0, 4.3e-3], [0, 4.4e-3]], ]) _rate = np.array([ log2(1+1.1/31), log2(1+2.2/42), log2(1+33/1.3), log2(1+44/2.4) ]) target_states = np.array([ np.concatenate([power[3],power[0],_recv[3][0],_recv[0][0],[_rate[3], _rate[0]]]), np.concatenate([power[3],power[1],_recv[3][1],_recv[1][1],[_rate[3], _rate[1]]]), np.concatenate([power[3],power[2],_recv[3][2],_recv[2][2],[_rate[3], _rate[2]]]), np.concatenate([power[2],power[3],_recv[2][3],_recv[3][3],[_rate[2], _rate[3]]]), ])[:2] assert equal(states, target_states) def test_sorter(): # now only recv_power can be sorter pass def test_seed(): env = PAEnv(n_level=4, m_cue=1, seed=123) # this is func in PAEnv to random pos def random_point(min_r, radius, ox=0, oy=0): theta = np.random.random() * 2 * np.pi r = np.random.uniform(min_r, radius**2) x, y = np.cos(theta) * np.sqrt(r), np.sin(theta) * np.sqrt(r) return ox + x, oy + y np.random.seed(123) target_x, target_y = random_point(env.r_bs, env.R_bs) usr = env.cues[0] assert all((target_x == usr.x, target_y == usr.y)) def test_action(): env = PAEnv(n_level=10, seed=799345) n_actions = env.n_actions n_channel, n_pair = env.n_channel, env.n_pair # normal env.reset() np.random.seed(799345) action = np.random.randint(0, n_actions, (n_channel, )) s_, r, d, i = env.step(action, unit='dBm') assert i['rate'] == 3.4741923099965257 # only D2D actions is enough env.reset() np.random.seed(799345) action = np.random.randint(0, n_actions, (n_pair, )) s_, r, d, i = env.step(action, unit='dBm') assert i['rate'] == 3.4741923099965257 # other action dim raises error env.reset() np.random.seed(799345) action = np.random.randint(0, n_actions, (n_pair - 1, )) try: s_, r, d, i = env.step(action, unit='dBm') except ValueError as e: msg = f"length of action should be n_channel({env.n_channel})" \ f" or n_pair({n_pair}), but is {len(action)}" assert e.args[0] == msg env.reset() np.random.seed(799345) action = np.random.randint(0, n_actions, (n_channel, )) s_, r, d, i = env.step(action, unit='mW') assert i['rate'] == 3.4928823957853856 # TODO add test of continuous action def test_step(): env = PAEnv(n_level=10) n_actions, n_states = env.n_actions, env.n_states assert n_actions == 40 assert n_states == 304 env.reset() action = env.sample() env.step(action, unit='dBm') # action = env.sample() action = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0]) env.step(action, unit='mW') action = env.sample() try: env.step(action, unit='xx') except ValueError as e: msg = f"unit should in ['dBm', 'mW'], but is xx" assert e.args[0] == msg fig: Path() = env.render() if fig.exists(): fig.unlink() if __name__ == '__main__': test_action()
30.502976
89
0.530296
from .pa_rb_env import ( PAEnv, Node ) import numpy as np from pathlib import Path log2 = np.log2 cues = { 0: Node(0.1, 0, 'cue'), 1: Node(-0.1, 0, 'cue'), } devices = { 0: { 't_device': Node(0, 0.5, 't_device'), 'r_devices': { 0: Node(0, 0.6, 'r_device') } }, 1: { 't_device': Node(0, -0.5, 't_device'), 'r_devices': { 0: Node(0, -0.6, 'r_device') } } } def equal(unit, target): tolerance = 1e-6 * np.ones_like(target) return (np.abs(unit - target) < tolerance).all() def test_init_pos(): env = PAEnv(n_level=4) def dis(node, target): return np.sqrt( (node.x - target.x) ** 2 + (node.y - target.y) ** 2 ) assert all( env.r_bs <= dis(usr, env.station) <= env.R_bs for usr in env.cues.values() ) for cluster in env.devices.values(): t_device, r_devices = cluster['t_device'], cluster['r_devices'] assert env.r_bs <= dis(t_device, env.station) <= ( env.R_bs - env.R_dev) assert all( env.r_dev <= dis(r_device, t_device) <= env.R_dev for r_device in r_devices.values() ) def test_jakes(): pass def test_init_path_loss(): env = PAEnv(n_level=4, n_pair=2, m_cue=2) env.cues = cues env.devices = devices env.init_path_loss() distance_matrix = env.distance_matrix target_dis = np.array( [ [0.1, 1.1, np.sqrt(0.26), np.sqrt(0.26), 0.5], [1.1, 0.1, np.sqrt(0.26), np.sqrt(0.26), 0.5], [0.6, 0.6, 0.1, 0.1, 0.503], [np.sqrt(0.37), np.sqrt(0.37), 0.503, 0.2, 0.1], [np.sqrt(0.37), np.sqrt(0.37), 0.2, 0.503, 0.1], ] ) assert equal(distance_matrix, target_dis) def test_get_recv_powers(): env = PAEnv(n_level=4, n_pair=2, m_cue=1) power = np.array([ [0.01, 0], [0, 0.01], [0.1, 0], [0, 0.1], ]) emit_powers = np.tile(np.expand_dims(power, axis=1), (1, env.n_channel, 1)) fading = np.array([ [1.1e-2, 1.2e-2, 1.3e-2, 1.4e-2], [2.1e-2, 2.2e-2, 2.3e-2, 2.4e-2], [3.1e-2, 3.2e-2, 3.3e-2, 3.4e-2], [4.1e-2, 4.2e-2, 4.3e-2, 4.4e-2], ]) recv_powers = env.get_recv_powers(emit_powers, fading) target_recv_powers = np.array([ [[1.1e-4, 0], [1.2e-4, 0], [1.3e-4, 0], [1.4e-4, 0]], [[0, 2.1e-4], [0, 2.2e-4], [0, 2.3e-4], [0, 2.4e-4]], [[3.1e-3, 0], [3.2e-3, 0], [3.3e-3, 0], [3.4e-3, 0]], [[0, 4.1e-3], [0, 4.2e-3], [0, 4.3e-3], [0, 4.4e-3]], ]) assert equal(recv_powers, target_recv_powers) def test_get_rates(): env = PAEnv(n_level=4, n_pair=2, m_cue=1) recv_powers = np.array([ [[1.1e-4, 0], [1.2e-4, 0], [1.3e-4, 0], [1.4e-4, 0]], [[0, 2.1e-4], [0, 2.2e-4], [0, 2.3e-4], [0, 2.4e-4]], [[3.1e-3, 0], [3.2e-3, 0], [3.3e-3, 0], [3.4e-3, 0]], [[0, 4.1e-3], [0, 4.2e-3], [0, 4.3e-3], [0, 4.4e-3]], ]) rates = env.get_rates(recv_powers) _rate = np.array([ log2(1+1.1/31), log2(1+2.2/42), log2(1+33/1.3), log2(1+44/2.4) ]) target_rates = (_rate * np.ones((env.n_channel, env.n_channel))).T assert equal(rates, target_rates) def test_get_indices(): env = PAEnv(n_level=4, n_pair=2, m_cue=1, sorter="recv_power", m_state=2) power = np.array([ [0.01, 0], [0, 0.01], [0.1, 0], [0, 0.1], ]) emit_powers = np.tile(np.expand_dims(power, axis=1), (1, env.n_channel, 1)) fading = np.array([ [1.1e-2, 1.2e-2, 1.3e-2, 1.4e-2], [2.1e-2, 2.2e-2, 2.3e-2, 2.4e-2], [3.1e-2, 3.2e-2, 3.3e-2, 3.4e-2], [4.1e-2, 4.2e-2, 4.3e-2, 4.4e-2], ]) recv_powers = env.get_recv_powers(emit_powers, fading) rates = env.get_rates(recv_powers) metrics = emit_powers, recv_powers, rates, fading tx_indice, rx_indice = env.get_indices(*metrics) target_tx_indice = np.array([ [3, 3, 3, 2], [0, 1, 2, 3] ]) assert equal(tx_indice, target_tx_indice) def test_get_rewards(): env = PAEnv(n_level=4, n_pair=2, m_cue=1, sorter="recv_power", m_state=2) power = np.array([ [0.01, 0], [0, 0.01], [0.1, 0], [0, 0.1], ]) emit_powers = np.tile(np.expand_dims(power, axis=1), (1, env.n_channel, 1)) fading = np.array([ [1.1e-2, 1.2e-2, 1.3e-2, 1.4e-2], [2.1e-2, 2.2e-2, 2.3e-2, 2.4e-2], [3.1e-2, 3.2e-2, 3.3e-2, 3.4e-2], [4.1e-2, 4.2e-2, 4.3e-2, 4.4e-2], ]) recv_powers = env.get_recv_powers(emit_powers, fading) rates = env.get_rates(recv_powers) metrics = emit_powers, recv_powers, rates, fading indices = env.get_indices(*metrics) rewards = env.get_rewards(rates, indices) target_rewards = np.array([ log2(1+1.1/31) + log2(1+44/2.4), log2(1+2.2/42) + log2(1+44/2.4), log2(1+33/1.3) + log2(1+44/2.4), log2(1+44/2.4) + log2(1+33/1.3), ])[:2] assert equal(rewards, target_rewards) def test_get_states(): # test m_state env = PAEnv(n_level=4, n_pair=2, m_cue=1, m_state=8, metrics=['emit_power', 'recv_power', 'rate'], sorter='recv_power') assert env.m_state == 4 env = PAEnv(n_level=4, n_pair=2, m_cue=1, m_state=2, metrics=['emit_power', 'recv_power', 'rate'], sorter='recv_power') power = np.array([ [0.01, 0], [0, 0.01], [0.1, 0], [0, 0.1], ]) emit_powers = np.tile(np.expand_dims(power, axis=1), (1, env.n_channel, 1)) fading = np.array([ [1.1e-2, 1.2e-2, 1.3e-2, 1.4e-2], [2.1e-2, 2.2e-2, 2.3e-2, 2.4e-2], [3.1e-2, 3.2e-2, 3.3e-2, 3.4e-2], [4.1e-2, 4.2e-2, 4.3e-2, 4.4e-2], ]) recv_powers = env.get_recv_powers(emit_powers, fading) rates = env.get_rates(recv_powers) metrics = emit_powers, recv_powers, rates, fading indices = env.get_indices(*metrics) states = env.get_states(*metrics, indices=indices) _recv = np.array([ [[1.1e-4, 0], [1.2e-4, 0], [1.3e-4, 0], [1.4e-4, 0]], [[0, 2.1e-4], [0, 2.2e-4], [0, 2.3e-4], [0, 2.4e-4]], [[3.1e-3, 0], [3.2e-3, 0], [3.3e-3, 0], [3.4e-3, 0]], [[0, 4.1e-3], [0, 4.2e-3], [0, 4.3e-3], [0, 4.4e-3]], ]) _rate = np.array([ log2(1+1.1/31), log2(1+2.2/42), log2(1+33/1.3), log2(1+44/2.4) ]) target_states = np.array([ np.concatenate([power[3],power[0],_recv[3][0],_recv[0][0],[_rate[3], _rate[0]]]), np.concatenate([power[3],power[1],_recv[3][1],_recv[1][1],[_rate[3], _rate[1]]]), np.concatenate([power[3],power[2],_recv[3][2],_recv[2][2],[_rate[3], _rate[2]]]), np.concatenate([power[2],power[3],_recv[2][3],_recv[3][3],[_rate[2], _rate[3]]]), ])[:2] assert equal(states, target_states) def test_sorter(): # now only recv_power can be sorter pass def test_seed(): env = PAEnv(n_level=4, m_cue=1, seed=123) # this is func in PAEnv to random pos def random_point(min_r, radius, ox=0, oy=0): theta = np.random.random() * 2 * np.pi r = np.random.uniform(min_r, radius**2) x, y = np.cos(theta) * np.sqrt(r), np.sin(theta) * np.sqrt(r) return ox + x, oy + y np.random.seed(123) target_x, target_y = random_point(env.r_bs, env.R_bs) usr = env.cues[0] assert all((target_x == usr.x, target_y == usr.y)) def test_action(): env = PAEnv(n_level=10, seed=799345) n_actions = env.n_actions n_channel, n_pair = env.n_channel, env.n_pair # normal env.reset() np.random.seed(799345) action = np.random.randint(0, n_actions, (n_channel, )) s_, r, d, i = env.step(action, unit='dBm') assert i['rate'] == 3.4741923099965257 # only D2D actions is enough env.reset() np.random.seed(799345) action = np.random.randint(0, n_actions, (n_pair, )) s_, r, d, i = env.step(action, unit='dBm') assert i['rate'] == 3.4741923099965257 # other action dim raises error env.reset() np.random.seed(799345) action = np.random.randint(0, n_actions, (n_pair - 1, )) try: s_, r, d, i = env.step(action, unit='dBm') except ValueError as e: msg = f"length of action should be n_channel({env.n_channel})" \ f" or n_pair({n_pair}), but is {len(action)}" assert e.args[0] == msg env.reset() np.random.seed(799345) action = np.random.randint(0, n_actions, (n_channel, )) s_, r, d, i = env.step(action, unit='mW') assert i['rate'] == 3.4928823957853856 # TODO add test of continuous action def test_step(): env = PAEnv(n_level=10) n_actions, n_states = env.n_actions, env.n_states assert n_actions == 40 assert n_states == 304 env.reset() action = env.sample() env.step(action, unit='dBm') # action = env.sample() action = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0]) env.step(action, unit='mW') action = env.sample() try: env.step(action, unit='xx') except ValueError as e: msg = f"unit should in ['dBm', 'mW'], but is xx" assert e.args[0] == msg fig: Path() = env.render() if fig.exists(): fig.unlink() if __name__ == '__main__': test_action()
true
true
f717a0e970b2703e99561e27a1e128a2f7e5f983
488
py
Python
tests/testFlip.py
FrankRogalski/Riccchard
8a1abf6855f874f71df9d101e15c1968394ab38e
[ "MIT" ]
null
null
null
tests/testFlip.py
FrankRogalski/Riccchard
8a1abf6855f874f71df9d101e15c1968394ab38e
[ "MIT" ]
null
null
null
tests/testFlip.py
FrankRogalski/Riccchard
8a1abf6855f874f71df9d101e15c1968394ab38e
[ "MIT" ]
null
null
null
import unittest import commands.flip as flip import pandas as pd class TestFlip(unittest.TestCase): def test_use(self): cycles = 50000 series = pd.Series(flip.use(None) for _ in range(cycles)) self.assertAlmostEqual(len(series[series == "Heads"]) / cycles, 0.4998, delta=0.01) self.assertAlmostEqual(len(series[series == "Heads"]) / cycles, 0.4998, delta=0.01) self.assertAlmostEqual(len(series[series == "Edge"]) / cycles, 0.0002, delta=0.01)
44.363636
91
0.67623
import unittest import commands.flip as flip import pandas as pd class TestFlip(unittest.TestCase): def test_use(self): cycles = 50000 series = pd.Series(flip.use(None) for _ in range(cycles)) self.assertAlmostEqual(len(series[series == "Heads"]) / cycles, 0.4998, delta=0.01) self.assertAlmostEqual(len(series[series == "Heads"]) / cycles, 0.4998, delta=0.01) self.assertAlmostEqual(len(series[series == "Edge"]) / cycles, 0.0002, delta=0.01)
true
true
f717a0f6acd973f0aa1fdd12d14ebe4d62f6382a
714
py
Python
src/detection/dataset/__init__.py
inzva/Traffic-Anomaly-Detection
09bbfd55f5d375832afcc1994d3b549082830594
[ "MIT" ]
4
2020-05-31T13:19:58.000Z
2021-03-11T18:51:06.000Z
src/detection/dataset/__init__.py
inzva/Traffic-Anomaly-Detection
09bbfd55f5d375832afcc1994d3b549082830594
[ "MIT" ]
null
null
null
src/detection/dataset/__init__.py
inzva/Traffic-Anomaly-Detection
09bbfd55f5d375832afcc1994d3b549082830594
[ "MIT" ]
3
2020-05-31T13:19:58.000Z
2021-03-16T08:43:23.000Z
from .custom import CustomDataset from .xml_style import XMLDataset from .coco import CocoDataset from .voc import VOCDataset from .loader import GroupSampler, DistributedGroupSampler, build_dataloader from .utils import to_tensor, random_scale, show_ann, get_dataset from .concat_dataset import ConcatDataset from .repeat_dataset import RepeatDataset from .extra_aug import ExtraAugmentation from .anomaly_data import AnomalyDataset __all__ = [ 'CustomDataset', 'XMLDataset', 'CocoDataset','AnomalyDataset', 'VOCDataset', 'GroupSampler', 'DistributedGroupSampler', 'build_dataloader', 'to_tensor', 'random_scale', 'show_ann', 'get_dataset', 'ConcatDataset', 'RepeatDataset', 'ExtraAugmentation' ]
42
96
0.802521
from .custom import CustomDataset from .xml_style import XMLDataset from .coco import CocoDataset from .voc import VOCDataset from .loader import GroupSampler, DistributedGroupSampler, build_dataloader from .utils import to_tensor, random_scale, show_ann, get_dataset from .concat_dataset import ConcatDataset from .repeat_dataset import RepeatDataset from .extra_aug import ExtraAugmentation from .anomaly_data import AnomalyDataset __all__ = [ 'CustomDataset', 'XMLDataset', 'CocoDataset','AnomalyDataset', 'VOCDataset', 'GroupSampler', 'DistributedGroupSampler', 'build_dataloader', 'to_tensor', 'random_scale', 'show_ann', 'get_dataset', 'ConcatDataset', 'RepeatDataset', 'ExtraAugmentation' ]
true
true
f717a12c03c3130be9f4f39624e011168ba2f2d9
419
py
Python
opencv_py/opencv_morphology/blackhat_operation.py
yinleiCoder/interesting-python
8448b0731870feed033d845c085576a7d4a3154b
[ "Apache-2.0" ]
null
null
null
opencv_py/opencv_morphology/blackhat_operation.py
yinleiCoder/interesting-python
8448b0731870feed033d845c085576a7d4a3154b
[ "Apache-2.0" ]
null
null
null
opencv_py/opencv_morphology/blackhat_operation.py
yinleiCoder/interesting-python
8448b0731870feed033d845c085576a7d4a3154b
[ "Apache-2.0" ]
null
null
null
import cv2 import numpy as np """ 黑帽: 黑帽= 原图 - 闭运算 morphologyEx(img, MORPH_BLACKHAT, kernel) 保留噪点 """ img = cv2.imread(r'E:\PycharmProjects\funnyPython\opencv_py\data\imgs\dotinj.png') # kernel = np.ones((7, 7), np.uint8)# 手动创建 kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (7, 7)) print(kernel) res = cv2.morphologyEx(img, cv2.MORPH_BLACKHAT, kernel) cv2.imshow('img', img) cv2.imshow('res', res) cv2.waitKey(0)
23.277778
82
0.725537
import cv2 import numpy as np img = cv2.imread(r'E:\PycharmProjects\funnyPython\opencv_py\data\imgs\dotinj.png') l = cv2.getStructuringElement(cv2.MORPH_RECT, (7, 7)) print(kernel) res = cv2.morphologyEx(img, cv2.MORPH_BLACKHAT, kernel) cv2.imshow('img', img) cv2.imshow('res', res) cv2.waitKey(0)
true
true
f717a22f1c27c859185f0569c6622ab8d155e4ac
1,915
py
Python
src/trainer.py
Chicco94/crypto-bot
edbc22477544a25d8eb0c90cdd5f03345f11db68
[ "MIT" ]
null
null
null
src/trainer.py
Chicco94/crypto-bot
edbc22477544a25d8eb0c90cdd5f03345f11db68
[ "MIT" ]
null
null
null
src/trainer.py
Chicco94/crypto-bot
edbc22477544a25d8eb0c90cdd5f03345f11db68
[ "MIT" ]
null
null
null
from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split import pandas as pd import sqlalchemy from config.config import symbol,backward_steps import joblib from df_functions import * def prepare_single_dataset(df,remove_from_heads:int,remove_from_tails:int,label:int): df_copy = df.copy() for _ in range(remove_from_tails): remove_row_from_tail(df_copy) for _ in range(remove_from_heads): remove_row_from_head(df_copy) add_id(df_copy) df_copy.time = df_copy.time.apply(lambda x: x.value) df_copy.rename(columns={"time": "time{}".format(label) , "price": "price{}".format(label) , "quantity":"quantity{}".format(label)} ,inplace=True) df_copy.drop(columns=['symbol'],inplace=True) return df_copy def prepare_dataset(df,steps:int): datasets = [] for i in range(1,steps): datasets.append(prepare_single_dataset(df,steps-i,i-1,i)) df_target = prepare_single_dataset(df,0,steps-1,steps) result = datasets.pop() while len(datasets)>0: result = pd.merge(result, datasets.pop(), on="ID") target = df_target['price{}'.format(steps)] return result,target def main(): # open database engine = sqlalchemy.create_engine('sqlite:///data/{}_stream.db'.format(symbol)) df = pd.read_sql(symbol,engine) # prepare dataset source,target = prepare_dataset(df,backward_steps) # train model model = LinearRegression() X_train,X_test,y_train,y_test = train_test_split(source,target,test_size=0.33) model.fit(X_train,y_train) # evaluate model score = model.score(X_test,y_test) print('score: ',score) # save model filename = 'models/model_{}.sav'.format(score) joblib.dump(model, filename) #model = joblib.load(filename) if __name__=='__main__': main()
33.017241
85
0.681462
from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split import pandas as pd import sqlalchemy from config.config import symbol,backward_steps import joblib from df_functions import * def prepare_single_dataset(df,remove_from_heads:int,remove_from_tails:int,label:int): df_copy = df.copy() for _ in range(remove_from_tails): remove_row_from_tail(df_copy) for _ in range(remove_from_heads): remove_row_from_head(df_copy) add_id(df_copy) df_copy.time = df_copy.time.apply(lambda x: x.value) df_copy.rename(columns={"time": "time{}".format(label) , "price": "price{}".format(label) , "quantity":"quantity{}".format(label)} ,inplace=True) df_copy.drop(columns=['symbol'],inplace=True) return df_copy def prepare_dataset(df,steps:int): datasets = [] for i in range(1,steps): datasets.append(prepare_single_dataset(df,steps-i,i-1,i)) df_target = prepare_single_dataset(df,0,steps-1,steps) result = datasets.pop() while len(datasets)>0: result = pd.merge(result, datasets.pop(), on="ID") target = df_target['price{}'.format(steps)] return result,target def main(): engine = sqlalchemy.create_engine('sqlite:///data/{}_stream.db'.format(symbol)) df = pd.read_sql(symbol,engine) source,target = prepare_dataset(df,backward_steps) model = LinearRegression() X_train,X_test,y_train,y_test = train_test_split(source,target,test_size=0.33) model.fit(X_train,y_train) score = model.score(X_test,y_test) print('score: ',score) filename = 'models/model_{}.sav'.format(score) joblib.dump(model, filename) if __name__=='__main__': main()
true
true
f717a46b3c38e7a991236ce1bb31333e778f6d48
300
py
Python
backend/app/main.py
alldevic/base-fastapi-postgresql
7e3a2916910155cd83b10cd7fec42eba7b1d3a95
[ "MIT" ]
3
2021-06-17T00:06:15.000Z
2022-01-26T03:53:51.000Z
backend/app/main.py
alldevic/base-fastapi-postgresql
7e3a2916910155cd83b10cd7fec42eba7b1d3a95
[ "MIT" ]
null
null
null
backend/app/main.py
alldevic/base-fastapi-postgresql
7e3a2916910155cd83b10cd7fec42eba7b1d3a95
[ "MIT" ]
null
null
null
from .routes.users import router as user_router from .application import app import sys sys.path.extend(["./"]) ROUTERS = (user_router,) for r in ROUTERS: app.include_router(r) if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8888, log_level="info")
16.666667
65
0.693333
from .routes.users import router as user_router from .application import app import sys sys.path.extend(["./"]) ROUTERS = (user_router,) for r in ROUTERS: app.include_router(r) if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8888, log_level="info")
true
true
f717a4b4672f82239831e0aa4b03a4aaca187963
11,669
py
Python
tests/test_storage.py
civviGH/otterwiki
2ef84aa31f48da144cb0ef7a0116106b982f41d2
[ "MIT" ]
3
2018-07-15T20:20:31.000Z
2022-01-09T07:41:39.000Z
tests/test_storage.py
civviGH/otterwiki
2ef84aa31f48da144cb0ef7a0116106b982f41d2
[ "MIT" ]
3
2018-07-04T21:38:41.000Z
2022-03-06T17:03:23.000Z
tests/test_storage.py
civviGH/otterwiki
2ef84aa31f48da144cb0ef7a0116106b982f41d2
[ "MIT" ]
2
2021-04-29T13:17:56.000Z
2022-03-07T09:17:19.000Z
#!/usr/bin/env python import tempfile import unittest from pprint import pprint import otterwiki.storage class TestStorage(unittest.TestCase): def setUp(self): self.tempdir = tempfile.TemporaryDirectory() self.path = '/tmp/xxx' # self.tempdir.name self.path = self.tempdir.name self.storage = otterwiki.storage.GitStorage(path=self.path, initialize=True) def tearDown(self): self.tempdir.cleanup() def test_store_and_load(self): content = "kdfjlhg gdklfjghdf gkl;djshfg dgf;lkjhs glkshjad\n" message = "Test commit" filename = "test.md" author = ("Example Author", "mail@example.com") self.assertTrue( self.storage.store(filename, content=content, author=author, message=message) ) # check content self.assertEqual( self.storage.load(filename), content ) # check metadata metadata = self.storage.metadata(filename) self.assertEqual( metadata['author_name'], author[0] ) self.assertEqual( metadata['author_email'], author[1] ) self.assertEqual( metadata['message'], message ) # check if file is listed self.assertIn( filename, self.storage.list_files() ) # check if storing the same content changes nothing self.assertFalse( self.storage.store(filename, content=content, author=author) ) def test_load_fail(self): with self.assertRaises(otterwiki.storage.StorageNotFound): self.storage.load("non-existent.md") with self.assertRaises(otterwiki.storage.StorageNotFound): self.storage.metadata("non-existent.md") with self.assertRaises(otterwiki.storage.StorageNotFound): self.storage.metadata("non-existent.md", revision="xxx") with self.assertRaises(otterwiki.storage.StorageNotFound): self.storage.log("non-existent.md") def test_broken_author(self): content = "This is test content.\n" message = "Test commit" filename = "test_broken_author.md" author = ("Example Author", "") self.assertTrue( self.storage.store(filename, content=content, author=author, message=message) ) metadata = self.storage.metadata(filename) self.assertEqual( metadata['author_name'], author[0] ) def test_broken_message(self): content = "This is test content.\n" message = None filename = "test_broken_message.md" author = ("Example Author", "mail@example.org") self.assertTrue( self.storage.store(filename, content=content, author=author, message=message) ) metadata = self.storage.metadata(filename) self.assertEqual( metadata['message'], '' ) def test_log(self): content = "kdfjlhg gdklfjghdf gkl;djshfg dgf;lkjhs glkshjad\n" message = "Test commit" filename = "test_log.md" author = ("Example Author", "mail@example.com") self.assertTrue( self.storage.store(filename, content=content, author=author, message=message) ) # test log for filename log = self.storage.log(filename) msg = log[-1] self.assertEqual(msg['message'], message) # test global log log = self.storage.log() msg = log[-1] self.assertEqual(msg['message'], message) def test_revert(self): author = ("Example Author", "mail@example.com") filename = "test_revert.md" content1 = "aaa" message1 = "added {}".format(content1) content2 = "bbb" message2 = "added {}".format(content2) self.assertTrue( self.storage.store(filename, content=content1, author=author, message=message1) ) # check content self.assertEqual( self.storage.load(filename), content1 ) # change content self.assertTrue( self.storage.store(filename, content=content2, author=author, message=message2) ) # check content self.assertEqual( self.storage.load(filename), content2 ) # get revision log = self.storage.log(filename) revision = log[0]['revision'] self.storage.revert(revision, message="reverted {}".format(revision), author=author) # check that the file is in the old state self.assertEqual( self.storage.load(filename), content1 ) def test_revert_fail(self): author = ("Example Author", "mail@example.com") filename = "test_revert_fail.md" content1 = "aaa" message1 = "added {}".format(content1) self.assertTrue( self.storage.store(filename, content=content1, author=author, message=message1) ) # get revision log = self.storage.log(filename) revision = log[0]['revision'] # revert self.storage.revert(revision, message="reverted {}".format(revision), author=author) files = self.storage.list_files() self.assertNotIn(filename, files) def test_ascii_binary(self): content = u"kdfjlhg gdklfjghdf gkl;djshfg dgf;lkjhs glkshjad" message = "Test commit" filename = "test_binary.md" author = ("Example Author", "mail@example.com") self.assertTrue( self.storage.store(filename, content=content, author=author, message=message) ) content_rb = self.storage.load(filename, mode="rb") content_r = self.storage.load(filename, mode="r") # check types self.assertIs(type(content_rb), bytes) self.assertIs(type(content_r), str) # convert into str content_utf8 = content_rb.decode("utf-8") self.assertIs(type(content_utf8), str) self.assertEqual(content_utf8, content_r) def test_binary(self): content = b"GIF89a\x01\x00\x01\x00\x80\x01\x00\xff\xff"\ b"\xff\x00\x00\x00!\xf9\x04\x01\n\x00\x01\x00,"\ b"\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02L\x01\x00;" message = "Test commit" filename = "test_binary.gif" author = ("Example Author", "mail@example.com") self.assertTrue( self.storage.store(filename, content=content, author=author, message=message, mode='wb') ) content_rb = self.storage.load(filename, mode="rb") self.assertEqual(content, content_rb) # get log log = self.storage.log() # get revisions revision = log[0]['revision'] content_rb2 = self.storage.load(filename, mode="rb", revision=revision) self.assertEqual(content_rb2, content_rb) def test_revision(self): content = "kdfjlhg gdklfjghdf gkl;djshfg dgf;lkjhs glkshjad" message = "Test commit" filename = "test_revision.md" author = ("Example Author", "mail@example.com") self.assertTrue( self.storage.store(filename, content=content, author=author, message=message) ) metadata = self.storage.metadata(filename) revision = metadata['revision-full'] self.assertEqual( self.storage.load(filename, revision=revision), content ) metadata2 = self.storage.metadata(filename, revision=revision) self.assertEqual( metadata, metadata2) # check broken revision revision3 = "xxx{}".format(revision) with self.assertRaises(otterwiki.storage.StorageNotFound): self.storage.metadata(filename, revision=revision3) with self.assertRaises(otterwiki.storage.StorageNotFound): self.storage.load(filename, revision=revision3) def test_store_subdir(self): content = "kdfjlhg gdklfjghdf gkl;djshfg dgf;lkjhs glkshjad\n" message = "Test commit" filename = "test_subdir/test_subdir.md" author = ("Example Author", "mail@example.com") self.assertTrue( self.storage.store(filename, content=content, author=author, message=message) ) # check if file exists self.assertTrue( self.storage.exists(filename) ) # check via file list files = self.storage.list_files() self.assertIn(filename, files) dn, fn = filename.split('/') files = self.storage.list_files(dn) self.assertIn(fn, files) def test_diff(self): author = ("Example Author", "mail@example.com") filename = "test_revert.md" content1 = "aaa" message1 = "added {}".format(content1) content2 = "bbb" message2 = "added {}".format(content2) self.assertTrue( self.storage.store(filename, content=content1, author=author, message=message1) ) # check content self.assertEqual( self.storage.load(filename), content1 ) # change content self.assertTrue( self.storage.store(filename, content=content2, author=author, message=message2) ) # check content self.assertEqual( self.storage.load(filename), content2 ) # get log log = self.storage.log() # get revisions rev_b, rev_a= log[0]['revision'], log[1]['revision'] # get diff diff = self.storage.diff(filename, rev_a, rev_b) # check -/+ strings self.assertIn("-aaa", diff) self.assertIn("+bbb", diff) def test_rename(self): content = "kdfjlhg gdklfjghdf gkl;djshfg dgf;lkjhs glkshjad\n" message = "Test commit" filename1 = "test_rename1.md" filename2 = "test_rename2.md" author = ("Example Author", "mail@example.com") self.assertTrue( self.storage.store(filename1, content=content, author=author, message=message) ) # rename self.storage.rename( filename1, filename2, author=author ) # check if file exists self.assertFalse( self.storage.exists(filename1) ) self.assertTrue( self.storage.exists(filename2) ) # check if file exists via list_files files = self.storage.list_files() self.assertNotIn(filename1, files) self.assertIn(filename2, files) # check content self.assertEqual( self.storage.load(filename2), content ) # test rename fail with self.assertRaises(otterwiki.storage.StorageError): self.storage.rename( filename1, "", author=author ) def test_delete(self): content = "kdfjlhg gdklfjghdf gkl;djshfg dgf;lkjhs glkshjad" message = "Test commit" filename = "test_revision.md" author = ("Example Author", "mail@example.com") self.assertTrue( self.storage.store(filename, content=content, author=author, message=message) ) # check if file exists files = self.storage.list_files() self.assertIn(filename, files) # remove file self.storage.delete(filename, author=author) # check that file doesn't exist anymore files = self.storage.list_files() self.assertNotIn(filename, files) class TestEmptyStorage(unittest.TestCase): def test_log(self): with tempfile.TemporaryDirectory() as path: storage = otterwiki.storage.GitStorage(path=path, initialize=True) self.assertEqual(storage.log(), []) def test_load_fail(self): with tempfile.TemporaryDirectory() as path: storage = otterwiki.storage.GitStorage(path=path, initialize=True) with self.assertRaises(otterwiki.storage.StorageNotFound): storage.load("non-existent.md") with self.assertRaises(otterwiki.storage.StorageNotFound): storage.log("non-existent.md") def test_init_fail(self): with tempfile.TemporaryDirectory() as path: with self.assertRaises(otterwiki.storage.StorageError): storage = otterwiki.storage.GitStorage(path=path) if __name__ == '__main__': unittest.main()
43.70412
115
0.646756
import tempfile import unittest from pprint import pprint import otterwiki.storage class TestStorage(unittest.TestCase): def setUp(self): self.tempdir = tempfile.TemporaryDirectory() self.path = '/tmp/xxx' self.path = self.tempdir.name self.storage = otterwiki.storage.GitStorage(path=self.path, initialize=True) def tearDown(self): self.tempdir.cleanup() def test_store_and_load(self): content = "kdfjlhg gdklfjghdf gkl;djshfg dgf;lkjhs glkshjad\n" message = "Test commit" filename = "test.md" author = ("Example Author", "mail@example.com") self.assertTrue( self.storage.store(filename, content=content, author=author, message=message) ) self.assertEqual( self.storage.load(filename), content ) metadata = self.storage.metadata(filename) self.assertEqual( metadata['author_name'], author[0] ) self.assertEqual( metadata['author_email'], author[1] ) self.assertEqual( metadata['message'], message ) self.assertIn( filename, self.storage.list_files() ) self.assertFalse( self.storage.store(filename, content=content, author=author) ) def test_load_fail(self): with self.assertRaises(otterwiki.storage.StorageNotFound): self.storage.load("non-existent.md") with self.assertRaises(otterwiki.storage.StorageNotFound): self.storage.metadata("non-existent.md") with self.assertRaises(otterwiki.storage.StorageNotFound): self.storage.metadata("non-existent.md", revision="xxx") with self.assertRaises(otterwiki.storage.StorageNotFound): self.storage.log("non-existent.md") def test_broken_author(self): content = "This is test content.\n" message = "Test commit" filename = "test_broken_author.md" author = ("Example Author", "") self.assertTrue( self.storage.store(filename, content=content, author=author, message=message) ) metadata = self.storage.metadata(filename) self.assertEqual( metadata['author_name'], author[0] ) def test_broken_message(self): content = "This is test content.\n" message = None filename = "test_broken_message.md" author = ("Example Author", "mail@example.org") self.assertTrue( self.storage.store(filename, content=content, author=author, message=message) ) metadata = self.storage.metadata(filename) self.assertEqual( metadata['message'], '' ) def test_log(self): content = "kdfjlhg gdklfjghdf gkl;djshfg dgf;lkjhs glkshjad\n" message = "Test commit" filename = "test_log.md" author = ("Example Author", "mail@example.com") self.assertTrue( self.storage.store(filename, content=content, author=author, message=message) ) log = self.storage.log(filename) msg = log[-1] self.assertEqual(msg['message'], message) log = self.storage.log() msg = log[-1] self.assertEqual(msg['message'], message) def test_revert(self): author = ("Example Author", "mail@example.com") filename = "test_revert.md" content1 = "aaa" message1 = "added {}".format(content1) content2 = "bbb" message2 = "added {}".format(content2) self.assertTrue( self.storage.store(filename, content=content1, author=author, message=message1) ) self.assertEqual( self.storage.load(filename), content1 ) self.assertTrue( self.storage.store(filename, content=content2, author=author, message=message2) ) self.assertEqual( self.storage.load(filename), content2 ) log = self.storage.log(filename) revision = log[0]['revision'] self.storage.revert(revision, message="reverted {}".format(revision), author=author) self.assertEqual( self.storage.load(filename), content1 ) def test_revert_fail(self): author = ("Example Author", "mail@example.com") filename = "test_revert_fail.md" content1 = "aaa" message1 = "added {}".format(content1) self.assertTrue( self.storage.store(filename, content=content1, author=author, message=message1) ) log = self.storage.log(filename) revision = log[0]['revision'] self.storage.revert(revision, message="reverted {}".format(revision), author=author) files = self.storage.list_files() self.assertNotIn(filename, files) def test_ascii_binary(self): content = u"kdfjlhg gdklfjghdf gkl;djshfg dgf;lkjhs glkshjad" message = "Test commit" filename = "test_binary.md" author = ("Example Author", "mail@example.com") self.assertTrue( self.storage.store(filename, content=content, author=author, message=message) ) content_rb = self.storage.load(filename, mode="rb") content_r = self.storage.load(filename, mode="r") self.assertIs(type(content_rb), bytes) self.assertIs(type(content_r), str) content_utf8 = content_rb.decode("utf-8") self.assertIs(type(content_utf8), str) self.assertEqual(content_utf8, content_r) def test_binary(self): content = b"GIF89a\x01\x00\x01\x00\x80\x01\x00\xff\xff"\ b"\xff\x00\x00\x00!\xf9\x04\x01\n\x00\x01\x00,"\ b"\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02L\x01\x00;" message = "Test commit" filename = "test_binary.gif" author = ("Example Author", "mail@example.com") self.assertTrue( self.storage.store(filename, content=content, author=author, message=message, mode='wb') ) content_rb = self.storage.load(filename, mode="rb") self.assertEqual(content, content_rb) log = self.storage.log() revision = log[0]['revision'] content_rb2 = self.storage.load(filename, mode="rb", revision=revision) self.assertEqual(content_rb2, content_rb) def test_revision(self): content = "kdfjlhg gdklfjghdf gkl;djshfg dgf;lkjhs glkshjad" message = "Test commit" filename = "test_revision.md" author = ("Example Author", "mail@example.com") self.assertTrue( self.storage.store(filename, content=content, author=author, message=message) ) metadata = self.storage.metadata(filename) revision = metadata['revision-full'] self.assertEqual( self.storage.load(filename, revision=revision), content ) metadata2 = self.storage.metadata(filename, revision=revision) self.assertEqual( metadata, metadata2) revision3 = "xxx{}".format(revision) with self.assertRaises(otterwiki.storage.StorageNotFound): self.storage.metadata(filename, revision=revision3) with self.assertRaises(otterwiki.storage.StorageNotFound): self.storage.load(filename, revision=revision3) def test_store_subdir(self): content = "kdfjlhg gdklfjghdf gkl;djshfg dgf;lkjhs glkshjad\n" message = "Test commit" filename = "test_subdir/test_subdir.md" author = ("Example Author", "mail@example.com") self.assertTrue( self.storage.store(filename, content=content, author=author, message=message) ) self.assertTrue( self.storage.exists(filename) ) files = self.storage.list_files() self.assertIn(filename, files) dn, fn = filename.split('/') files = self.storage.list_files(dn) self.assertIn(fn, files) def test_diff(self): author = ("Example Author", "mail@example.com") filename = "test_revert.md" content1 = "aaa" message1 = "added {}".format(content1) content2 = "bbb" message2 = "added {}".format(content2) self.assertTrue( self.storage.store(filename, content=content1, author=author, message=message1) ) self.assertEqual( self.storage.load(filename), content1 ) self.assertTrue( self.storage.store(filename, content=content2, author=author, message=message2) ) self.assertEqual( self.storage.load(filename), content2 ) log = self.storage.log() rev_b, rev_a= log[0]['revision'], log[1]['revision'] diff = self.storage.diff(filename, rev_a, rev_b) self.assertIn("-aaa", diff) self.assertIn("+bbb", diff) def test_rename(self): content = "kdfjlhg gdklfjghdf gkl;djshfg dgf;lkjhs glkshjad\n" message = "Test commit" filename1 = "test_rename1.md" filename2 = "test_rename2.md" author = ("Example Author", "mail@example.com") self.assertTrue( self.storage.store(filename1, content=content, author=author, message=message) ) self.storage.rename( filename1, filename2, author=author ) self.assertFalse( self.storage.exists(filename1) ) self.assertTrue( self.storage.exists(filename2) ) files = self.storage.list_files() self.assertNotIn(filename1, files) self.assertIn(filename2, files) self.assertEqual( self.storage.load(filename2), content ) with self.assertRaises(otterwiki.storage.StorageError): self.storage.rename( filename1, "", author=author ) def test_delete(self): content = "kdfjlhg gdklfjghdf gkl;djshfg dgf;lkjhs glkshjad" message = "Test commit" filename = "test_revision.md" author = ("Example Author", "mail@example.com") self.assertTrue( self.storage.store(filename, content=content, author=author, message=message) ) files = self.storage.list_files() self.assertIn(filename, files) self.storage.delete(filename, author=author) files = self.storage.list_files() self.assertNotIn(filename, files) class TestEmptyStorage(unittest.TestCase): def test_log(self): with tempfile.TemporaryDirectory() as path: storage = otterwiki.storage.GitStorage(path=path, initialize=True) self.assertEqual(storage.log(), []) def test_load_fail(self): with tempfile.TemporaryDirectory() as path: storage = otterwiki.storage.GitStorage(path=path, initialize=True) with self.assertRaises(otterwiki.storage.StorageNotFound): storage.load("non-existent.md") with self.assertRaises(otterwiki.storage.StorageNotFound): storage.log("non-existent.md") def test_init_fail(self): with tempfile.TemporaryDirectory() as path: with self.assertRaises(otterwiki.storage.StorageError): storage = otterwiki.storage.GitStorage(path=path) if __name__ == '__main__': unittest.main()
true
true
f717a54cab0f7211990d1d0fff0102426e318378
4,412
py
Python
TTY_Utils/StatusLine.py
paul-ollis/cleversheep3
86e6ca76ea4e8524f16e2348d38484dcfafb07d0
[ "Apache-2.0" ]
null
null
null
TTY_Utils/StatusLine.py
paul-ollis/cleversheep3
86e6ca76ea4e8524f16e2348d38484dcfafb07d0
[ "Apache-2.0" ]
null
null
null
TTY_Utils/StatusLine.py
paul-ollis/cleversheep3
86e6ca76ea4e8524f16e2348d38484dcfafb07d0
[ "Apache-2.0" ]
null
null
null
import sys import time from cleversheep3.TTY_Utils import RichTerm, registerForWinch class Status: """A fairly general purpose status line for a simple terminal. """ def __init__(self, startActive=True): self.setTerm(RichTerm.RichTerminal(sys.stdout)) self.spinner = None self.prevLine = None self.leftFields = [] self.leftFieldsByName = {} self.rightFields = [] self.rightFieldsByName = {} self.prevTime = time.time() self.updateInterval = 0.1 self.killed = True self.active = startActive registerForWinch(lambda: self.onWinch()) def onWinch(self): h, self.w = self.term.getDims(force=1) def setTerm(self, term): self.term = term h, self.w = self.term.getDims() def stop(self): self.kill() self.active = False def start(self): self.active = True def addLeftField(self, name, w): if name not in self.leftFieldsByName: self.leftFieldsByName[name] = len(self.leftFields) self.leftFields.append((w, "")) addField = addLeftField def addRightField(self, name, w): if name not in self.rightFieldsByName: self.rightFieldsByName[name] = len(self.rightFields) self.rightFields.append((w, "")) def setField(self, name, text): if text: text = text.splitlines()[0] try: idx = self.leftFieldsByName[name] w, _ = self.leftFields[idx] self.leftFields[idx] = w, text except KeyError: idx = self.rightFieldsByName[name] w, _ = self.rightFields[idx] self.rightFields[idx] = w, text self.update() def addSpinner(self, seq=r'\|/-'): def chars(): while True: for c in seq: yield c def s(): cc = chars() c = next(cc) t = time.time() while True: if time.time() - t > 0.1: t = time.time() c = next(cc) yield c self.spinner = s() def buildLine(self): ww = self.w - 2 rline = "" lline = "" for w, text in self.rightFields: bar = "" if rline: bar = "|" rline = "%-*.*s%s%s" % (w, w, text, bar, rline) lline = "" if self.spinner: lline += "%s " % next(self.spinner) for w, text in self.leftFields: if lline: lline += "|" if w is not None: lline += "%-*.*s" % (w, w, text) else: lline += "%s" % (text,) l = len(lline) + len(rline) if l > ww: rline = rline.rstrip() l = len(lline) + len(rline) if l > ww: lline = lline.rstrip() l = len(lline) + len(rline) while len(lline) > len(rline) and l > ww: lline = lline[:-1] l = len(lline) + len(rline) while len(rline) > len(lline) and l > ww: rline = rline[1:] l = len(lline) + len(rline) while l > ww: lline = lline[:-1] rline = rline[1:] l = len(lline) + len(rline) if lline and rline: pad = " " * (ww - len(lline) - len(rline) - 1) line = "%s%s|%s" % (lline, pad, rline) elif rline: pad = " " * (ww - len(lline) - len(rline)) line = "%s%s%s" % (lline, pad, rline) else: line = lline return line def update(self, force=False): if not (self.active and self.term.isatty()): return if not force and time.time() - self.prevTime < self.updateInterval: return self.prevTime = time.time() self.line = self.buildLine() if self.line != self.prevLine: self.term.write("\r%s" % self.line) self.term.flush() self.prevLine = self.line self.killed = False def kill(self): if not (self.active and self.term.isatty()): return if self.killed: return self.term.write("\r%s\r" % (" " * (self.w - 1))) self.term.flush() self.prevLine = None self.killed = True
29.026316
75
0.486174
import sys import time from cleversheep3.TTY_Utils import RichTerm, registerForWinch class Status: def __init__(self, startActive=True): self.setTerm(RichTerm.RichTerminal(sys.stdout)) self.spinner = None self.prevLine = None self.leftFields = [] self.leftFieldsByName = {} self.rightFields = [] self.rightFieldsByName = {} self.prevTime = time.time() self.updateInterval = 0.1 self.killed = True self.active = startActive registerForWinch(lambda: self.onWinch()) def onWinch(self): h, self.w = self.term.getDims(force=1) def setTerm(self, term): self.term = term h, self.w = self.term.getDims() def stop(self): self.kill() self.active = False def start(self): self.active = True def addLeftField(self, name, w): if name not in self.leftFieldsByName: self.leftFieldsByName[name] = len(self.leftFields) self.leftFields.append((w, "")) addField = addLeftField def addRightField(self, name, w): if name not in self.rightFieldsByName: self.rightFieldsByName[name] = len(self.rightFields) self.rightFields.append((w, "")) def setField(self, name, text): if text: text = text.splitlines()[0] try: idx = self.leftFieldsByName[name] w, _ = self.leftFields[idx] self.leftFields[idx] = w, text except KeyError: idx = self.rightFieldsByName[name] w, _ = self.rightFields[idx] self.rightFields[idx] = w, text self.update() def addSpinner(self, seq=r'\|/-'): def chars(): while True: for c in seq: yield c def s(): cc = chars() c = next(cc) t = time.time() while True: if time.time() - t > 0.1: t = time.time() c = next(cc) yield c self.spinner = s() def buildLine(self): ww = self.w - 2 rline = "" lline = "" for w, text in self.rightFields: bar = "" if rline: bar = "|" rline = "%-*.*s%s%s" % (w, w, text, bar, rline) lline = "" if self.spinner: lline += "%s " % next(self.spinner) for w, text in self.leftFields: if lline: lline += "|" if w is not None: lline += "%-*.*s" % (w, w, text) else: lline += "%s" % (text,) l = len(lline) + len(rline) if l > ww: rline = rline.rstrip() l = len(lline) + len(rline) if l > ww: lline = lline.rstrip() l = len(lline) + len(rline) while len(lline) > len(rline) and l > ww: lline = lline[:-1] l = len(lline) + len(rline) while len(rline) > len(lline) and l > ww: rline = rline[1:] l = len(lline) + len(rline) while l > ww: lline = lline[:-1] rline = rline[1:] l = len(lline) + len(rline) if lline and rline: pad = " " * (ww - len(lline) - len(rline) - 1) line = "%s%s|%s" % (lline, pad, rline) elif rline: pad = " " * (ww - len(lline) - len(rline)) line = "%s%s%s" % (lline, pad, rline) else: line = lline return line def update(self, force=False): if not (self.active and self.term.isatty()): return if not force and time.time() - self.prevTime < self.updateInterval: return self.prevTime = time.time() self.line = self.buildLine() if self.line != self.prevLine: self.term.write("\r%s" % self.line) self.term.flush() self.prevLine = self.line self.killed = False def kill(self): if not (self.active and self.term.isatty()): return if self.killed: return self.term.write("\r%s\r" % (" " * (self.w - 1))) self.term.flush() self.prevLine = None self.killed = True
true
true
f717a6a6f7df269ba5f932fb06f6150bdffcbc05
2,958
py
Python
etk/unit_tests/test_filter_results.py
linqyd/etk
dcf0cae4076619f5261573d47b4f5f26baaf15b7
[ "MIT" ]
null
null
null
etk/unit_tests/test_filter_results.py
linqyd/etk
dcf0cae4076619f5261573d47b4f5f26baaf15b7
[ "MIT" ]
null
null
null
etk/unit_tests/test_filter_results.py
linqyd/etk
dcf0cae4076619f5261573d47b4f5f26baaf15b7
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- import unittest import sys, os sys.path.append('../../') from etk.core import Core import json import codecs class TestExtractionsFilterResults(unittest.TestCase): def test_filter_results(self): doc = { "url":"http:www.testurl.com", "doc_id": "19B0EAB211CD1D3C63063FAB0B2937043EA1F07B5341014A80E7473BA7318D9E", "knowledge_graph": { "name": [ { "provenance": [ { "extracted_value": "Very", "method": "extract_using_custom_spacy", "confidence": { "extraction": 1 }, "source": { "segment": "content_strict", "context": { "rule_id": 1, "input": "tokens", "identifier": "name_rule_02", "start": 18, "end": 21, "text": ". \n Well Guess What <etk 'attribute' = 'name'>i am Very</etk> Real \n I DON ' " }, "document_id": "19B0EAB211CD1D3C63063FAB0B2937043EA1F07B5341014A80E7473BA7318D9E" } } ], "confidence": 1.0, "value": "Very", "key": "very" } ] } } stop_words_path = os.path.join(os.path.dirname(__file__), "resources/stop_word_names.json") e_config = { "document_id":"doc_id", "resources": { "stop_word_dictionaries": { "name": stop_words_path } }, "kg_enhancement": { "fields": { "name": { "priority": 0, "extractors": { "filter_results": { "config": { "stop_word_dictionaries": "name" } } } } }, "input_path": "knowledge_graph.`parent`" }} c = Core(extraction_config=e_config) r = c.process(doc) self.assertTrue('knowledge_graph' in doc) self.assertTrue('name' in doc['knowledge_graph']) self.assertTrue(len(doc['knowledge_graph']['name']) == 1) self.assertTrue(doc['knowledge_graph']['name'][0]['confidence'] == 0.3) if __name__ == '__main__': unittest.main()
36.518519
129
0.373563
import unittest import sys, os sys.path.append('../../') from etk.core import Core import json import codecs class TestExtractionsFilterResults(unittest.TestCase): def test_filter_results(self): doc = { "url":"http:www.testurl.com", "doc_id": "19B0EAB211CD1D3C63063FAB0B2937043EA1F07B5341014A80E7473BA7318D9E", "knowledge_graph": { "name": [ { "provenance": [ { "extracted_value": "Very", "method": "extract_using_custom_spacy", "confidence": { "extraction": 1 }, "source": { "segment": "content_strict", "context": { "rule_id": 1, "input": "tokens", "identifier": "name_rule_02", "start": 18, "end": 21, "text": ". \n Well Guess What <etk 'attribute' = 'name'>i am Very</etk> Real \n I DON ' " }, "document_id": "19B0EAB211CD1D3C63063FAB0B2937043EA1F07B5341014A80E7473BA7318D9E" } } ], "confidence": 1.0, "value": "Very", "key": "very" } ] } } stop_words_path = os.path.join(os.path.dirname(__file__), "resources/stop_word_names.json") e_config = { "document_id":"doc_id", "resources": { "stop_word_dictionaries": { "name": stop_words_path } }, "kg_enhancement": { "fields": { "name": { "priority": 0, "extractors": { "filter_results": { "config": { "stop_word_dictionaries": "name" } } } } }, "input_path": "knowledge_graph.`parent`" }} c = Core(extraction_config=e_config) r = c.process(doc) self.assertTrue('knowledge_graph' in doc) self.assertTrue('name' in doc['knowledge_graph']) self.assertTrue(len(doc['knowledge_graph']['name']) == 1) self.assertTrue(doc['knowledge_graph']['name'][0]['confidence'] == 0.3) if __name__ == '__main__': unittest.main()
true
true
f717a6c9a05c6c18f54f5308390fe72e04c86105
10,727
py
Python
dataset/cs_labels.py
ChunGaoY/DSPnet
8fad61059d85ad0cd1f7790c37b5e0478dccb158
[ "MIT" ]
33
2018-04-18T06:52:16.000Z
2021-09-26T20:57:56.000Z
dataset/cs_labels.py
ChunGaoY/DSPnet
8fad61059d85ad0cd1f7790c37b5e0478dccb158
[ "MIT" ]
4
2018-07-09T07:09:15.000Z
2020-04-12T12:43:36.000Z
dataset/cs_labels.py
liangfu/dspnet
8fad61059d85ad0cd1f7790c37b5e0478dccb158
[ "MIT" ]
10
2018-04-19T08:17:01.000Z
2021-09-26T20:57:57.000Z
#!/usr/bin/python # # Cityscapes labels # from collections import namedtuple #-------------------------------------------------------------------------------- # Definitions #-------------------------------------------------------------------------------- # a label and all meta information Label = namedtuple( 'Label' , [ 'name' , # The identifier of this label, e.g. 'car', 'person', ... . # We use them to uniquely name a class 'id' , # An integer ID that is associated with this label. # The IDs are used to represent the label in ground truth images # An ID of -1 means that this label does not have an ID and thus # is ignored when creating ground truth images (e.g. license plate). # Do not modify these IDs, since exactly these IDs are expected by the # evaluation server. 'trainId' , # Feel free to modify these IDs as suitable for your method. Then create # ground truth images with train IDs, using the tools provided in the # 'preparation' folder. However, make sure to validate or submit results # to our evaluation server using the regular IDs above! # For trainIds, multiple labels might have the same ID. Then, these labels # are mapped to the same class in the ground truth images. For the inverse # mapping, we use the label that is defined first in the list below. # For example, mapping all void-type classes to the same ID in training, # might make sense for some approaches. # Max value is 255! 'category' , # The name of the category that this label belongs to 'categoryId' , # The ID of this category. Used to create ground truth images # on category level. 'hasInstances', # Whether this label distinguishes between single instances or not 'ignoreInEval', # Whether pixels having this class as ground truth label are ignored # during evaluations or not 'color' , # The color of this label ] ) #-------------------------------------------------------------------------------- # A list of all labels #-------------------------------------------------------------------------------- # Please adapt the train IDs as appropriate for you approach. # Note that you might want to ignore labels with ID 255 during training. # Further note that the current train IDs are only a suggestion. You can use whatever you like. # Make sure to provide your results using the original IDs and not the training IDs. # Note that many IDs are ignored in evaluation and thus you never need to predict these! labels = [ # name id trainId category catId hasInstances ignoreInEval color Label( 'unlabeled' , 0 , 255 , 'void' , 0 , False , True , ( 0, 0, 0) ), Label( 'ego vehicle' , 1 , 255 , 'void' , 0 , False , True , ( 0, 0, 0) ), Label( 'rectification border' , 2 , 255 , 'void' , 0 , False , True , ( 0, 0, 0) ), Label( 'out of roi' , 3 , 255 , 'void' , 0 , False , True , ( 0, 0, 0) ), Label( 'static' , 4 , 255 , 'void' , 0 , False , True , ( 0, 0, 0) ), Label( 'dynamic' , 5 , 255 , 'void' , 0 , False , True , (111, 74, 0) ), Label( 'ground' , 6 , 255 , 'void' , 0 , False , True , ( 81, 0, 81) ), Label( 'road' , 7 , 0 , 'flat' , 1 , False , False , (128, 64,128) ), Label( 'sidewalk' , 8 , 1 , 'flat' , 1 , False , False , (244, 35,232) ), Label( 'parking' , 9 , 255 , 'flat' , 1 , False , True , (250,170,160) ), Label( 'rail track' , 10 , 255 , 'flat' , 1 , False , True , (230,150,140) ), Label( 'building' , 11 , 2 , 'construction' , 2 , False , False , ( 70, 70, 70) ), Label( 'wall' , 12 , 3 , 'construction' , 2 , False , False , (102,102,156) ), Label( 'fence' , 13 , 4 , 'construction' , 2 , False , False , (190,153,153) ), Label( 'guard rail' , 14 , 255 , 'construction' , 2 , False , True , (180,165,180) ), Label( 'bridge' , 15 , 255 , 'construction' , 2 , False , True , (150,100,100) ), Label( 'tunnel' , 16 , 255 , 'construction' , 2 , False , True , (150,120, 90) ), Label( 'pole' , 17 , 5 , 'object' , 3 , False , False , (153,153,153) ), Label( 'polegroup' , 18 , 255 , 'object' , 3 , False , True , (153,153,153) ), Label( 'traffic light' , 19 , 6 , 'object' , 3 , False , False , (250,170, 30) ), Label( 'traffic sign' , 20 , 7 , 'object' , 3 , False , False , (220,220, 0) ), Label( 'vegetation' , 21 , 8 , 'nature' , 4 , False , False , (107,142, 35) ), Label( 'terrain' , 22 , 9 , 'nature' , 4 , False , False , (152,251,152) ), Label( 'sky' , 23 , 10 , 'sky' , 5 , False , False , ( 70,130,180) ), Label( 'person' , 24 , 11 , 'human' , 6 , True , False , (220, 20, 60) ), Label( 'rider' , 25 , 12 , 'human' , 6 , True , False , (255, 0, 0) ), Label( 'car' , 26 , 13 , 'vehicle' , 7 , True , False , ( 0, 0,142) ), Label( 'truck' , 27 , 14 , 'vehicle' , 7 , True , False , ( 0, 0, 70) ), Label( 'bus' , 28 , 15 , 'vehicle' , 7 , True , False , ( 0, 60,100) ), Label( 'caravan' , 29 , 255 , 'vehicle' , 7 , True , True , ( 0, 0, 90) ), Label( 'trailer' , 30 , 255 , 'vehicle' , 7 , True , True , ( 0, 0,110) ), Label( 'train' , 31 , 16 , 'vehicle' , 7 , True , False , ( 0, 80,100) ), Label( 'motorcycle' , 32 , 17 , 'vehicle' , 7 , True , False , ( 0, 0,230) ), Label( 'bicycle' , 33 , 18 , 'vehicle' , 7 , True , False , (119, 11, 32) ), Label( 'license plate' , -1 , -1 , 'vehicle' , 7 , False , True , ( 0, 0,142) ), Label( 'lane marking' , 34 , 19 , 'vehicle' , 1 , False , True , (192, 64,192) ), ] #-------------------------------------------------------------------------------- # Create dictionaries for a fast lookup #-------------------------------------------------------------------------------- # Please refer to the main method below for example usages! # name to label object name2label = { label.name : label for label in labels } # id to label object id2label = { label.id : label for label in labels } # trainId to label object trainId2label = { label.trainId : label for label in reversed(labels) } # category to list of label objects category2labels = {} for label in labels: category = label.category if category in category2labels: category2labels[category].append(label) else: category2labels[category] = [label] #-------------------------------------------------------------------------------- # Assure single instance name #-------------------------------------------------------------------------------- # returns the label name that describes a single instance (if possible) # e.g. input | output # ---------------------- # car | car # cargroup | car # foo | None # foogroup | None # skygroup | None def assureSingleInstanceName( name ): # if the name is known, it is not a group if name in name2label: return name # test if the name actually denotes a group if not name.endswith("group"): return None # remove group name = name[:-len("group")] # test if the new name exists if not name in name2label: return None # test if the new name denotes a label that actually has instances if not name2label[name].hasInstances: return None # all good then return name #-------------------------------------------------------------------------------- # Main for testing #-------------------------------------------------------------------------------- # just a dummy main if __name__ == "__main__": # Print all the labels print("List of cityscapes labels:") print("") print(" {:>21} | {:>3} | {:>7} | {:>14} | {:>10} | {:>12} | {:>12}".format( 'name', 'id', 'trainId', 'category', 'categoryId', 'hasInstances', 'ignoreInEval' )) print(" " + ('-' * 98)) for label in labels: print(" {:>21} | {:>3} | {:>7} | {:>14} | {:>10} | {:>12} | {:>12}".format( label.name, label.id, label.trainId, label.category, label.categoryId, label.hasInstances, label.ignoreInEval )) print("") print("Example usages:") # Map from name to label name = 'car' id = name2label[name].id print("ID of label '{name}': {id}".format( name=name, id=id )) # Map from ID to label category = id2label[id].category print("Category of label with ID '{id}': {category}".format( id=id, category=category )) # Map from trainID to label trainId = 0 name = trainId2label[trainId].name print("Name of label with trainID '{id}': {name}".format( id=trainId, name=name ))
58.617486
199
0.430223
from collections import namedtuple Label = namedtuple( 'Label' , [ 'name' , 'id' , 'trainId' , 'category' , 'categoryId' , 'hasInstances', 'ignoreInEval', 'color' , ] ) labels = [ Label( 'unlabeled' , 0 , 255 , 'void' , 0 , False , True , ( 0, 0, 0) ), Label( 'ego vehicle' , 1 , 255 , 'void' , 0 , False , True , ( 0, 0, 0) ), Label( 'rectification border' , 2 , 255 , 'void' , 0 , False , True , ( 0, 0, 0) ), Label( 'out of roi' , 3 , 255 , 'void' , 0 , False , True , ( 0, 0, 0) ), Label( 'static' , 4 , 255 , 'void' , 0 , False , True , ( 0, 0, 0) ), Label( 'dynamic' , 5 , 255 , 'void' , 0 , False , True , (111, 74, 0) ), Label( 'ground' , 6 , 255 , 'void' , 0 , False , True , ( 81, 0, 81) ), Label( 'road' , 7 , 0 , 'flat' , 1 , False , False , (128, 64,128) ), Label( 'sidewalk' , 8 , 1 , 'flat' , 1 , False , False , (244, 35,232) ), Label( 'parking' , 9 , 255 , 'flat' , 1 , False , True , (250,170,160) ), Label( 'rail track' , 10 , 255 , 'flat' , 1 , False , True , (230,150,140) ), Label( 'building' , 11 , 2 , 'construction' , 2 , False , False , ( 70, 70, 70) ), Label( 'wall' , 12 , 3 , 'construction' , 2 , False , False , (102,102,156) ), Label( 'fence' , 13 , 4 , 'construction' , 2 , False , False , (190,153,153) ), Label( 'guard rail' , 14 , 255 , 'construction' , 2 , False , True , (180,165,180) ), Label( 'bridge' , 15 , 255 , 'construction' , 2 , False , True , (150,100,100) ), Label( 'tunnel' , 16 , 255 , 'construction' , 2 , False , True , (150,120, 90) ), Label( 'pole' , 17 , 5 , 'object' , 3 , False , False , (153,153,153) ), Label( 'polegroup' , 18 , 255 , 'object' , 3 , False , True , (153,153,153) ), Label( 'traffic light' , 19 , 6 , 'object' , 3 , False , False , (250,170, 30) ), Label( 'traffic sign' , 20 , 7 , 'object' , 3 , False , False , (220,220, 0) ), Label( 'vegetation' , 21 , 8 , 'nature' , 4 , False , False , (107,142, 35) ), Label( 'terrain' , 22 , 9 , 'nature' , 4 , False , False , (152,251,152) ), Label( 'sky' , 23 , 10 , 'sky' , 5 , False , False , ( 70,130,180) ), Label( 'person' , 24 , 11 , 'human' , 6 , True , False , (220, 20, 60) ), Label( 'rider' , 25 , 12 , 'human' , 6 , True , False , (255, 0, 0) ), Label( 'car' , 26 , 13 , 'vehicle' , 7 , True , False , ( 0, 0,142) ), Label( 'truck' , 27 , 14 , 'vehicle' , 7 , True , False , ( 0, 0, 70) ), Label( 'bus' , 28 , 15 , 'vehicle' , 7 , True , False , ( 0, 60,100) ), Label( 'caravan' , 29 , 255 , 'vehicle' , 7 , True , True , ( 0, 0, 90) ), Label( 'trailer' , 30 , 255 , 'vehicle' , 7 , True , True , ( 0, 0,110) ), Label( 'train' , 31 , 16 , 'vehicle' , 7 , True , False , ( 0, 80,100) ), Label( 'motorcycle' , 32 , 17 , 'vehicle' , 7 , True , False , ( 0, 0,230) ), Label( 'bicycle' , 33 , 18 , 'vehicle' , 7 , True , False , (119, 11, 32) ), Label( 'license plate' , -1 , -1 , 'vehicle' , 7 , False , True , ( 0, 0,142) ), Label( 'lane marking' , 34 , 19 , 'vehicle' , 1 , False , True , (192, 64,192) ), ] name2label = { label.name : label for label in labels } id2label = { label.id : label for label in labels } trainId2label = { label.trainId : label for label in reversed(labels) } category2labels = {} for label in labels: category = label.category if category in category2labels: category2labels[category].append(label) else: category2labels[category] = [label] def assureSingleInstanceName( name ): if name in name2label: return name if not name.endswith("group"): return None name = name[:-len("group")] if not name in name2label: return None if not name2label[name].hasInstances: return None return name if __name__ == "__main__": print("List of cityscapes labels:") print("") print(" {:>21} | {:>3} | {:>7} | {:>14} | {:>10} | {:>12} | {:>12}".format( 'name', 'id', 'trainId', 'category', 'categoryId', 'hasInstances', 'ignoreInEval' )) print(" " + ('-' * 98)) for label in labels: print(" {:>21} | {:>3} | {:>7} | {:>14} | {:>10} | {:>12} | {:>12}".format( label.name, label.id, label.trainId, label.category, label.categoryId, label.hasInstances, label.ignoreInEval )) print("") print("Example usages:") name = 'car' id = name2label[name].id print("ID of label '{name}': {id}".format( name=name, id=id )) category = id2label[id].category print("Category of label with ID '{id}': {category}".format( id=id, category=category )) trainId = 0 name = trainId2label[trainId].name print("Name of label with trainID '{id}': {name}".format( id=trainId, name=name ))
true
true
f717a7d323d2826aa7fc0c90ce4ba34258907b10
1,050
py
Python
0301-0400/0391-Perfect Rectangle/0391-Perfect Rectangle.py
jiadaizhao/LeetCode
4ddea0a532fe7c5d053ffbd6870174ec99fc2d60
[ "MIT" ]
49
2018-05-05T02:53:10.000Z
2022-03-30T12:08:09.000Z
0301-0400/0391-Perfect Rectangle/0391-Perfect Rectangle.py
jolly-fellow/LeetCode
ab20b3ec137ed05fad1edda1c30db04ab355486f
[ "MIT" ]
11
2017-12-15T22:31:44.000Z
2020-10-02T12:42:49.000Z
0301-0400/0391-Perfect Rectangle/0391-Perfect Rectangle.py
jolly-fellow/LeetCode
ab20b3ec137ed05fad1edda1c30db04ab355486f
[ "MIT" ]
28
2017-12-05T10:56:51.000Z
2022-01-26T18:18:27.000Z
import math class Solution: def isRectangleCover(self, rectangles: 'List[List[int]]') -> 'bool': area = 0 x1 = y1 = math.inf x2 = y2 = -math.inf table = set() for rec in rectangles: x1 = min(x1, rec[0]) y1 = min(y1, rec[1]) x2 = max(x2, rec[2]) y2 = max(y2, rec[3]) area += (rec[2] - rec[0])*(rec[3] - rec[1]) points = ((rec[0], rec[1]), (rec[0], rec[3]), (rec[2], rec[1]), (rec[2], rec[3])) points = (str(p1) + '_' + str(p2) for p1, p2 in points) for point in points: if point in table: table.remove(point) else: table.add(point) return (len(table) == 4 and str(x1) + '_' + str(y1) in table and str(x1) + '_' + str(y2) in table and str(x2) + '_' + str(y1) in table and str(x2) + '_' + str(y2) in table and area == (x2 - x1)*(y2 - y1))
37.5
93
0.414286
import math class Solution: def isRectangleCover(self, rectangles: 'List[List[int]]') -> 'bool': area = 0 x1 = y1 = math.inf x2 = y2 = -math.inf table = set() for rec in rectangles: x1 = min(x1, rec[0]) y1 = min(y1, rec[1]) x2 = max(x2, rec[2]) y2 = max(y2, rec[3]) area += (rec[2] - rec[0])*(rec[3] - rec[1]) points = ((rec[0], rec[1]), (rec[0], rec[3]), (rec[2], rec[1]), (rec[2], rec[3])) points = (str(p1) + '_' + str(p2) for p1, p2 in points) for point in points: if point in table: table.remove(point) else: table.add(point) return (len(table) == 4 and str(x1) + '_' + str(y1) in table and str(x1) + '_' + str(y2) in table and str(x2) + '_' + str(y1) in table and str(x2) + '_' + str(y2) in table and area == (x2 - x1)*(y2 - y1))
true
true
f717a8e5702adf2484d162a384d9cd7e1c5d590d
2,944
py
Python
tests/test_sftp.py
lfbos/qftplib
2a1b79c7f36cc2dfd139a7a3d179fb23f7c6dc1f
[ "MIT" ]
null
null
null
tests/test_sftp.py
lfbos/qftplib
2a1b79c7f36cc2dfd139a7a3d179fb23f7c6dc1f
[ "MIT" ]
null
null
null
tests/test_sftp.py
lfbos/qftplib
2a1b79c7f36cc2dfd139a7a3d179fb23f7c6dc1f
[ "MIT" ]
null
null
null
import os import tempfile import time import unittest from qftplib.client import FTPClient class FTPTest(unittest.TestCase): host = os.environ.get('SFTP_HOST_TEST') user = os.environ.get('SFTP_USER_TEST') password = os.environ.get('SFTP_PASS_TEST') dir = os.environ.get('SFTP_DIR_TEST') port = 22 def test_name(self): with FTPClient(self.host, self.user, self.password, port=self.port, protocol='sftp')as sftp: assert str(sftp) == f'<FTPClient({self.host}, {self.user}, xxxx, port = {self.port}, protocol = sftp)>' def test_listdir(self): with FTPClient(self.host, self.user, self.password, port=self.port, protocol='sftp')as sftp: directory_files = sftp.listdir(self.dir) assert len(directory_files) > 0 def test_pwd_chdir(self): with FTPClient(self.host, self.user, self.password, port=self.port, protocol='sftp')as sftp: sftp.chdir(self.dir) assert sftp.pwd() == f'/home/{self.user}/{self.dir}' def test_rmdir_mkdir(self): with FTPClient(self.host, self.user, self.password, port=self.port, protocol='sftp')as sftp: sftp.chdir(self.dir) new_dir = str(int(time.time())) sftp.mkdir(new_dir) files = sftp.listdir('.') assert f'{new_dir}' in files sftp.rmdir(f'/home/{self.user}/{self.dir}/{new_dir}') files = sftp.listdir('.') assert f'{new_dir}' not in files def test_rename(self): with FTPClient(self.host, self.user, self.password, port=self.port, protocol='sftp')as sftp: sftp.chdir(self.dir) new_dir = str(int(time.time())) sftp.mkdir(new_dir) sftp.rename(f'/home/{self.user}/{self.dir}/{new_dir}', f'/home/{self.user}/{self.dir}/{new_dir}_renamed') files = sftp.listdir('.') assert f'{new_dir}_renamed' in files sftp.rmdir(f'/home/{self.user}/{self.dir}/{new_dir}_renamed') def test_put_delete(self): with FTPClient(self.host, self.user, self.password, port=self.port, protocol='sftp')as sftp, tempfile.NamedTemporaryFile() as f: remotepath = os.path.join(self.dir, os.path.basename(f.name)) sftp.put(f.name, remotepath) sftp.delete(remotepath) files = sftp.listdir(self.dir) assert remotepath not in files def test_get(self): with FTPClient(self.host, self.user, self.password, port=self.port, protocol='sftp')as sftp, tempfile.NamedTemporaryFile(mode='w') as f: files = sftp.listdir(self.dir) filename = next((f for f in files if f.endswith('.csv') or f.endswith('.txt')), None) sftp.get(f'/home/{self.user}/{self.dir}/{filename}', f.name) assert os.path.exists(f.name) assert os.path.isfile(f.name)
35.047619
117
0.605978
import os import tempfile import time import unittest from qftplib.client import FTPClient class FTPTest(unittest.TestCase): host = os.environ.get('SFTP_HOST_TEST') user = os.environ.get('SFTP_USER_TEST') password = os.environ.get('SFTP_PASS_TEST') dir = os.environ.get('SFTP_DIR_TEST') port = 22 def test_name(self): with FTPClient(self.host, self.user, self.password, port=self.port, protocol='sftp')as sftp: assert str(sftp) == f'<FTPClient({self.host}, {self.user}, xxxx, port = {self.port}, protocol = sftp)>' def test_listdir(self): with FTPClient(self.host, self.user, self.password, port=self.port, protocol='sftp')as sftp: directory_files = sftp.listdir(self.dir) assert len(directory_files) > 0 def test_pwd_chdir(self): with FTPClient(self.host, self.user, self.password, port=self.port, protocol='sftp')as sftp: sftp.chdir(self.dir) assert sftp.pwd() == f'/home/{self.user}/{self.dir}' def test_rmdir_mkdir(self): with FTPClient(self.host, self.user, self.password, port=self.port, protocol='sftp')as sftp: sftp.chdir(self.dir) new_dir = str(int(time.time())) sftp.mkdir(new_dir) files = sftp.listdir('.') assert f'{new_dir}' in files sftp.rmdir(f'/home/{self.user}/{self.dir}/{new_dir}') files = sftp.listdir('.') assert f'{new_dir}' not in files def test_rename(self): with FTPClient(self.host, self.user, self.password, port=self.port, protocol='sftp')as sftp: sftp.chdir(self.dir) new_dir = str(int(time.time())) sftp.mkdir(new_dir) sftp.rename(f'/home/{self.user}/{self.dir}/{new_dir}', f'/home/{self.user}/{self.dir}/{new_dir}_renamed') files = sftp.listdir('.') assert f'{new_dir}_renamed' in files sftp.rmdir(f'/home/{self.user}/{self.dir}/{new_dir}_renamed') def test_put_delete(self): with FTPClient(self.host, self.user, self.password, port=self.port, protocol='sftp')as sftp, tempfile.NamedTemporaryFile() as f: remotepath = os.path.join(self.dir, os.path.basename(f.name)) sftp.put(f.name, remotepath) sftp.delete(remotepath) files = sftp.listdir(self.dir) assert remotepath not in files def test_get(self): with FTPClient(self.host, self.user, self.password, port=self.port, protocol='sftp')as sftp, tempfile.NamedTemporaryFile(mode='w') as f: files = sftp.listdir(self.dir) filename = next((f for f in files if f.endswith('.csv') or f.endswith('.txt')), None) sftp.get(f'/home/{self.user}/{self.dir}/{filename}', f.name) assert os.path.exists(f.name) assert os.path.isfile(f.name)
true
true
f717a96bf2f36b05dfb39bd231a309d8afe03392
723
py
Python
django-rest-framework-quick-start/tutorial/quickstart/views.py
madhikarma/python-django-demo
d18ca7e25d01f12813cd6e011ae253e792ac2d03
[ "MIT" ]
null
null
null
django-rest-framework-quick-start/tutorial/quickstart/views.py
madhikarma/python-django-demo
d18ca7e25d01f12813cd6e011ae253e792ac2d03
[ "MIT" ]
null
null
null
django-rest-framework-quick-start/tutorial/quickstart/views.py
madhikarma/python-django-demo
d18ca7e25d01f12813cd6e011ae253e792ac2d03
[ "MIT" ]
null
null
null
from django.contrib.auth.models import User, Group from rest_framework import viewsets from rest_framework import permissions from tutorial.quickstart.serializers import UserSerializer, GroupSerializer class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer permission_classes = [permissions.IsAuthenticated] class GroupViewSet(viewsets.ModelViewSet): """ API endpoint that allows groups to be viewed or edited. """ queryset = Group.objects.all() serializer_class = GroupSerializer permission_classes = [permissions.IsAuthenticated]
31.434783
75
0.763485
from django.contrib.auth.models import User, Group from rest_framework import viewsets from rest_framework import permissions from tutorial.quickstart.serializers import UserSerializer, GroupSerializer class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer permission_classes = [permissions.IsAuthenticated] class GroupViewSet(viewsets.ModelViewSet): queryset = Group.objects.all() serializer_class = GroupSerializer permission_classes = [permissions.IsAuthenticated]
true
true
f717a97ac0ae713afc793d70fe3a8c677d331876
767
py
Python
yatube/posts/migrations/0004_auto_20210318_1753.py
Rusich90/yatube
8593443fe64b0422b2ebbedc9966d347a668e0a3
[ "BSD-3-Clause" ]
1
2021-06-06T11:15:57.000Z
2021-06-06T11:15:57.000Z
yatube/posts/migrations/0004_auto_20210318_1753.py
Rusich90/yatube
8593443fe64b0422b2ebbedc9966d347a668e0a3
[ "BSD-3-Clause" ]
null
null
null
yatube/posts/migrations/0004_auto_20210318_1753.py
Rusich90/yatube
8593443fe64b0422b2ebbedc9966d347a668e0a3
[ "BSD-3-Clause" ]
1
2021-06-06T11:15:58.000Z
2021-06-06T11:15:58.000Z
# Generated by Django 2.2 on 2021-03-18 17:53 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('posts', '0003_auto_20210307_1711'), ] operations = [ migrations.AlterField( model_name='post', name='group', field=models.ForeignKey(blank=True, help_text='Выберите группу для поста (необязательно)', null=True, on_delete=django.db.models.deletion.CASCADE, related_name='posts', to='posts.Group', verbose_name='Группа'), ), migrations.AlterField( model_name='post', name='text', field=models.TextField(help_text='Введите текст', verbose_name='Текст'), ), ]
30.68
222
0.636245
from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('posts', '0003_auto_20210307_1711'), ] operations = [ migrations.AlterField( model_name='post', name='group', field=models.ForeignKey(blank=True, help_text='Выберите группу для поста (необязательно)', null=True, on_delete=django.db.models.deletion.CASCADE, related_name='posts', to='posts.Group', verbose_name='Группа'), ), migrations.AlterField( model_name='post', name='text', field=models.TextField(help_text='Введите текст', verbose_name='Текст'), ), ]
true
true
f717aa4a2dd6cc01429db2f797d20ef18a428275
8,080
py
Python
neutron/services/trunk/rpc/server.py
knodir/neutron
ac4e28478ac8a8a0c9f5c5785f6a6bcf532c66b8
[ "Apache-2.0" ]
null
null
null
neutron/services/trunk/rpc/server.py
knodir/neutron
ac4e28478ac8a8a0c9f5c5785f6a6bcf532c66b8
[ "Apache-2.0" ]
5
2019-08-14T06:46:03.000Z
2021-12-13T20:01:25.000Z
neutron/services/trunk/rpc/server.py
knodir/neutron
ac4e28478ac8a8a0c9f5c5785f6a6bcf532c66b8
[ "Apache-2.0" ]
2
2020-03-15T01:24:15.000Z
2020-07-22T20:34:26.000Z
# Copyright 2016 Hewlett Packard Enterprise Development LP # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import collections from neutron_lib.api.definitions import portbindings from neutron_lib.db import api as db_api from neutron_lib.plugins import directory from neutron_lib import rpc as n_rpc from oslo_log import helpers as log_helpers from oslo_log import log as logging import oslo_messaging from neutron.api.rpc.callbacks import events from neutron.api.rpc.callbacks.producer import registry from neutron.api.rpc.callbacks import resources from neutron.api.rpc.handlers import resources_rpc from neutron.objects import trunk as trunk_objects from neutron.services.trunk import constants as trunk_consts from neutron.services.trunk import exceptions as trunk_exc from neutron.services.trunk.rpc import constants LOG = logging.getLogger(__name__) # This module contains stub (client-side) and skeleton (server-side) # proxy code that executes in the Neutron server process space. This # is needed if any of the trunk service plugin drivers has a remote # component (e.g. agent), that needs to communicate with the Neutron # Server. # The Server side exposes the following remote methods: # # - lookup method to retrieve trunk details: used by the agent to learn # about the trunk. # - update methods for trunk and its subports: used by the agent to # inform the server about local trunk status changes. # # For agent-side stub and skeleton proxy code, please look at agent.py def trunk_by_port_provider(resource, port_id, context, **kwargs): """Provider callback to supply trunk information by parent port.""" return trunk_objects.Trunk.get_object(context, port_id=port_id) class TrunkSkeleton(object): """Skeleton proxy code for agent->server communication.""" # API version history: # 1.0 Initial version target = oslo_messaging.Target(version='1.0', namespace=constants.TRUNK_BASE_NAMESPACE) _core_plugin = None def __init__(self): # Used to provide trunk lookups for the agent. registry.provide(trunk_by_port_provider, resources.TRUNK) self._connection = n_rpc.Connection() self._connection.create_consumer( constants.TRUNK_BASE_TOPIC, [self], fanout=False) self._connection.consume_in_threads() @property def core_plugin(self): if not self._core_plugin: self._core_plugin = directory.get_plugin() return self._core_plugin @log_helpers.log_method_call def update_subport_bindings(self, context, subports): """Update subport bindings to match trunk host binding.""" el = context.elevated() ports_by_trunk_id = collections.defaultdict(list) updated_ports = collections.defaultdict(list) for s in subports: ports_by_trunk_id[s['trunk_id']].append(s['port_id']) for trunk_id, subport_ids in ports_by_trunk_id.items(): trunk = trunk_objects.Trunk.get_object(el, id=trunk_id) if not trunk: LOG.debug("Trunk not found. id: %s", trunk_id) continue trunk_updated_ports = self._process_trunk_subport_bindings( el, trunk, subport_ids) updated_ports[trunk.id].extend(trunk_updated_ports) return updated_ports def update_trunk_status(self, context, trunk_id, status): """Update the trunk status to reflect outcome of data plane wiring.""" with db_api.autonested_transaction(context.session): trunk = trunk_objects.Trunk.get_object(context, id=trunk_id) if trunk: trunk.update(status=status) def _process_trunk_subport_bindings(self, context, trunk, port_ids): """Process port bindings for subports on the given trunk.""" updated_ports = [] trunk_port_id = trunk.port_id trunk_port = self.core_plugin.get_port(context, trunk_port_id) trunk_host = trunk_port.get(portbindings.HOST_ID) # NOTE(status_police) Set the trunk in BUILD state before processing # subport bindings. The trunk will stay in BUILD state until an # attempt has been made to bind all subports passed here and the # agent acknowledges the operation was successful. trunk.update(status=trunk_consts.BUILD_STATUS) for port_id in port_ids: try: updated_port = self._handle_port_binding(context, port_id, trunk, trunk_host) # NOTE(fitoduarte): consider trimming down the content # of the port data structure. updated_ports.append(updated_port) except trunk_exc.SubPortBindingError as e: LOG.error("Failed to bind subport: %s", e) # NOTE(status_police) The subport binding has failed in a # manner in which we cannot proceed and the user must take # action to bring the trunk back to a sane state. trunk.update(status=trunk_consts.ERROR_STATUS) return [] except Exception as e: msg = ("Failed to bind subport port %(port)s on trunk " "%(trunk)s: %(exc)s") LOG.error(msg, {'port': port_id, 'trunk': trunk.id, 'exc': e}) if len(port_ids) != len(updated_ports): trunk.update(status=trunk_consts.DEGRADED_STATUS) return updated_ports def _handle_port_binding(self, context, port_id, trunk, trunk_host): """Bind the given port to the given host. :param context: The context to use for the operation :param port_id: The UUID of the port to be bound :param trunk: The trunk that the given port belongs to :param trunk_host: The host to bind the given port to """ port = self.core_plugin.update_port( context, port_id, {'port': {portbindings.HOST_ID: trunk_host, 'device_owner': trunk_consts.TRUNK_SUBPORT_OWNER}}) vif_type = port.get(portbindings.VIF_TYPE) if vif_type == portbindings.VIF_TYPE_BINDING_FAILED: raise trunk_exc.SubPortBindingError(port_id=port_id, trunk_id=trunk.id) return port class TrunkStub(object): """Stub proxy code for server->agent communication.""" def __init__(self): self._resource_rpc = resources_rpc.ResourcesPushRpcApi() @log_helpers.log_method_call def trunk_created(self, context, trunk): """Tell the agent about a trunk being created.""" self._resource_rpc.push(context, [trunk], events.CREATED) @log_helpers.log_method_call def trunk_deleted(self, context, trunk): """Tell the agent about a trunk being deleted.""" self._resource_rpc.push(context, [trunk], events.DELETED) @log_helpers.log_method_call def subports_added(self, context, subports): """Tell the agent about new subports to add.""" self._resource_rpc.push(context, subports, events.CREATED) @log_helpers.log_method_call def subports_deleted(self, context, subports): """Tell the agent about existing subports to remove.""" self._resource_rpc.push(context, subports, events.DELETED)
41.865285
78
0.664604
import collections from neutron_lib.api.definitions import portbindings from neutron_lib.db import api as db_api from neutron_lib.plugins import directory from neutron_lib import rpc as n_rpc from oslo_log import helpers as log_helpers from oslo_log import log as logging import oslo_messaging from neutron.api.rpc.callbacks import events from neutron.api.rpc.callbacks.producer import registry from neutron.api.rpc.callbacks import resources from neutron.api.rpc.handlers import resources_rpc from neutron.objects import trunk as trunk_objects from neutron.services.trunk import constants as trunk_consts from neutron.services.trunk import exceptions as trunk_exc from neutron.services.trunk.rpc import constants LOG = logging.getLogger(__name__) def trunk_by_port_provider(resource, port_id, context, **kwargs): return trunk_objects.Trunk.get_object(context, port_id=port_id) class TrunkSkeleton(object): target = oslo_messaging.Target(version='1.0', namespace=constants.TRUNK_BASE_NAMESPACE) _core_plugin = None def __init__(self): registry.provide(trunk_by_port_provider, resources.TRUNK) self._connection = n_rpc.Connection() self._connection.create_consumer( constants.TRUNK_BASE_TOPIC, [self], fanout=False) self._connection.consume_in_threads() @property def core_plugin(self): if not self._core_plugin: self._core_plugin = directory.get_plugin() return self._core_plugin @log_helpers.log_method_call def update_subport_bindings(self, context, subports): el = context.elevated() ports_by_trunk_id = collections.defaultdict(list) updated_ports = collections.defaultdict(list) for s in subports: ports_by_trunk_id[s['trunk_id']].append(s['port_id']) for trunk_id, subport_ids in ports_by_trunk_id.items(): trunk = trunk_objects.Trunk.get_object(el, id=trunk_id) if not trunk: LOG.debug("Trunk not found. id: %s", trunk_id) continue trunk_updated_ports = self._process_trunk_subport_bindings( el, trunk, subport_ids) updated_ports[trunk.id].extend(trunk_updated_ports) return updated_ports def update_trunk_status(self, context, trunk_id, status): with db_api.autonested_transaction(context.session): trunk = trunk_objects.Trunk.get_object(context, id=trunk_id) if trunk: trunk.update(status=status) def _process_trunk_subport_bindings(self, context, trunk, port_ids): updated_ports = [] trunk_port_id = trunk.port_id trunk_port = self.core_plugin.get_port(context, trunk_port_id) trunk_host = trunk_port.get(portbindings.HOST_ID) trunk.update(status=trunk_consts.BUILD_STATUS) for port_id in port_ids: try: updated_port = self._handle_port_binding(context, port_id, trunk, trunk_host) updated_ports.append(updated_port) except trunk_exc.SubPortBindingError as e: LOG.error("Failed to bind subport: %s", e) trunk.update(status=trunk_consts.ERROR_STATUS) return [] except Exception as e: msg = ("Failed to bind subport port %(port)s on trunk " "%(trunk)s: %(exc)s") LOG.error(msg, {'port': port_id, 'trunk': trunk.id, 'exc': e}) if len(port_ids) != len(updated_ports): trunk.update(status=trunk_consts.DEGRADED_STATUS) return updated_ports def _handle_port_binding(self, context, port_id, trunk, trunk_host): port = self.core_plugin.update_port( context, port_id, {'port': {portbindings.HOST_ID: trunk_host, 'device_owner': trunk_consts.TRUNK_SUBPORT_OWNER}}) vif_type = port.get(portbindings.VIF_TYPE) if vif_type == portbindings.VIF_TYPE_BINDING_FAILED: raise trunk_exc.SubPortBindingError(port_id=port_id, trunk_id=trunk.id) return port class TrunkStub(object): def __init__(self): self._resource_rpc = resources_rpc.ResourcesPushRpcApi() @log_helpers.log_method_call def trunk_created(self, context, trunk): self._resource_rpc.push(context, [trunk], events.CREATED) @log_helpers.log_method_call def trunk_deleted(self, context, trunk): self._resource_rpc.push(context, [trunk], events.DELETED) @log_helpers.log_method_call def subports_added(self, context, subports): self._resource_rpc.push(context, subports, events.CREATED) @log_helpers.log_method_call def subports_deleted(self, context, subports): self._resource_rpc.push(context, subports, events.DELETED)
true
true
f717aaa141f06ebfe41236718707dffb420687d5
11,262
py
Python
mars/worker/service.py
wdkwyf/mars
3f750e360e64380eab779301a5103994d4886b6a
[ "Apache-2.0" ]
null
null
null
mars/worker/service.py
wdkwyf/mars
3f750e360e64380eab779301a5103994d4886b6a
[ "Apache-2.0" ]
null
null
null
mars/worker/service.py
wdkwyf/mars
3f750e360e64380eab779301a5103994d4886b6a
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # Copyright 1999-2018 Alibaba Group Holding Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import logging try: from pyarrow import plasma except ImportError: # pragma: no cover plasma = None from ..config import options from .. import resource from ..utils import parse_readable_size, readable_size from ..compat import six from .status import StatusActor from .quota import QuotaActor, MemQuotaActor from .chunkholder import ChunkHolderActor from .dispatcher import DispatchActor from .events import EventsActor from .execution import ExecutionActor from .calc import CpuCalcActor from .transfer import ReceiverActor, SenderActor from .prochelper import ProcessHelperActor from .transfer import ResultSenderActor from .spill import SpillActor from .utils import WorkerClusterInfoActor logger = logging.getLogger(__name__) class WorkerService(object): def __init__(self, **kwargs): self._plasma_store = None self._chunk_holder_ref = None self._task_queue_ref = None self._mem_quota_ref = None self._dispatch_ref = None self._events_ref = None self._status_ref = None self._execution_ref = None self._daemon_ref = None self._cluster_info_ref = None self._cpu_calc_actors = [] self._sender_actors = [] self._receiver_actors = [] self._spill_actors = [] self._process_helper_actors = [] self._result_sender_ref = None self._advertise_addr = kwargs.pop('advertise_addr', None) self._n_cpu_process = int(kwargs.pop('n_cpu_process', None) or resource.cpu_count()) self._n_net_process = int(kwargs.pop('n_net_process', None) or '1') self._spill_dirs = kwargs.pop('spill_dirs', None) if self._spill_dirs: if isinstance(self._spill_dirs, six.string_types): from .spill import parse_spill_dirs self._spill_dirs = options.worker.spill_directory = parse_spill_dirs(self._spill_dirs) else: options.worker.spill_directory = self._spill_dirs else: self._spill_dirs = options.worker.spill_directory = [] options.worker.disk_compression = kwargs.pop('disk_compression', None) or \ options.worker.disk_compression options.worker.transfer_compression = kwargs.pop('transfer_compression', None) or \ options.worker.transfer_compression self._total_mem = kwargs.pop('total_mem', None) self._cache_mem_limit = kwargs.pop('cache_mem_limit', None) self._soft_mem_limit = kwargs.pop('soft_mem_limit', None) or '80%' self._hard_mem_limit = kwargs.pop('hard_mem_limit', None) or '90%' self._ignore_avail_mem = kwargs.pop('ignore_avail_mem', None) or False self._min_mem_size = kwargs.pop('min_mem_size', None) or 128 * 1024 ** 2 self._soft_quota_limit = self._soft_mem_limit self._calc_memory_limits() if kwargs: # pragma: no cover raise TypeError('Keyword arguments %r cannot be recognized.' % ', '.join(kwargs)) @property def n_process(self): return 1 + self._n_cpu_process + self._n_net_process + (1 if self._spill_dirs else 0) def _calc_memory_limits(self): def _calc_size_limit(limit_str, total_size): if limit_str is None: return None if isinstance(limit_str, int): return limit_str mem_limit, is_percent = parse_readable_size(limit_str) if is_percent: return int(total_size * mem_limit) else: return int(mem_limit) mem_stats = resource.virtual_memory() if self._total_mem: self._total_mem = _calc_size_limit(self._total_mem, mem_stats.total) else: self._total_mem = mem_stats.total self._min_mem_size = _calc_size_limit(self._min_mem_size, self._total_mem) self._hard_mem_limit = _calc_size_limit(self._hard_mem_limit, self._total_mem) self._cache_mem_limit = _calc_size_limit(self._cache_mem_limit, self._total_mem) if self._cache_mem_limit is None: self._cache_mem_limit = mem_stats.free // 2 self._soft_mem_limit = _calc_size_limit(self._soft_mem_limit, self._total_mem) actual_used = self._total_mem - mem_stats.available if self._ignore_avail_mem: self._soft_quota_limit = self._soft_mem_limit else: self._soft_quota_limit = self._soft_mem_limit - self._cache_mem_limit - actual_used if self._soft_quota_limit < self._min_mem_size: raise MemoryError('Memory not enough. soft_limit=%s, cache_limit=%s, used=%s' % tuple(readable_size(k) for k in ( self._soft_mem_limit, self._cache_mem_limit, actual_used))) logger.info('Setting soft limit to %s.', readable_size(self._soft_quota_limit)) def start_plasma(self): self._plasma_store = plasma.start_plasma_store(self._cache_mem_limit) options.worker.plasma_socket, _ = self._plasma_store.__enter__() def start(self, endpoint, pool, distributed=True, discoverer=None, process_start_index=0): # create plasma key mapper from .chunkstore import PlasmaKeyMapActor pool.create_actor(PlasmaKeyMapActor, uid=PlasmaKeyMapActor.default_uid()) # create WorkerClusterInfoActor self._cluster_info_ref = pool.create_actor( WorkerClusterInfoActor, discoverer, uid=WorkerClusterInfoActor.default_uid()) if distributed: # create process daemon from .daemon import WorkerDaemonActor actor_holder = self._daemon_ref = pool.create_actor( WorkerDaemonActor, uid=WorkerDaemonActor.default_uid()) # create StatusActor if ':' not in self._advertise_addr: self._advertise_addr += ':' + endpoint.rsplit(':', 1)[-1] self._status_ref = pool.create_actor( StatusActor, self._advertise_addr, uid=StatusActor.default_uid()) else: # create StatusActor self._status_ref = pool.create_actor( StatusActor, endpoint, uid=StatusActor.default_uid()) actor_holder = pool if self._ignore_avail_mem: # start a QuotaActor instead of MemQuotaActor to avoid memory size detection # for debug purpose only, DON'T USE IN PRODUCTION self._mem_quota_ref = pool.create_actor( QuotaActor, self._soft_mem_limit, uid=MemQuotaActor.default_uid()) else: self._mem_quota_ref = pool.create_actor( MemQuotaActor, self._soft_quota_limit, self._hard_mem_limit, uid=MemQuotaActor.default_uid()) # create ChunkHolderActor self._chunk_holder_ref = pool.create_actor( ChunkHolderActor, self._cache_mem_limit, uid=ChunkHolderActor.default_uid()) # create DispatchActor self._dispatch_ref = pool.create_actor(DispatchActor, uid=DispatchActor.default_uid()) # create EventsActor self._events_ref = pool.create_actor(EventsActor, uid=EventsActor.default_uid()) # create ExecutionActor self._execution_ref = pool.create_actor(ExecutionActor, uid=ExecutionActor.default_uid()) # create CpuCalcActor if not distributed: self._n_cpu_process = pool.cluster_info.n_process - 1 - process_start_index for cpu_id in range(self._n_cpu_process): uid = 'w:%d:mars-calc-%d-%d' % (cpu_id + 1, os.getpid(), cpu_id) actor = actor_holder.create_actor(CpuCalcActor, uid=uid) self._cpu_calc_actors.append(actor) start_pid = 1 + process_start_index + self._n_cpu_process if distributed: # create SenderActor and ReceiverActor for sender_id in range(self._n_net_process): uid = 'w:%d:mars-sender-%d-%d' % (start_pid + sender_id, os.getpid(), sender_id) actor = actor_holder.create_actor(SenderActor, uid=uid) self._sender_actors.append(actor) # Mutable requires ReceiverActor (with LocalClusterSession) for receiver_id in range(2 * self._n_net_process): uid = 'w:%d:mars-receiver-%d-%d' % (start_pid + receiver_id // 2, os.getpid(), receiver_id) actor = actor_holder.create_actor(ReceiverActor, uid=uid) self._receiver_actors.append(actor) # create ProcessHelperActor for proc_id in range(pool.cluster_info.n_process - process_start_index): uid = 'w:%d:mars-process-helper-%d-%d' % (proc_id, os.getpid(), proc_id) actor = actor_holder.create_actor(ProcessHelperActor, uid=uid) self._process_helper_actors.append(actor) # create ResultSenderActor self._result_sender_ref = pool.create_actor(ResultSenderActor, uid=ResultSenderActor.default_uid()) # create SpillActor start_pid = pool.cluster_info.n_process - 1 if options.worker.spill_directory: for spill_id in range(len(options.worker.spill_directory) * 2): uid = 'w:%d:mars-spill-%d-%d' % (start_pid, os.getpid(), spill_id) actor = actor_holder.create_actor(SpillActor, uid=uid) self._spill_actors.append(actor) # worker can be registered when everything is ready self._status_ref.enable_status_upload(_tell=True) def handle_process_down(self, pool, proc_indices): logger.debug('Process %r halt. Trying to recover.', proc_indices) for pid in proc_indices: pool.restart_process(pid) self._daemon_ref.handle_process_down(proc_indices, _tell=True) def stop(self): try: if self._result_sender_ref: self._result_sender_ref.destroy(wait=False) if self._status_ref: self._status_ref.destroy(wait=False) if self._chunk_holder_ref: self._chunk_holder_ref.destroy(wait=False) if self._events_ref: self._events_ref.destroy(wait=False) if self._dispatch_ref: self._dispatch_ref.destroy(wait=False) if self._execution_ref: self._execution_ref.destroy(wait=False) for actor in (self._cpu_calc_actors + self._sender_actors + self._receiver_actors + self._spill_actors + self._process_helper_actors): actor.destroy(wait=False) finally: self._plasma_store.__exit__(None, None, None)
42.659091
109
0.665335
import os import logging try: from pyarrow import plasma except ImportError: plasma = None from ..config import options from .. import resource from ..utils import parse_readable_size, readable_size from ..compat import six from .status import StatusActor from .quota import QuotaActor, MemQuotaActor from .chunkholder import ChunkHolderActor from .dispatcher import DispatchActor from .events import EventsActor from .execution import ExecutionActor from .calc import CpuCalcActor from .transfer import ReceiverActor, SenderActor from .prochelper import ProcessHelperActor from .transfer import ResultSenderActor from .spill import SpillActor from .utils import WorkerClusterInfoActor logger = logging.getLogger(__name__) class WorkerService(object): def __init__(self, **kwargs): self._plasma_store = None self._chunk_holder_ref = None self._task_queue_ref = None self._mem_quota_ref = None self._dispatch_ref = None self._events_ref = None self._status_ref = None self._execution_ref = None self._daemon_ref = None self._cluster_info_ref = None self._cpu_calc_actors = [] self._sender_actors = [] self._receiver_actors = [] self._spill_actors = [] self._process_helper_actors = [] self._result_sender_ref = None self._advertise_addr = kwargs.pop('advertise_addr', None) self._n_cpu_process = int(kwargs.pop('n_cpu_process', None) or resource.cpu_count()) self._n_net_process = int(kwargs.pop('n_net_process', None) or '1') self._spill_dirs = kwargs.pop('spill_dirs', None) if self._spill_dirs: if isinstance(self._spill_dirs, six.string_types): from .spill import parse_spill_dirs self._spill_dirs = options.worker.spill_directory = parse_spill_dirs(self._spill_dirs) else: options.worker.spill_directory = self._spill_dirs else: self._spill_dirs = options.worker.spill_directory = [] options.worker.disk_compression = kwargs.pop('disk_compression', None) or \ options.worker.disk_compression options.worker.transfer_compression = kwargs.pop('transfer_compression', None) or \ options.worker.transfer_compression self._total_mem = kwargs.pop('total_mem', None) self._cache_mem_limit = kwargs.pop('cache_mem_limit', None) self._soft_mem_limit = kwargs.pop('soft_mem_limit', None) or '80%' self._hard_mem_limit = kwargs.pop('hard_mem_limit', None) or '90%' self._ignore_avail_mem = kwargs.pop('ignore_avail_mem', None) or False self._min_mem_size = kwargs.pop('min_mem_size', None) or 128 * 1024 ** 2 self._soft_quota_limit = self._soft_mem_limit self._calc_memory_limits() if kwargs: raise TypeError('Keyword arguments %r cannot be recognized.' % ', '.join(kwargs)) @property def n_process(self): return 1 + self._n_cpu_process + self._n_net_process + (1 if self._spill_dirs else 0) def _calc_memory_limits(self): def _calc_size_limit(limit_str, total_size): if limit_str is None: return None if isinstance(limit_str, int): return limit_str mem_limit, is_percent = parse_readable_size(limit_str) if is_percent: return int(total_size * mem_limit) else: return int(mem_limit) mem_stats = resource.virtual_memory() if self._total_mem: self._total_mem = _calc_size_limit(self._total_mem, mem_stats.total) else: self._total_mem = mem_stats.total self._min_mem_size = _calc_size_limit(self._min_mem_size, self._total_mem) self._hard_mem_limit = _calc_size_limit(self._hard_mem_limit, self._total_mem) self._cache_mem_limit = _calc_size_limit(self._cache_mem_limit, self._total_mem) if self._cache_mem_limit is None: self._cache_mem_limit = mem_stats.free // 2 self._soft_mem_limit = _calc_size_limit(self._soft_mem_limit, self._total_mem) actual_used = self._total_mem - mem_stats.available if self._ignore_avail_mem: self._soft_quota_limit = self._soft_mem_limit else: self._soft_quota_limit = self._soft_mem_limit - self._cache_mem_limit - actual_used if self._soft_quota_limit < self._min_mem_size: raise MemoryError('Memory not enough. soft_limit=%s, cache_limit=%s, used=%s' % tuple(readable_size(k) for k in ( self._soft_mem_limit, self._cache_mem_limit, actual_used))) logger.info('Setting soft limit to %s.', readable_size(self._soft_quota_limit)) def start_plasma(self): self._plasma_store = plasma.start_plasma_store(self._cache_mem_limit) options.worker.plasma_socket, _ = self._plasma_store.__enter__() def start(self, endpoint, pool, distributed=True, discoverer=None, process_start_index=0): from .chunkstore import PlasmaKeyMapActor pool.create_actor(PlasmaKeyMapActor, uid=PlasmaKeyMapActor.default_uid()) self._cluster_info_ref = pool.create_actor( WorkerClusterInfoActor, discoverer, uid=WorkerClusterInfoActor.default_uid()) if distributed: from .daemon import WorkerDaemonActor actor_holder = self._daemon_ref = pool.create_actor( WorkerDaemonActor, uid=WorkerDaemonActor.default_uid()) if ':' not in self._advertise_addr: self._advertise_addr += ':' + endpoint.rsplit(':', 1)[-1] self._status_ref = pool.create_actor( StatusActor, self._advertise_addr, uid=StatusActor.default_uid()) else: self._status_ref = pool.create_actor( StatusActor, endpoint, uid=StatusActor.default_uid()) actor_holder = pool if self._ignore_avail_mem: self._mem_quota_ref = pool.create_actor( QuotaActor, self._soft_mem_limit, uid=MemQuotaActor.default_uid()) else: self._mem_quota_ref = pool.create_actor( MemQuotaActor, self._soft_quota_limit, self._hard_mem_limit, uid=MemQuotaActor.default_uid()) # create ChunkHolderActor self._chunk_holder_ref = pool.create_actor( ChunkHolderActor, self._cache_mem_limit, uid=ChunkHolderActor.default_uid()) # create DispatchActor self._dispatch_ref = pool.create_actor(DispatchActor, uid=DispatchActor.default_uid()) # create EventsActor self._events_ref = pool.create_actor(EventsActor, uid=EventsActor.default_uid()) # create ExecutionActor self._execution_ref = pool.create_actor(ExecutionActor, uid=ExecutionActor.default_uid()) # create CpuCalcActor if not distributed: self._n_cpu_process = pool.cluster_info.n_process - 1 - process_start_index for cpu_id in range(self._n_cpu_process): uid = 'w:%d:mars-calc-%d-%d' % (cpu_id + 1, os.getpid(), cpu_id) actor = actor_holder.create_actor(CpuCalcActor, uid=uid) self._cpu_calc_actors.append(actor) start_pid = 1 + process_start_index + self._n_cpu_process if distributed: # create SenderActor and ReceiverActor for sender_id in range(self._n_net_process): uid = 'w:%d:mars-sender-%d-%d' % (start_pid + sender_id, os.getpid(), sender_id) actor = actor_holder.create_actor(SenderActor, uid=uid) self._sender_actors.append(actor) # Mutable requires ReceiverActor (with LocalClusterSession) for receiver_id in range(2 * self._n_net_process): uid = 'w:%d:mars-receiver-%d-%d' % (start_pid + receiver_id // 2, os.getpid(), receiver_id) actor = actor_holder.create_actor(ReceiverActor, uid=uid) self._receiver_actors.append(actor) # create ProcessHelperActor for proc_id in range(pool.cluster_info.n_process - process_start_index): uid = 'w:%d:mars-process-helper-%d-%d' % (proc_id, os.getpid(), proc_id) actor = actor_holder.create_actor(ProcessHelperActor, uid=uid) self._process_helper_actors.append(actor) # create ResultSenderActor self._result_sender_ref = pool.create_actor(ResultSenderActor, uid=ResultSenderActor.default_uid()) # create SpillActor start_pid = pool.cluster_info.n_process - 1 if options.worker.spill_directory: for spill_id in range(len(options.worker.spill_directory) * 2): uid = 'w:%d:mars-spill-%d-%d' % (start_pid, os.getpid(), spill_id) actor = actor_holder.create_actor(SpillActor, uid=uid) self._spill_actors.append(actor) # worker can be registered when everything is ready self._status_ref.enable_status_upload(_tell=True) def handle_process_down(self, pool, proc_indices): logger.debug('Process %r halt. Trying to recover.', proc_indices) for pid in proc_indices: pool.restart_process(pid) self._daemon_ref.handle_process_down(proc_indices, _tell=True) def stop(self): try: if self._result_sender_ref: self._result_sender_ref.destroy(wait=False) if self._status_ref: self._status_ref.destroy(wait=False) if self._chunk_holder_ref: self._chunk_holder_ref.destroy(wait=False) if self._events_ref: self._events_ref.destroy(wait=False) if self._dispatch_ref: self._dispatch_ref.destroy(wait=False) if self._execution_ref: self._execution_ref.destroy(wait=False) for actor in (self._cpu_calc_actors + self._sender_actors + self._receiver_actors + self._spill_actors + self._process_helper_actors): actor.destroy(wait=False) finally: self._plasma_store.__exit__(None, None, None)
true
true
f717ac92ce24bf53f59cb78906005b06e6b861f3
483
py
Python
final_project/machinetranslation/tests/test_translator.py
BrunoYH/xzceb-flask_eng_fr
a86a32ef56fcae1a8a9e281f17eb73dca05aec10
[ "Apache-2.0" ]
null
null
null
final_project/machinetranslation/tests/test_translator.py
BrunoYH/xzceb-flask_eng_fr
a86a32ef56fcae1a8a9e281f17eb73dca05aec10
[ "Apache-2.0" ]
null
null
null
final_project/machinetranslation/tests/test_translator.py
BrunoYH/xzceb-flask_eng_fr
a86a32ef56fcae1a8a9e281f17eb73dca05aec10
[ "Apache-2.0" ]
null
null
null
import unittest from translator import english_to_french, french_to_english class TestEnglishToFrench(unittest.TestCase): def testE2F(self): self.assertEqual(english_to_french("Hello"), "Bonjour") self.assertNotEqual(english_to_french("Null"), "") class FrenchEnglishToEnglish(unittest.TestCase): def testF2E(self): self.assertEqual(french_to_english("Bonjour"), "Hello") self.assertNotEqual(french_to_english("Null"), "") unittest.main()
30.1875
63
0.73913
import unittest from translator import english_to_french, french_to_english class TestEnglishToFrench(unittest.TestCase): def testE2F(self): self.assertEqual(english_to_french("Hello"), "Bonjour") self.assertNotEqual(english_to_french("Null"), "") class FrenchEnglishToEnglish(unittest.TestCase): def testF2E(self): self.assertEqual(french_to_english("Bonjour"), "Hello") self.assertNotEqual(french_to_english("Null"), "") unittest.main()
true
true
f717ad7f8ee5170fed096dfbfb9360232cb0abc4
157,342
py
Python
tests/test_cadquery.py
RubenRubens/cadquery
94030ad5e4d5489b29cb021282ecc8db34172471
[ "Apache-2.0" ]
1
2021-09-01T20:16:29.000Z
2021-09-01T20:16:29.000Z
tests/test_cadquery.py
RubenRubens/cadquery
94030ad5e4d5489b29cb021282ecc8db34172471
[ "Apache-2.0" ]
null
null
null
tests/test_cadquery.py
RubenRubens/cadquery
94030ad5e4d5489b29cb021282ecc8db34172471
[ "Apache-2.0" ]
null
null
null
""" This module tests cadquery creation and manipulation functions """ # system modules import math, os.path, time, tempfile from random import choice from random import random from random import randrange from itertools import product from pytest import approx, raises # my modules from cadquery import * from cadquery import exporters from cadquery import occ_impl from tests import ( BaseTest, writeStringToFile, makeUnitCube, readFileAsString, makeUnitSquareWire, makeCube, ) # test data directory testdataDir = os.path.join(os.path.dirname(__file__), "testdata") # where unit test output will be saved OUTDIR = tempfile.gettempdir() SUMMARY_FILE = os.path.join(OUTDIR, "testSummary.html") SUMMARY_TEMPLATE = """<html> <head> <style type="text/css"> .testResult{ background: #eeeeee; margin: 50px; border: 1px solid black; } </style> </head> <body> <!--TEST_CONTENT--> </body> </html>""" TEST_RESULT_TEMPLATE = """ <div class="testResult"><h3>%(name)s</h3> %(svg)s </div> <!--TEST_CONTENT--> """ # clean up any summary file that is in the output directory. # i know, this sux, but there is no other way to do this in 2.6, as we cannot do class fixtures till 2.7 writeStringToFile(SUMMARY_TEMPLATE, SUMMARY_FILE) class TestCadQuery(BaseTest): def tearDown(self): """ Update summary with data from this test. This is a really hacky way of doing it-- we get a startup event from module load, but there is no way in unittest to get a single shutdown event-- except for stuff in 2.7 and above So what we do here is to read the existing file, stick in more content, and leave it """ svgFile = os.path.join(OUTDIR, self._testMethodName + ".svg") # all tests do not produce output if os.path.exists(svgFile): existingSummary = readFileAsString(SUMMARY_FILE) svgText = readFileAsString(svgFile) svgText = svgText.replace( '<?xml version="1.0" encoding="UTF-8" standalone="no"?>', "" ) # now write data into the file # the content we are replacing it with also includes the marker, so it can be replaced again existingSummary = existingSummary.replace( "<!--TEST_CONTENT-->", TEST_RESULT_TEMPLATE % (dict(svg=svgText, name=self._testMethodName)), ) writeStringToFile(existingSummary, SUMMARY_FILE) def saveModel(self, shape): """ shape must be a CQ object Save models in SVG and STEP format """ shape.exportSvg(os.path.join(OUTDIR, self._testMethodName + ".svg")) shape.val().exportStep(os.path.join(OUTDIR, self._testMethodName + ".step")) def testToOCC(self): """ Tests to make sure that a CadQuery object is converted correctly to a OCC object. """ r = Workplane("XY").rect(5, 5).extrude(5) r = r.toOCC() import OCP self.assertEqual(type(r), OCP.TopoDS.TopoDS_Compound) def testToSVG(self): """ Tests to make sure that a CadQuery object is converted correctly to SVG """ r = Workplane("XY").rect(5, 5).extrude(5) r_str = r.toSvg() # Make sure that a couple of sections from the SVG output make sense self.assertTrue(r_str.index('path d="M') > 0) self.assertTrue( r_str.index('line x1="30" y1="-30" x2="58" y2="-15" stroke-width="3"') > 0 ) def testCubePlugin(self): """ Tests a plugin that combines cubes together with a base :return: """ # make the plugin method def makeCubes(self, length): # self refers to the CQ or Workplane object # create the solid s = Solid.makeBox(length, length, length, Vector(0, 0, 0)) # use CQ utility method to iterate over the stack an position the cubes return self.eachpoint(lambda loc: s.located(loc), True) # link the plugin in Workplane.makeCubes = makeCubes # call it result = ( Workplane("XY") .box(6.0, 8.0, 0.5) .faces(">Z") .rect(4.0, 4.0, forConstruction=True) .vertices() ) result = result.makeCubes(1.0) result = result.combineSolids() self.saveModel(result) self.assertEqual(1, result.solids().size()) def testCylinderPlugin(self): """ Tests a cylinder plugin. The plugin creates cylinders of the specified radius and height for each item on the stack This is a very short plugin that illustrates just about the simplest possible plugin """ def cylinders(self, radius, height): # construct a cylinder at (0,0,0) c = Solid.makeCylinder(radius, height, Vector(0, 0, 0)) # combine all the cylinders into a single compound r = self.eachpoint(lambda loc: c.located(loc), True).combineSolids() return r Workplane.cyl = cylinders # now test. here we want weird workplane to see if the objects are transformed right s = ( Workplane(Plane(Vector((0, 0, 0)), Vector((1, -1, 0)), Vector((1, 1, 0)))) .rect(2.0, 3.0, forConstruction=True) .vertices() .cyl(0.25, 0.5) ) self.assertEqual(4, s.solids().size()) self.saveModel(s) def testPolygonPlugin(self): """ Tests a plugin to make regular polygons around points on the stack Demonstrations using eachpoint to allow working in local coordinates to create geometry """ def rPoly(self, nSides, diameter): def _makePolygon(loc): # pnt is a vector in local coordinates angle = 2.0 * math.pi / nSides pnts = [] for i in range(nSides + 1): pnts.append( Vector( (diameter / 2.0 * math.cos(angle * i)), (diameter / 2.0 * math.sin(angle * i)), 0, ) ) return Wire.makePolygon(pnts).located(loc) return self.eachpoint(_makePolygon, True) Workplane.rPoly = rPoly s = ( Workplane("XY") .box(4.0, 4.0, 0.25) .faces(">Z") .workplane() .rect(2.0, 2.0, forConstruction=True) .vertices() .rPoly(5, 0.5) .cutThruAll() ) # 6 base sides, 4 pentagons, 5 sides each = 26 self.assertEqual(26, s.faces().size()) self.saveModel(s) def testFluentMethodInheritance(self): """ Tests that a derived class inherits fluent methods which return instances of derived class when inherited. """ class ExtendedWorkplane(Workplane): def nonExistentInWorkplane(self): pass # Call an inherited fluent method: wp = ExtendedWorkplane("XY").moveTo(1, 2) # Verify that the inherited method returned an instance of the derived # class: self.assertEqual(type(wp), ExtendedWorkplane) # The following is redundant, but can make the use case clearer. # This must not raise an AttributeError: wp.nonExistentInWorkplane() def testPointList(self): """ Tests adding points and using them """ c = CQ(makeUnitCube()) s = c.faces(">Z").workplane().pushPoints([(-0.3, 0.3), (0.3, 0.3), (0, 0)]) self.assertEqual(3, s.size()) # TODO: is the ability to iterate over points with circle really worth it? # maybe we should just require using all() and a loop for this. the semantics and # possible combinations got too hard ( ie, .circle().circle() ) was really odd body = s.circle(0.05).cutThruAll() self.saveModel(body) self.assertEqual(9, body.faces().size()) # Test the case when using eachpoint with only a blank workplane def callback_fn(loc): self.assertEqual( Vector(0, 0, 0), Vector(loc.wrapped.Transformation().TranslationPart()) ) r = Workplane("XY") r.objects = [] r.eachpoint(callback_fn) def testWorkplaneFromFace(self): # make a workplane on the top face s = CQ(makeUnitCube()).faces(">Z").workplane() r = s.circle(0.125).cutBlind(-2.0) self.saveModel(r) # the result should have 7 faces self.assertEqual(7, r.faces().size()) self.assertEqual(type(r.val()), Compound) self.assertEqual(type(r.first().val()), Compound) def testFrontReference(self): # make a workplane on the top face s = CQ(makeUnitCube()).faces("front").workplane() r = s.circle(0.125).cutBlind(-2.0) self.saveModel(r) # the result should have 7 faces self.assertEqual(7, r.faces().size()) self.assertEqual(type(r.val()), Compound) self.assertEqual(type(r.first().val()), Compound) def testRotate(self): """Test solid rotation at the CQ object level.""" box = Workplane("XY").box(1, 1, 5) box.rotate((0, 0, 0), (1, 0, 0), 90) startPoint = box.faces("<Y").edges("<X").first().val().startPoint().toTuple() endPoint = box.faces("<Y").edges("<X").first().val().endPoint().toTuple() self.assertEqual(-0.5, startPoint[0]) self.assertEqual(-0.5, startPoint[1]) self.assertEqual(-2.5, startPoint[2]) self.assertEqual(-0.5, endPoint[0]) self.assertEqual(-0.5, endPoint[1]) self.assertEqual(2.5, endPoint[2]) def testPlaneRotateZNormal(self): """ Rotation of a plane in the Z direction should never alter its normal. This test creates random planes. The plane is rotated a random angle in the Z-direction to verify that the resulting plane maintains the same normal. The test also checks that the random origin is unaltered after rotation. """ for _ in range(100): angle = (random() - 0.5) * 720 xdir = Vector(random(), random(), random()).normalized() rdir = Vector(random(), random(), random()).normalized() zdir = xdir.cross(rdir).normalized() origin = (random(), random(), random()) plane = Plane(origin=origin, xDir=xdir, normal=zdir) rotated = plane.rotated((0, 0, angle)) assert rotated.zDir.toTuple() == approx(zdir.toTuple()) assert rotated.origin.toTuple() == approx(origin) def testPlaneRotateConcat(self): """ Test the result of a well-known concatenated rotation example. """ xdir = (1, 0, 0) normal = (0, 0, 1) k = 2.0 ** 0.5 / 2.0 origin = (2, -1, 1) plane = Plane(origin=origin, xDir=xdir, normal=normal) plane = plane.rotated((0, 0, 45)) assert plane.xDir.toTuple() == approx((k, k, 0)) assert plane.yDir.toTuple() == approx((-k, k, 0)) assert plane.zDir.toTuple() == approx((0, 0, 1)) plane = plane.rotated((0, 45, 0)) assert plane.xDir.toTuple() == approx((0.5, 0.5, -k)) assert plane.yDir.toTuple() == approx((-k, k, 0)) assert plane.zDir.toTuple() == approx((0.5, 0.5, k)) assert plane.origin.toTuple() == origin def testPlaneRotateConcatRandom(self): """ Rotation of a plane in a given direction should never alter that direction. This test creates a plane and rotates it a random angle in a given direction. After the rotation, the direction of the resulting plane in the rotation-direction should be constant. The test also checks that the origin is unaltered after all rotations. """ origin = (2, -1, 1) plane = Plane(origin=origin, xDir=(1, 0, 0), normal=(0, 0, 1)) for _ in range(100): before = { 0: plane.xDir.toTuple(), 1: plane.yDir.toTuple(), 2: plane.zDir.toTuple(), } angle = (random() - 0.5) * 720 direction = randrange(3) rotation = [0, 0, 0] rotation[direction] = angle plane = plane.rotated(rotation) after = { 0: plane.xDir.toTuple(), 1: plane.yDir.toTuple(), 2: plane.zDir.toTuple(), } assert before[direction] == approx(after[direction]) assert plane.origin.toTuple() == origin def testPlaneNoXDir(self): """ Plane should pick an arbitrary x direction if None is passed in. """ for z_dir in [(0, 0, 1), (1, 0, 0), (-1, 0, 0), Vector(-1, 0, 0)]: result = Plane(origin=(1, 2, 3), xDir=None, normal=z_dir) assert result.zDir == Vector(z_dir) assert result.xDir.Length == approx(1) assert result.origin == Vector(1, 2, 3) # unspecified xDir should be the same as xDir=None result2 = Plane(origin=(1, 2, 3), normal=z_dir) assert result2 == result def testPlaneToPln(self): plane = Plane(origin=(1, 2, 3), xDir=(-1, 0, 0), normal=(0, 1, 0)) gppln = plane.toPln() assert Vector(gppln.XAxis().Direction()) == Vector(-1, 0, 0) assert Vector(gppln.YAxis().Direction()) == plane.yDir assert Vector(gppln.Axis().Direction()) == plane.zDir def testRect(self): x = 10 y = 11 s = Workplane().rect(x, y) # a rectangle has 4 sides self.assertEqual(s.edges().size(), 4) # assert that the lower left corner is in the correct spot for all # possible values of centered for centered_x, xval in zip([True, False], [-x / 2, 0]): for centered_y, yval in zip([True, False], [-y / 2, 0]): s = ( Workplane() .rect(x, y, centered=(centered_x, centered_y)) .vertices("<X and <Y") ) self.assertEqual(s.size(), 1) self.assertTupleAlmostEquals(s.val().toTuple(), (xval, yval, 0), 3) # check that centered=True is the same as centered=(True, True) for option0 in [True, False]: v0 = ( Workplane() .rect(x, y, centered=option0) .vertices(">X and >Y") .val() .toTuple() ) v1 = ( Workplane() .rect(x, y, centered=(option0, option0)) .vertices(">X and >Y") .val() .toTuple() ) self.assertTupleAlmostEquals(v0, v1, 3) # test negative lengths r0 = Workplane().rect(-x, -y, centered=False) self.assertTupleAlmostEquals( (0, 0, 0), r0.vertices(">X and >Y").val().toTuple(), 3 ) self.assertTupleAlmostEquals( (-x, -y, 0), r0.vertices("<X and <Y").val().toTuple(), 3 ) # test move plus negative length r1 = Workplane().move(x, y).rect(-x, -y, centered=False) self.assertTupleAlmostEquals( (x, y, 0), r1.vertices(">X and >Y").val().toTuple(), 3 ) self.assertTupleAlmostEquals( (0, 0, 0), r1.vertices("<X and <Y").val().toTuple(), 3 ) # negative length should have no effect with centered=True v2 = Workplane().rect(x, y).vertices(">X and >Y").val().toTuple() v3 = Workplane().rect(-x, -y).vertices(">X and >Y").val().toTuple() self.assertTupleAlmostEquals(v2, v3, 3) def testLoft(self): """ Test making a lofted solid """ s = Workplane("XY").circle(4.0).workplane(5.0).rect(2.0, 2.0).loft() self.saveModel(s) # the result should have 7 faces self.assertEqual(1, s.solids().size()) # the resulting loft had a split on the side, not sure why really, i expected only 3 faces self.assertEqual(7, s.faces().size()) def testLoftRaisesValueError(self): s0 = Workplane().hLine(1) # no wires with raises(ValueError): s0.loft() s1 = Workplane("XY").circle(5) # one wire with self.assertRaises(ValueError) as cm: s1.loft() err = cm.exception self.assertEqual(str(err), "More than one wire is required") def testLoftCombine(self): """ test combining a lof with another feature :return: """ s = ( Workplane("front") .box(4.0, 4.0, 0.25) .faces(">Z") .circle(1.5) .workplane(offset=3.0) .rect(0.75, 0.5) .loft(combine=True) ) self.saveModel(s) # self.assertEqual(1,s.solids().size() ) # self.assertEqual(8,s.faces().size() ) def testRevolveCylinder(self): """ Test creating a solid using the revolve operation. :return: """ # The dimensions of the model. These can be modified rather than changing the # shape's code directly. rectangle_width = 10.0 rectangle_length = 10.0 angle_degrees = 360.0 # Test revolve without any options for making a cylinder result = ( Workplane("XY").rect(rectangle_width, rectangle_length, False).revolve() ) self.assertEqual(3, result.faces().size()) self.assertEqual(2, result.vertices().size()) self.assertEqual(3, result.edges().size()) # Test revolve when only setting the angle to revolve through result = ( Workplane("XY") .rect(rectangle_width, rectangle_length, False) .revolve(angle_degrees) ) self.assertEqual(3, result.faces().size()) self.assertEqual(2, result.vertices().size()) self.assertEqual(3, result.edges().size()) result = ( Workplane("XY") .rect(rectangle_width, rectangle_length, False) .revolve(270.0) ) self.assertEqual(5, result.faces().size()) self.assertEqual(6, result.vertices().size()) self.assertEqual(9, result.edges().size()) # Test when passing revolve the angle and the axis of revolution's start point result = ( Workplane("XY") .rect(rectangle_width, rectangle_length) .revolve(angle_degrees, (-5, -5)) ) self.assertEqual(3, result.faces().size()) self.assertEqual(2, result.vertices().size()) self.assertEqual(3, result.edges().size()) result = ( Workplane("XY") .rect(rectangle_width, rectangle_length) .revolve(270.0, (-5, -5)) ) self.assertEqual(5, result.faces().size()) self.assertEqual(6, result.vertices().size()) self.assertEqual(9, result.edges().size()) # Test when passing revolve the angle and both the start and ends of the axis of revolution result = ( Workplane("XY") .rect(rectangle_width, rectangle_length) .revolve(angle_degrees, (-5, -5), (-5, 5)) ) self.assertEqual(3, result.faces().size()) self.assertEqual(2, result.vertices().size()) self.assertEqual(3, result.edges().size()) result = ( Workplane("XY") .rect(rectangle_width, rectangle_length) .revolve(270.0, (-5, -5), (-5, 5)) ) self.assertEqual(5, result.faces().size()) self.assertEqual(6, result.vertices().size()) self.assertEqual(9, result.edges().size()) # Testing all of the above without combine result = ( Workplane("XY") .rect(rectangle_width, rectangle_length) .revolve(angle_degrees, (-5, -5), (-5, 5), False) ) self.assertEqual(3, result.faces().size()) self.assertEqual(2, result.vertices().size()) self.assertEqual(3, result.edges().size()) result = ( Workplane("XY") .rect(rectangle_width, rectangle_length) .revolve(270.0, (-5, -5), (-5, 5), False) ) self.assertEqual(5, result.faces().size()) self.assertEqual(6, result.vertices().size()) self.assertEqual(9, result.edges().size()) def testRevolveDonut(self): """ Test creating a solid donut shape with square walls :return: """ # The dimensions of the model. These can be modified rather than changing the # shape's code directly. rectangle_width = 10.0 rectangle_length = 10.0 angle_degrees = 360.0 result = ( Workplane("XY") .rect(rectangle_width, rectangle_length, True) .revolve(angle_degrees, (20, 0), (20, 10)) ) self.assertEqual(4, result.faces().size()) self.assertEqual(4, result.vertices().size()) self.assertEqual(6, result.edges().size()) def testRevolveCone(self): """ Test creating a solid from a revolved triangle :return: """ result = Workplane("XY").lineTo(0, 10).lineTo(5, 0).close().revolve() self.assertEqual(2, result.faces().size()) self.assertEqual(2, result.vertices().size()) self.assertEqual(2, result.edges().size()) def testRevolveErrors(self): """ Test that revolve raises errors when used incorrectly. """ result = Workplane("XY").lineTo(0, 10).lineTo(5, 0) with raises(ValueError): result.revolve() def testSpline(self): """ Tests construction of splines """ pts = [(0, 0), (0, 1), (1, 2), (2, 4)] # Spline path - just a smoke test path = Workplane("XZ").spline(pts).val() # Closed spline path_closed = Workplane("XZ").spline(pts, periodic=True).val() self.assertTrue(path_closed.IsClosed()) # attempt to build a valid face w = Wire.assembleEdges([path_closed,]) f = Face.makeFromWires(w) self.assertTrue(f.isValid()) # attempt to build an invalid face w = Wire.assembleEdges([path,]) f = Face.makeFromWires(w) self.assertFalse(f.isValid()) # Spline with explicit tangents path_const = Workplane("XZ").spline(pts, tangents=((0, 1), (1, 0))).val() self.assertFalse(path.tangentAt(0) == path_const.tangentAt(0)) self.assertFalse(path.tangentAt(1) == path_const.tangentAt(1)) # test include current path1 = Workplane("XZ").spline(pts[1:], includeCurrent=True).val() self.assertAlmostEqual(path.Length(), path1.Length()) # test tangents and offset plane pts = [(0, 0), (-1, 1), (-2, 0), (-1, 0)] tangents = [(0, 1), (1, 0)] path2 = Workplane("XY", (0, 0, 10)).spline(pts, tangents=tangents) self.assertAlmostEqual(path2.val().tangentAt(0).z, 0) def testSplineWithMultipleTangents(self): """ Tests specifying B-spline tangents, besides the start point and end point tangents. """ points = [(0, 0), (1, 1), (2, 0), (1, -1)] tangents = [(0, 1), (1, 0), (0, -1), (-1, 0)] parameters = range(len(points)) spline = ( Workplane("XY") .spline(points, tangents=tangents, parameters=parameters) .consolidateWires() ) test_point = spline.edges().val().positionAt(2.5, mode="parameter") expected_test_point = Vector(1.875, -0.625, 0.0) self.assertAlmostEqual((test_point - expected_test_point).Length, 0) def testSplineWithSpecifiedAndUnspecifiedTangents(self): points = [(0, 0), (1, 1), (2, 0), (1, -1)] tangents = [(0, 1), None, (0, -1), (-1, 0)] parameters = range(len(points)) spline = ( Workplane("XY") .spline(points, tangents=tangents, parameters=parameters) .consolidateWires() ) test_point = spline.edges().val().positionAt(1.5, mode="parameter") expected_test_point = Vector(1.6875, 0.875, 0.0) self.assertAlmostEqual((test_point - expected_test_point).Length, 0) def testSplineSpecifyingParameters(self): points = [(0, 0), (1, 1), (2, 0), (1, -1)] tangents = [(0, 1), (1, 0), (0, -1), (-1, 0)] spline1 = ( Workplane("XY") .spline(points, tangents=tangents, parameters=[0, 1, 2, 3]) .consolidateWires() ) # Multiply all parameter values by 10: spline2 = ( Workplane("XY") .spline(points, tangents=tangents, parameters=[0, 10, 20, 30]) .consolidateWires() ) # Test point equivalence for parameter, and parameter multiplied by 10: test_point1 = spline1.edges().val().positionAt(1.5, mode="parameter") test_point2 = spline2.edges().val().positionAt(15, mode="parameter") expected_test_point = Vector(1.625, 0.625, 0.0) self.assertAlmostEqual((test_point1 - test_point2).Length, 0) self.assertAlmostEqual((test_point1 - expected_test_point).Length, 0) # test periodic with parameters spline3 = Workplane().spline( points, periodic=True, parameters=[x for x in range(len(points) + 1)] ) self.assertTrue(spline3.val().IsClosed()) def testSplineWithScaleTrue(self): points = [(0, 0), (1, 1), (2, 0), (1, -1)] tangents = [(0, 1), (1, 0), (0, -1), (-1, 0)] parameters = range(len(points)) spline = ( Workplane("XY") .spline(points, tangents=tangents, parameters=parameters, scale=True) .consolidateWires() ) test_point = spline.edges().val().positionAt(0.5, mode="parameter") expected_test_point = Vector(0.375, 0.875, 0.0) self.assertAlmostEqual((test_point - expected_test_point).Length, 0) def testSplineWithScaleFalse(self): """ Like testSplineWithScaleTrue, but verifies the tangent vector is different when scale=False. The interpolation points and tangent vectors are the same in `testSplineWithScaleTrue`, and `testSplineWithScaleFalse`. A test point is rendered at the same parameter value in both cases, but its coordinates are different in each case. """ points = [(0, 0), (1, 1), (2, 0), (1, -1)] tangents = [(0, 1), (1, 0), (0, -1), (-1, 0)] parameters = range(len(points)) spline = ( Workplane("XY") .spline(points, tangents=tangents, parameters=parameters, scale=False) .consolidateWires() ) test_point = spline.edges().val().positionAt(0.5, mode="parameter") expected_test_point = Vector(0.375, 0.625, 0.0) self.assertAlmostEqual((test_point - expected_test_point).Length, 0) def testSplineTangentMagnitudeBelowToleranceThrows(self): import OCP points = [(0, 0), (1, 1), (2, 0), (1, -1)] # Use a tangent vector with magnitude 0.5: tangents = [(0, 0.5), (1, 0), (0, -1), (-1, 0)] parameters = range(len(points)) # Set tolerance above the 0.5 length of the tangent vector. This # should throw an exception: with raises( (OCP.Standard.Standard_ConstructionError, OCP.Standard.Standard_Failure) ): spline = ( Workplane("XY") .spline(points, tangents=tangents, tol=1) .consolidateWires() ) def testSplineInputValidation(self): points = [(0, 0), (1, 1), (2, 0)] tangents = [(0, 0.5), (1, 0), (0, -1), (-1, 0)] with raises(ValueError): spline = Workplane().spline(points, tangents=tangents) with raises(ValueError): Workplane().spline( points, periodic=False, parameters=[x for x in range(len(points) + 1)], ) with raises(ValueError): Workplane().spline( points, periodic=True, parameters=[x for x in range(len(points))], ) def testRotatedEllipse(self): def rotatePoint(x, y, alpha): # rotation matrix a = alpha * DEG2RAD r = ((math.cos(a), math.sin(a)), (-math.sin(a), math.cos(a))) return ((x * r[0][0] + y * r[1][0]), (x * r[0][1] + y * r[1][1])) def ellipsePoints(r1, r2, a): return (r1 * math.cos(a * DEG2RAD), r2 * math.sin(a * DEG2RAD)) DEG2RAD = math.pi / 180.0 p0 = (10, 20) a1, a2 = 30, -60 r1, r2 = 20, 10 ra = 25 sx_rot, sy_rot = rotatePoint(*ellipsePoints(r1, r2, a1), ra) ex_rot, ey_rot = rotatePoint(*ellipsePoints(r1, r2, a2), ra) # startAtCurrent=False, sense = 1 ellipseArc1 = ( Workplane("XY") .moveTo(*p0) .ellipseArc( r1, r2, startAtCurrent=False, angle1=a1, angle2=a2, rotation_angle=ra ) ) start = ellipseArc1.vertices().objects[0] end = ellipseArc1.vertices().objects[1] self.assertTupleAlmostEquals( (start.X, start.Y), (p0[0] + sx_rot, p0[1] + sy_rot), 3 ) self.assertTupleAlmostEquals( (end.X, end.Y), (p0[0] + ex_rot, p0[1] + ey_rot), 3 ) # startAtCurrent=True, sense = 1 ellipseArc2 = ( Workplane("XY") .moveTo(*p0) .ellipseArc( r1, r2, startAtCurrent=True, angle1=a1, angle2=a2, rotation_angle=ra ) ) start = ellipseArc2.vertices().objects[0] end = ellipseArc2.vertices().objects[1] self.assertTupleAlmostEquals( (start.X, start.Y), (p0[0] + sx_rot - sx_rot, p0[1] + sy_rot - sy_rot), 3 ) self.assertTupleAlmostEquals( (end.X, end.Y), (p0[0] + ex_rot - sx_rot, p0[1] + ey_rot - sy_rot), 3 ) # startAtCurrent=False, sense = -1 ellipseArc3 = ( Workplane("XY") .moveTo(*p0) .ellipseArc( r1, r2, startAtCurrent=False, angle1=a1, angle2=a2, rotation_angle=ra, sense=-1, ) ) start = ellipseArc3.vertices().objects[0] end = ellipseArc3.vertices().objects[1] # swap start and end points for comparison due to different sense self.assertTupleAlmostEquals( (start.X, start.Y), (p0[0] + ex_rot, p0[1] + ey_rot), 3 ) self.assertTupleAlmostEquals( (end.X, end.Y), (p0[0] + sx_rot, p0[1] + sy_rot), 3 ) # startAtCurrent=True, sense = -1 ellipseArc4 = ( Workplane("XY") .moveTo(*p0) .ellipseArc( r1, r2, startAtCurrent=True, angle1=a1, angle2=a2, rotation_angle=ra, sense=-1, makeWire=True, ) ) self.assertEqual(len(ellipseArc4.ctx.pendingWires), 1) start = ellipseArc4.vertices().objects[0] end = ellipseArc4.vertices().objects[1] # swap start and end points for comparison due to different sense self.assertTupleAlmostEquals( (start.X, start.Y), (p0[0] + ex_rot - ex_rot, p0[1] + ey_rot - ey_rot), 3 ) self.assertTupleAlmostEquals( (end.X, end.Y), (p0[0] + sx_rot - ex_rot, p0[1] + sy_rot - ey_rot), 3 ) def testEllipseArcsClockwise(self): ellipseArc = ( Workplane("XY") .moveTo(10, 15) .ellipseArc(5, 4, -10, 190, 45, sense=-1, startAtCurrent=False) ) sp = ellipseArc.val().startPoint() ep = ellipseArc.val().endPoint() self.assertTupleAlmostEquals( (sp.x, sp.y), (7.009330014275797, 11.027027582524015), 3 ) self.assertTupleAlmostEquals( (ep.x, ep.y), (13.972972417475985, 17.990669985724203), 3 ) ellipseArc = ( ellipseArc.ellipseArc(5, 4, -10, 190, 315, sense=-1) .ellipseArc(5, 4, -10, 190, 225, sense=-1) .ellipseArc(5, 4, -10, 190, 135, sense=-1) ) ep = ellipseArc.val().endPoint() self.assertTupleAlmostEquals((sp.x, sp.y), (ep.x, ep.y), 3) def testEllipseArcsCounterClockwise(self): ellipseArc = ( Workplane("XY") .moveTo(10, 15) .ellipseArc(5, 4, -10, 190, 45, startAtCurrent=False) ) sp = ellipseArc.val().startPoint() ep = ellipseArc.val().endPoint() self.assertTupleAlmostEquals( (sp.x, sp.y), (13.972972417475985, 17.990669985724203), 3 ) self.assertTupleAlmostEquals( (ep.x, ep.y), (7.009330014275797, 11.027027582524015), 3 ) ellipseArc = ( ellipseArc.ellipseArc(5, 4, -10, 190, 135) .ellipseArc(5, 4, -10, 190, 225) .ellipseArc(5, 4, -10, 190, 315) ) ep = ellipseArc.val().endPoint() self.assertTupleAlmostEquals((sp.x, sp.y), (ep.x, ep.y), 3) def testEllipseCenterAndMoveTo(self): # Whether we start from a center() call or a moveTo call, it should be the same ellipse Arc p0 = (10, 20) a1, a2 = 30, -60 r1, r2 = 20, 10 ra = 25 ellipseArc1 = ( Workplane("XY") .moveTo(*p0) .ellipseArc( r1, r2, startAtCurrent=False, angle1=a1, angle2=a2, rotation_angle=ra ) ) sp1 = ellipseArc1.val().startPoint() ep1 = ellipseArc1.val().endPoint() ellipseArc2 = ( Workplane("XY") .moveTo(*p0) .ellipseArc( r1, r2, startAtCurrent=False, angle1=a1, angle2=a2, rotation_angle=ra ) ) sp2 = ellipseArc2.val().startPoint() ep2 = ellipseArc2.val().endPoint() self.assertTupleAlmostEquals(sp1.toTuple(), sp2.toTuple(), 3) self.assertTupleAlmostEquals(ep1.toTuple(), ep2.toTuple(), 3) def testMakeEllipse(self): el = Wire.makeEllipse( 1, 2, Vector(0, 0, 0), Vector(0, 0, 1), Vector(1, 0, 0), 0, 90, 45, True, ) self.assertTrue(el.IsClosed()) self.assertTrue(el.isValid()) def testSweep(self): """ Tests the operation of sweeping a wire(s) along a path """ pts = [(0, 0), (0, 1), (1, 2), (2, 4)] # Spline path path = Workplane("XZ").spline(pts) # Test defaults result = Workplane("XY").circle(1.0).sweep(path) self.assertEqual(3, result.faces().size()) self.assertEqual(3, result.edges().size()) # Test with makeSolid False result = Workplane("XY").circle(1.0).sweep(path, makeSolid=False) self.assertEqual(1, result.faces().size()) self.assertEqual(3, result.edges().size()) # Test with isFrenet True result = Workplane("XY").circle(1.0).sweep(path, isFrenet=True) self.assertEqual(3, result.faces().size()) self.assertEqual(3, result.edges().size()) # Test with makeSolid False and isFrenet True result = Workplane("XY").circle(1.0).sweep(path, makeSolid=False, isFrenet=True) self.assertEqual(1, result.faces().size()) self.assertEqual(3, result.edges().size()) # Test rectangle with defaults result = Workplane("XY").rect(1.0, 1.0).sweep(path) self.assertEqual(6, result.faces().size()) self.assertEqual(12, result.edges().size()) # Test fixed normal result = Workplane().circle(0.5).sweep(path, normal=Vector(0, 0, 1)) self.assertTupleAlmostEquals( result.faces(">Z").val().normalAt().toTuple(), (0, 0, 1), 6 ) # Polyline path path = Workplane("XZ").polyline(pts) # Test defaults result = Workplane("XY").circle(0.1).sweep(path, transition="transformed") self.assertEqual(5, result.faces().size()) self.assertEqual(7, result.edges().size()) # Polyline path and one inner profiles path = Workplane("XZ").polyline(pts) # Test defaults result = ( Workplane("XY") .circle(0.2) .circle(0.1) .sweep(path, transition="transformed") ) self.assertEqual(8, result.faces().size()) self.assertEqual(14, result.edges().size()) # Polyline path and different transition settings for t in ("transformed", "right", "round"): path = Workplane("XZ").polyline(pts) result = ( Workplane("XY") .circle(0.2) .rect(0.2, 0.1) .rect(0.1, 0.2) .sweep(path, transition=t) ) self.assertTrue(result.solids().val().isValid()) # Polyline path and multiple inner profiles path = Workplane("XZ").polyline(pts) # Test defaults result = ( Workplane("XY") .circle(0.2) .rect(0.2, 0.1) .rect(0.1, 0.2) .circle(0.1) .sweep(path) ) self.assertTrue(result.solids().val().isValid()) # Arc path path = Workplane("XZ").threePointArc((1.0, 1.5), (0.0, 1.0)) # Test defaults result = Workplane("XY").circle(0.1).sweep(path) self.assertEqual(3, result.faces().size()) self.assertEqual(3, result.edges().size()) # Test aux spine pts1 = [(0, 0), (20, 100)] pts2 = [(0, 20, 0), (20, 0, 100)] path = Workplane("YZ").spline(pts1, tangents=[(0, 1, 0), (0, 1, 0)]) aux_path = Workplane("XY").spline(pts2, tangents=[(0, 0, 1), (0, 0, 1)]) result = Workplane("XY").rect(10, 20).sweep(path, auxSpine=aux_path) bottom = result.faces("<Z") top = result.faces(">Z") v1 = bottom.wires().val().tangentAt(0.0) v2 = top.wires().val().tangentAt(0.0) self.assertAlmostEqual(v1.getAngle(v2), math.pi / 4, 6) # test for ValueError if pending wires is empty w0 = Workplane().hLine(1).vLine(1) with raises(ValueError): w0.sweep(path) # Test aux spine invalid input handling with raises(ValueError): result = ( Workplane("XY") .rect(10, 20) .sweep(path, auxSpine=Workplane().box(1, 1, 1)) ) def testMultisectionSweep(self): """ Tests the operation of sweeping along a list of wire(s) along a path """ # X axis line length 20.0 path = Workplane("XZ").moveTo(-10, 0).lineTo(10, 0) # Sweep a circle from diameter 2.0 to diameter 1.0 to diameter 2.0 along X axis length 10.0 + 10.0 defaultSweep = ( Workplane("YZ") .workplane(offset=-10.0) .circle(2.0) .workplane(offset=10.0) .circle(1.0) .workplane(offset=10.0) .circle(2.0) .sweep(path, multisection=True) ) # We can sweep through different shapes recttocircleSweep = ( Workplane("YZ") .workplane(offset=-10.0) .rect(2.0, 2.0) .workplane(offset=8.0) .circle(1.0) .workplane(offset=4.0) .circle(1.0) .workplane(offset=8.0) .rect(2.0, 2.0) .sweep(path, multisection=True) ) circletorectSweep = ( Workplane("YZ") .workplane(offset=-10.0) .circle(1.0) .workplane(offset=7.0) .rect(2.0, 2.0) .workplane(offset=6.0) .rect(2.0, 2.0) .workplane(offset=7.0) .circle(1.0) .sweep(path, multisection=True) ) # Placement of the Shape is important otherwise could produce unexpected shape specialSweep = ( Workplane("YZ") .circle(1.0) .workplane(offset=10.0) .rect(2.0, 2.0) .sweep(path, multisection=True) ) # Switch to an arc for the path : line l=5.0 then half circle r=4.0 then line l=5.0 path = ( Workplane("XZ") .moveTo(-5, 4) .lineTo(0, 4) .threePointArc((4, 0), (0, -4)) .lineTo(-5, -4) ) # Placement of different shapes should follow the path # cylinder r=1.5 along first line # then sweep along arc from r=1.5 to r=1.0 # then cylinder r=1.0 along last line arcSweep = ( Workplane("YZ") .workplane(offset=-5) .moveTo(0, 4) .circle(1.5) .workplane(offset=5, centerOption="CenterOfMass") .circle(1.5) .moveTo(0, -8) .circle(1.0) .workplane(offset=-5, centerOption="CenterOfMass") .circle(1.0) .sweep(path, multisection=True) ) # Test multisection with normal pts = [(0, 0), (20, 100)] path = Workplane("YZ").spline(pts, tangents=[(0, 1, 0), (0, 1, 0)]) normalSweep = ( Workplane() .rect(10, 10) .workplane(offset=100) .rect(10, 20) .sweep(path, multisection=True, normal=(0, 1, 1)) ) self.assertTupleAlmostEquals( normalSweep.faces("<Z").val().normalAt().toTuple(), Vector(0, -1, -1).normalized().toTuple(), 6, ) self.assertTupleAlmostEquals( normalSweep.faces(">Z").val().normalAt().toTuple(), Vector(0, 1, 1).normalized().toTuple(), 6, ) # Test and saveModel self.assertEqual(1, defaultSweep.solids().size()) self.assertEqual(1, circletorectSweep.solids().size()) self.assertEqual(1, recttocircleSweep.solids().size()) self.assertEqual(1, specialSweep.solids().size()) self.assertEqual(1, arcSweep.solids().size()) self.saveModel(defaultSweep) def testTwistExtrude(self): """ Tests extrusion while twisting through an angle. """ profile = Workplane("XY").rect(10, 10) r = profile.twistExtrude(10, 45, False) self.assertEqual(6, r.faces().size()) def testTwistExtrudeCombine(self): """ Tests extrusion while twisting through an angle, combining with other solids. """ profile = Workplane("XY").rect(10, 10) r = profile.twistExtrude(10, 45) self.assertEqual(6, r.faces().size()) def testRectArray(self): x_num = 3 y_num = 3 x_spacing = 8.0 y_spacing = 8.0 s = ( Workplane("XY") .box(40, 40, 5, centered=(True, True, True)) .faces(">Z") .workplane() .rarray(x_spacing, y_spacing, x_num, y_num, True) .circle(2.0) .extrude(2.0) ) self.saveModel(s) # 6 faces for the box, 2 faces for each cylinder self.assertEqual(6 + x_num * y_num * 2, s.faces().size()) with raises(ValueError): Workplane().rarray(0, 0, x_num, y_num, True) # check lower and upper corner points are correct for all combinations of centering for x_opt, x_min, x_max in zip( [True, False], [-x_spacing, 0.0], [x_spacing, x_spacing * 2] ): for y_opt, y_min, y_max in zip( [True, False], [-y_spacing, 0.0], [y_spacing, y_spacing * 2] ): s = Workplane().rarray( x_spacing, y_spacing, x_num, y_num, center=(x_opt, y_opt) ) lower = Vector(x_min, y_min, 0) upper = Vector(x_max, y_max, 0) self.assertTrue(lower in s.objects) self.assertTrue(upper in s.objects) # check centered=True is equivalent to centered=(True, True) for val in [True, False]: s0 = Workplane().rarray(x_spacing, y_spacing, x_num, y_num, center=val) s1 = Workplane().rarray( x_spacing, y_spacing, x_num, y_num, center=(val, val) ) # check all the points in s0 are present in s1 self.assertTrue(all(pnt in s1.objects for pnt in s0.objects)) self.assertEqual(s0.size(), s1.size()) def testPolarArray(self): radius = 10 # Test for proper number of elements s = Workplane("XY").polarArray(radius, 0, 180, 1) self.assertEqual(1, s.size()) s = Workplane("XY").polarArray(radius, 0, 180, 6) self.assertEqual(6, s.size()) to_x = lambda l: l.wrapped.Transformation().TranslationPart().X() to_y = lambda l: l.wrapped.Transformation().TranslationPart().Y() to_angle = ( lambda l: l.wrapped.Transformation().GetRotation().GetRotationAngle() * 180.0 / math.pi ) # Test for proper placement when fill == True s = Workplane("XY").polarArray(radius, 0, 180, 3) self.assertAlmostEqual(0, to_y(s.objects[1])) self.assertAlmostEqual(radius, to_x(s.objects[1])) # Test for proper placement when angle to fill is multiple of 360 deg s = Workplane("XY").polarArray(radius, 0, 360, 4) self.assertAlmostEqual(0, to_y(s.objects[1])) self.assertAlmostEqual(radius, to_x(s.objects[1])) # Test for proper placement when fill == False s = Workplane("XY").polarArray(radius, 0, 90, 3, fill=False) self.assertAlmostEqual(0, to_y(s.objects[1])) self.assertAlmostEqual(radius, to_x(s.objects[1])) # Test for proper operation of startAngle s = Workplane("XY").polarArray(radius, 90, 180, 3) self.assertAlmostEqual(radius, to_x(s.objects[0])) self.assertAlmostEqual(0, to_y(s.objects[0])) # Test for local rotation s = Workplane().polarArray(radius, 0, 180, 3) self.assertAlmostEqual(0, to_angle(s.objects[0])) self.assertAlmostEqual(90, to_angle(s.objects[1])) s = Workplane().polarArray(radius, 0, 180, 3, rotate=False) self.assertAlmostEqual(0, to_angle(s.objects[0])) self.assertAlmostEqual(0, to_angle(s.objects[1])) def testNestedCircle(self): s = ( Workplane("XY") .box(40, 40, 5) .pushPoints([(10, 0), (0, 10)]) .circle(4) .circle(2) .extrude(4) ) self.saveModel(s) self.assertEqual(14, s.faces().size()) def testConcentricEllipses(self): concentricEllipses = ( Workplane("XY").center(10, 20).ellipse(100, 10).center(0, 0).ellipse(50, 5) ) v = concentricEllipses.vertices().objects[0] self.assertTupleAlmostEquals((v.X, v.Y), (10 + 50, 20), 3) def testLegoBrick(self): # test making a simple lego brick # which of the below # inputs lbumps = 8 wbumps = 2 # lego brick constants P = 8.0 # nominal pitch c = 0.1 # clearance on each brick side H = 1.2 * P # nominal height of a brick bumpDiam = 4.8 # the standard bump diameter # the nominal thickness of the walls, normally 1.5 t = (P - (2 * c) - bumpDiam) / 2.0 postDiam = P - t # works out to 6.5 total_length = lbumps * P - 2.0 * c total_width = wbumps * P - 2.0 * c # build the brick s = Workplane("XY").box(total_length, total_width, H) # make the base s = s.faces("<Z").shell(-1.0 * t) # shell inwards not outwards s = ( s.faces(">Z") .workplane() .rarray(P, P, lbumps, wbumps, True) .circle(bumpDiam / 2.0) .extrude(1.8) ) # make the bumps on the top # add posts on the bottom. posts are different diameter depending on geometry # solid studs for 1 bump, tubes for multiple, none for 1x1 # this is cheating a little-- how to select the inner face from the shell? tmp = s.faces("<Z").workplane(invert=True) if lbumps > 1 and wbumps > 1: tmp = ( tmp.rarray(P, P, lbumps - 1, wbumps - 1, center=True) .circle(postDiam / 2.0) .circle(bumpDiam / 2.0) .extrude(H - t) ) elif lbumps > 1: tmp = tmp.rarray(P, P, lbumps - 1, 1, center=True).circle(t).extrude(H - t) elif wbumps > 1: tmp = tmp.rarray(P, P, 1, wbumps - 1, center=True).circle(t).extrude(H - t) self.saveModel(s) def testAngledHoles(self): s = ( Workplane("front") .box(4.0, 4.0, 0.25) .faces(">Z") .workplane() .transformed(offset=Vector(0, -1.5, 1.0), rotate=Vector(60, 0, 0)) .rect(1.5, 1.5, forConstruction=True) .vertices() .hole(0.25) ) self.saveModel(s) self.assertEqual(10, s.faces().size()) def testTranslateSolid(self): c = CQ(makeUnitCube()) self.assertAlmostEqual(0.0, c.faces("<Z").vertices().item(0).val().Z, 3) # TODO: it might be nice to provide a version of translate that modifies the existing geometry too d = c.translate(Vector(0, 0, 1.5)) self.assertAlmostEqual(1.5, d.faces("<Z").vertices().item(0).val().Z, 3) def testTranslateWire(self): c = CQ(makeUnitSquareWire()) self.assertAlmostEqual(0.0, c.edges().vertices().item(0).val().Z, 3) d = c.translate(Vector(0, 0, 1.5)) self.assertAlmostEqual(1.5, d.edges().vertices().item(0).val().Z, 3) def testSolidReferencesCombine(self): "test that solid references are preserved correctly" c = CQ(makeUnitCube()) # the cube is the context solid self.assertEqual(6, c.faces().size()) # cube has six faces r = ( c.faces(">Z").workplane().circle(0.125).extrude(0.5, True) ) # make a boss, not updating the original self.assertEqual(8, r.faces().size()) # just the boss faces self.assertEqual(6, c.faces().size()) # original is not modified def testSolidReferencesCombineTrue(self): s = Workplane(Plane.XY()) r = s.rect(2.0, 2.0).extrude(0.5) # the result of course has 6 faces self.assertEqual(6, r.faces().size()) # the original workplane does not, because it did not have a solid initially self.assertEqual(0, s.faces().size()) t = r.faces(">Z").workplane().rect(0.25, 0.25).extrude(0.5, True) # of course the result has 11 faces self.assertEqual(11, t.faces().size()) # r (being the parent) remains unmodified self.assertEqual(6, r.faces().size()) self.saveModel(r) def testSolidReferenceCombineFalse(self): s = Workplane(Plane.XY()) r = s.rect(2.0, 2.0).extrude(0.5) # the result of course has 6 faces self.assertEqual(6, r.faces().size()) # the original workplane does not, because it did not have a solid initially self.assertEqual(0, s.faces().size()) t = r.faces(">Z").workplane().rect(0.25, 0.25).extrude(0.5, False) # result has 6 faces, because it was not combined with the original self.assertEqual(6, t.faces().size()) self.assertEqual(6, r.faces().size()) # original is unmodified as well # subsequent operations use that context solid afterwards def testSimpleWorkplane(self): """ A simple square part with a hole in it """ s = Workplane(Plane.XY()) r = ( s.rect(2.0, 2.0) .extrude(0.5) .faces(">Z") .workplane() .circle(0.25) .cutBlind(-1.0) ) self.saveModel(r) self.assertEqual(7, r.faces().size()) def testMultiFaceWorkplane(self): """ Test Creation of workplane from multiple co-planar face selection. """ s = Workplane("XY").box(1, 1, 1).faces(">Z").rect(1, 0.5).cutBlind(-0.2) w = s.faces(">Z").workplane() o = w.val() # origin of the workplane self.assertAlmostEqual(o.x, 0.0, 3) self.assertAlmostEqual(o.y, 0.0, 3) self.assertAlmostEqual(o.z, 0.5, 3) def testTriangularPrism(self): s = Workplane("XY").lineTo(1, 0).lineTo(1, 1).close().extrude(0.2) self.saveModel(s) def testMultiWireWorkplane(self): """ A simple square part with a hole in it-- but this time done as a single extrusion with two wires, as opposed to s cut """ s = Workplane(Plane.XY()) r = s.rect(2.0, 2.0).circle(0.25).extrude(0.5) self.saveModel(r) self.assertEqual(7, r.faces().size()) def testConstructionWire(self): """ Tests a wire with several holes, that are based on the vertices of a square also tests using a workplane plane other than XY """ s = Workplane(Plane.YZ()) r = ( s.rect(2.0, 2.0) .rect(1.3, 1.3, forConstruction=True) .vertices() .circle(0.125) .extrude(0.5) ) self.saveModel(r) # 10 faces-- 6 plus 4 holes, the vertices of the second rect. self.assertEqual(10, r.faces().size()) def testTwoWorkplanes(self): """ Tests a model that uses more than one workplane """ # base block s = Workplane(Plane.XY()) # TODO: this syntax is nice, but the iteration might not be worth # the complexity. # the simpler and slightly longer version would be: # r = s.rect(2.0,2.0).rect(1.3,1.3,forConstruction=True).vertices() # for c in r.all(): # c.circle(0.125).extrude(0.5,True) r = ( s.rect(2.0, 2.0) .rect(1.3, 1.3, forConstruction=True) .vertices() .circle(0.125) .extrude(0.5) ) # side hole, blind deep 1.9 t = r.faces(">Y").workplane().circle(0.125).cutBlind(-1.9) self.saveModel(t) self.assertEqual(12, t.faces().size()) def testCut(self): """ Tests the cut function by itself to catch the case where a Solid object is passed. """ s = Workplane(Plane.XY()) currentS = s.rect(2.0, 2.0).extrude(0.5) toCut = s.rect(1.0, 1.0).extrude(0.5) resS = currentS.cut(toCut.val()) self.assertEqual(10, resS.faces().size()) with self.assertRaises(ValueError): currentS.cut(toCut.faces().val()) # Test syntactic sugar [__sub__ method] sugar = currentS - toCut.val() self.assertEqual(resS.faces().size(), sugar.faces().size()) # test ValueError on no solid found s0 = Workplane().hLine(1).vLine(1).close() with raises(ValueError): s0.cut(toCut.val()) def testIntersect(self): """ Tests the intersect function. """ s = Workplane(Plane.XY()) currentS = s.rect(2.0, 2.0).extrude(0.5) toIntersect = s.rect(1.0, 1.0).extrude(1) resS = currentS.intersect(toIntersect.val()) self.assertEqual(6, resS.faces().size()) self.assertAlmostEqual(resS.val().Volume(), 0.5) resS = currentS.intersect(toIntersect) self.assertEqual(6, resS.faces().size()) self.assertAlmostEqual(resS.val().Volume(), 0.5) b1 = Workplane("XY").box(1, 1, 1) b2 = Workplane("XY", origin=(0, 0, 0.5)).box(1, 1, 1) resS = b1.intersect(b2) self.assertAlmostEqual(resS.val().Volume(), 0.5) with self.assertRaises(ValueError): b1.intersect(b2.faces().val()) # Test syntactic sugar [__mul__ method] sugar = b1 & b2 self.assertEqual(resS.val().Volume(), sugar.val().Volume()) # raise ValueError when no solid found with raises(ValueError): Workplane().intersect(toIntersect) def testBoundingBox(self): """ Tests the boudingbox center of a model """ result0 = ( Workplane("XY") .moveTo(10, 0) .lineTo(5, 0) .threePointArc((3.9393, 0.4393), (3.5, 1.5)) .threePointArc((3.0607, 2.5607), (2, 3)) .lineTo(1.5, 3) .threePointArc((0.4393, 3.4393), (0, 4.5)) .lineTo(0, 13.5) .threePointArc((0.4393, 14.5607), (1.5, 15)) .lineTo(28, 15) .lineTo(28, 13.5) .lineTo(24, 13.5) .lineTo(24, 11.5) .lineTo(27, 11.5) .lineTo(27, 10) .lineTo(22, 10) .lineTo(22, 13.2) .lineTo(14.5, 13.2) .lineTo(14.5, 10) .lineTo(12.5, 10) .lineTo(12.5, 13.2) .lineTo(5.5, 13.2) .lineTo(5.5, 2) .threePointArc((5.793, 1.293), (6.5, 1)) .lineTo(10, 1) .close() ) result = result0.extrude(100) bb_center = result.val().BoundingBox().center self.saveModel(result) self.assertAlmostEqual(14.0, bb_center.x, 3) self.assertAlmostEqual(7.5, bb_center.y, 3) self.assertAlmostEqual(50.0, bb_center.z, 3) # The following will raise with the default tolerance of TOL 1e-2 bb = result.val().BoundingBox(tolerance=1e-3) self.assertAlmostEqual(0.0, bb.xmin, 2) self.assertAlmostEqual(28, bb.xmax, 2) self.assertAlmostEqual(0.0, bb.ymin, 2) self.assertAlmostEqual(15.0, bb.ymax, 2) self.assertAlmostEqual(0.0, bb.zmin, 2) self.assertAlmostEqual(100.0, bb.zmax, 2) def testCutThroughAll(self): """ Tests a model that uses more than one workplane """ # base block s = Workplane(Plane.XY()) r = ( s.rect(2.0, 2.0) .rect(1.3, 1.3, forConstruction=True) .vertices() .circle(0.125) .extrude(0.5) ) # thru all without explicit face selection t = r.circle(0.5).cutThruAll() self.assertEqual(11, t.faces().size()) # side hole, thru all t = ( t.faces(">Y") .workplane(centerOption="CenterOfMass") .circle(0.125) .cutThruAll() ) self.saveModel(t) self.assertEqual(13, t.faces().size()) # no planar faces sphere_r = 10.0 r = ( Workplane() .sphere(sphere_r) .workplane() .circle(sphere_r / 2.0) .cutThruAll() .workplane() .transformed(rotate=(90, 0, 0)) .circle(sphere_r / 2.0) .cutThruAll() .workplane() .transformed(rotate=(0, 90, 0)) .circle(sphere_r / 2.0) .cutThruAll() ) self.assertTrue(r.val().isValid()) self.assertEqual(r.faces().size(), 7) # test errors box0 = Workplane().box(1, 1, 1).faces(">Z").workplane().hLine(1) with raises(ValueError): box0.cutThruAll() no_box = Workplane().hLine(1).vLine(1).close() with raises(ValueError): no_box.cutThruAll() def testCutToFaceOffsetNOTIMPLEMENTEDYET(self): """ Tests cutting up to a given face, or an offset from a face """ # base block s = Workplane(Plane.XY()) r = ( s.rect(2.0, 2.0) .rect(1.3, 1.3, forConstruction=True) .vertices() .circle(0.125) .extrude(0.5) ) # side hole, up to 0.1 from the last face try: t = ( r.faces(">Y") .workplane() .circle(0.125) .cutToOffsetFromFace(r.faces().mminDist(Dir.Y), 0.1) ) # should end up being a blind hole self.assertEqual(10, t.faces().size()) t.first().val().exportStep("c:/temp/testCutToFace.STEP") except: pass # Not Implemented Yet def testWorkplaneOnExistingSolid(self): "Tests extruding on an existing solid" c = ( CQ(makeUnitCube()) .faces(">Z") .workplane() .circle(0.25) .circle(0.125) .extrude(0.25) ) self.saveModel(c) self.assertEqual(10, c.faces().size()) def testWorkplaneCenterMove(self): # this workplane is centered at x=0.5,y=0.5, the center of the upper face s = ( Workplane("XY").box(1, 1, 1).faces(">Z").workplane().center(-0.5, -0.5) ) # move the center to the corner t = s.circle(0.25).extrude(0.2) # make a boss self.assertEqual(9, t.faces().size()) self.saveModel(t) def testBasicLines(self): "Make a triangular boss" global OUTDIR s = Workplane(Plane.XY()) # TODO: extrude() should imply wire() if not done already # most users dont understand what a wire is, they are just drawing r = s.lineTo(1.0, 0).lineTo(0, 1.0).close().wire().extrude(0.25) r.val().exportStep(os.path.join(OUTDIR, "testBasicLinesStep1.STEP")) # no faces on the original workplane self.assertEqual(0, s.faces().size()) # 5 faces on newly created object self.assertEqual(5, r.faces().size()) # now add a circle through a side face r1 = ( r.faces("+XY") .workplane(centerOption="CenterOfMass") .circle(0.08) .cutThruAll() ) self.assertEqual(6, r1.faces().size()) r1.val().exportStep(os.path.join(OUTDIR, "testBasicLinesXY.STEP")) # now add a circle through a top r2 = ( r1.faces("+Z") .workplane(centerOption="CenterOfMass") .circle(0.08) .cutThruAll() ) self.assertEqual(9, r2.faces().size()) r2.val().exportStep(os.path.join(OUTDIR, "testBasicLinesZ.STEP")) self.saveModel(r2) def test2DDrawing(self): """ Draw things like 2D lines and arcs, should be expanded later to include all 2D constructs """ s = Workplane(Plane.XY()) r = ( s.lineTo(1.0, 0.0) .lineTo(1.0, 1.0) .threePointArc((1.0, 1.5), (0.0, 1.0)) .lineTo(0.0, 0.0) .moveTo(1.0, 0.0) .lineTo(2.0, 0.0) .lineTo(2.0, 2.0) .threePointArc((2.0, 2.5), (0.0, 2.0)) .lineTo(-2.0, 2.0) .lineTo(-2.0, 0.0) .close() ) self.assertEqual(1, r.wires().size()) # Test the *LineTo functions s = Workplane(Plane.XY()) r = s.hLineTo(1.0).vLineTo(1.0).hLineTo(0.0).close() self.assertEqual(1, r.wire().size()) self.assertEqual(4, r.edges().size()) # Test the *Line functions s = Workplane(Plane.XY()) r = s.hLine(1.0).vLine(1.0).hLine(-1.0).close() self.assertEqual(1, r.wire().size()) self.assertEqual(4, r.edges().size()) # Test the move function s = Workplane(Plane.XY()) r = s.move(1.0, 1.0).hLine(1.0).vLine(1.0).hLine(-1.0).close() self.assertEqual(1, r.wire().size()) self.assertEqual(4, r.edges().size()) self.assertEqual( (1.0, 1.0), ( r.vertices(selectors.NearestToPointSelector((0.0, 0.0, 0.0))) .first() .val() .X, r.vertices(selectors.NearestToPointSelector((0.0, 0.0, 0.0))) .first() .val() .Y, ), ) # Test the sagittaArc and radiusArc functions a1 = Workplane(Plane.YZ()).threePointArc((5, 1), (10, 0)) a2 = Workplane(Plane.YZ()).sagittaArc((10, 0), -1) a3 = Workplane(Plane.YZ()).threePointArc((6, 2), (12, 0)) a4 = Workplane(Plane.YZ()).radiusArc((12, 0), -10) assert a1.edges().first().val().geomType() == "CIRCLE" assert a2.edges().first().val().geomType() == "CIRCLE" assert a3.edges().first().val().geomType() == "CIRCLE" assert a4.edges().first().val().geomType() == "CIRCLE" assert a1.edges().first().val().Length() == a2.edges().first().val().Length() assert a3.edges().first().val().Length() == a4.edges().first().val().Length() def testPolarLines(self): """ Draw some polar lines and check expected results """ # Test the PolarLine* functions s = Workplane(Plane.XY()) r = ( s.polarLine(10, 45) .polarLineTo(10, -45) .polarLine(10, -180) .polarLine(-10, -90) .close() ) # a single wire, 5 edges self.assertEqual(1, r.wires().size()) self.assertEqual(5, r.wires().edges().size()) def testLargestDimension(self): """ Tests the largestDimension function when no solids are on the stack and when there are """ r = Workplane("XY").box(1, 1, 1) dim = r.largestDimension() self.assertAlmostEqual(1.76, dim, 1) r = Workplane("XY").rect(1, 1).extrude(1) dim = r.largestDimension() self.assertAlmostEqual(1.76, dim, 1) r = Workplane("XY") with raises(ValueError): r.largestDimension() def testOccBottle(self): """ Make the OCC bottle example. """ L = 20.0 w = 6.0 t = 3.0 s = Workplane(Plane.XY()) # draw half the profile of the bottle p = ( s.center(-L / 2.0, 0) .vLine(w / 2.0) .threePointArc((L / 2.0, w / 2.0 + t), (L, w / 2.0)) .vLine(-w / 2.0) .mirrorX() .extrude(30.0, True) ) # make the neck p.faces(">Z").workplane().circle(3.0).extrude( 2.0, True ) # .edges().fillet(0.05) # make a shell p.faces(">Z").shell(0.3) self.saveModel(p) def testSplineShape(self): """ Tests making a shape with an edge that is a spline """ s = Workplane(Plane.XY()) sPnts = [ (2.75, 1.5), (2.5, 1.75), (2.0, 1.5), (1.5, 1.0), (1.0, 1.25), (0.5, 1.0), (0, 1.0), ] r = s.lineTo(3.0, 0).lineTo(3.0, 1.0).spline(sPnts).close() r = r.extrude(0.5) self.saveModel(r) def testSimpleMirror(self): """ Tests a simple mirroring operation """ s = ( Workplane("XY") .lineTo(2, 2) .threePointArc((3, 1), (2, 0)) .mirrorX() .extrude(0.25) ) self.assertEqual(6, s.faces().size()) self.saveModel(s) def testUnorderedMirror(self): """ Tests whether or not a wire can be mirrored if its mirror won't connect to it """ r = 20 s = 7 t = 1.5 points = [ (0, 0), (0, t / 2), (r / 2 - 1.5 * t, r / 2 - t), (s / 2, r / 2 - t), (s / 2, r / 2), (r / 2, r / 2), (r / 2, s / 2), (r / 2 - t, s / 2), (r / 2 - t, r / 2 - 1.5 * t), (t / 2, 0), ] r = Workplane("XY").polyline(points).mirrorX() self.assertEqual(1, r.wires().size()) self.assertEqual(18, r.edges().size()) # try the same with includeCurrent=True r = Workplane("XY").polyline(points[1:], includeCurrent=True).mirrorX() self.assertEqual(1, r.wires().size()) self.assertEqual(18, r.edges().size()) def testChainedMirror(self): """ Tests whether or not calling mirrorX().mirrorY() works correctly """ r = 20 s = 7 t = 1.5 points = [ (0, t / 2), (r / 2 - 1.5 * t, r / 2 - t), (s / 2, r / 2 - t), (s / 2, r / 2), (r / 2, r / 2), (r / 2, s / 2), (r / 2 - t, s / 2), (r / 2 - t, r / 2 - 1.5 * t), (t / 2, 0), ] r = Workplane("XY").polyline(points).mirrorX().mirrorY().extrude(1).faces(">Z") self.assertEqual(1, r.wires().size()) self.assertEqual(32, r.edges().size()) # TODO: Re-work testIbeam test below now that chaining works # TODO: Add toLocalCoords and toWorldCoords tests def testIbeam(self): """ Make an ibeam. demonstrates fancy mirroring """ s = Workplane(Plane.XY()) L = 100.0 H = 20.0 W = 20.0 t = 1.0 # TODO: for some reason doing 1/4 of the profile and mirroring twice ( .mirrorX().mirrorY() ) # did not work, due to a bug in freecad-- it was losing edges when creating a composite wire. # i just side-stepped it for now pts = [ (0, 0), (0, H / 2.0), (W / 2.0, H / 2.0), (W / 2.0, (H / 2.0 - t)), (t / 2.0, (H / 2.0 - t)), (t / 2.0, (t - H / 2.0)), (W / 2.0, (t - H / 2.0)), (W / 2.0, H / -2.0), (0, H / -2.0), ] r = s.polyline(pts).mirrorY() # these other forms also work res = r.extrude(L) self.saveModel(res) def testCone(self): """ Tests that a simple cone works """ s = Solid.makeCone(0, 1.0, 2.0) t = CQ(s) self.saveModel(t) self.assertEqual(2, t.faces().size()) def testFillet(self): """ Tests filleting edges on a solid """ c = ( CQ(makeUnitCube()) .faces(">Z") .workplane() .circle(0.25) .extrude(0.25, True) .edges("|Z") .fillet(0.2) ) self.saveModel(c) self.assertEqual(12, c.faces().size()) # should raise an error if no solid c1 = Workplane().hLine(1).vLine(1).close() with raises(ValueError): c1.fillet(0.1) def testChamfer(self): """ Test chamfer API with a box shape """ cube = CQ(makeUnitCube()).faces(">Z").chamfer(0.1) self.saveModel(cube) self.assertEqual(10, cube.faces().size()) # should raise an error if no solid c1 = Workplane().hLine(1).vLine(1).close() with raises(ValueError): c1.chamfer(0.1) def testChamferAsymmetrical(self): """ Test chamfer API with a box shape for asymmetrical lengths """ cube = CQ(makeUnitCube()).faces(">Z").chamfer(0.1, 0.2) self.saveModel(cube) self.assertEqual(10, cube.faces().size()) # test if edge lengths are different edge = cube.edges(">Z").vals()[0] self.assertAlmostEqual(0.6, edge.Length(), 3) edge = cube.edges("|Z").vals()[0] self.assertAlmostEqual(0.9, edge.Length(), 3) def testChamferCylinder(self): """ Test chamfer API with a cylinder shape """ cylinder = Workplane("XY").circle(1).extrude(1).faces(">Z").chamfer(0.1) self.saveModel(cylinder) self.assertEqual(4, cylinder.faces().size()) def testCounterBores(self): """ Tests making a set of counterbored holes in a face """ c = CQ(makeCube(3.0)) pnts = [(-1.0, -1.0), (0.0, 0.0), (1.0, 1.0)] c = c.faces(">Z").workplane().pushPoints(pnts).cboreHole(0.1, 0.25, 0.25, 0.75) self.assertEqual(18, c.faces().size()) self.saveModel(c) # Tests the case where the depth of the cboreHole is not specified c2 = CQ(makeCube(3.0)) c2 = c2.faces(">Z").workplane().pushPoints(pnts).cboreHole(0.1, 0.25, 0.25) self.assertEqual(15, c2.faces().size()) def testCounterSinks(self): """ Tests countersinks """ s = Workplane(Plane.XY()) result = ( s.rect(2.0, 4.0) .extrude(0.5) .faces(">Z") .workplane() .rect(1.5, 3.5, forConstruction=True) .vertices() .cskHole(0.125, 0.25, 82, depth=None) ) self.saveModel(result) def testSplitKeepingHalf(self): """ Tests splitting a solid """ # drill a hole in the side c = CQ(makeUnitCube()).faces(">Z").workplane().circle(0.25).cutThruAll() self.assertEqual(7, c.faces().size()) # now cut it in half sideways result = c.faces(">Y").workplane(-0.5).split(keepTop=True) self.saveModel(result) self.assertEqual(8, result.faces().size()) def testSplitKeepingBoth(self): """ Tests splitting a solid """ # drill a hole in the side c = CQ(makeUnitCube()).faces(">Z").workplane().circle(0.25).cutThruAll() self.assertEqual(7, c.faces().size()) # now cut it in half sideways result = c.faces(">Y").workplane(-0.5).split(keepTop=True, keepBottom=True) # stack will have both halves, original will be unchanged # two solids are on the stack, eac self.assertEqual(2, result.solids().size()) self.assertEqual(8, result.solids().item(0).faces().size()) self.assertEqual(8, result.solids().item(1).faces().size()) def testSplitKeepingBottom(self): """ Tests splitting a solid improperly """ # Drill a hole in the side c = CQ(makeUnitCube()).faces(">Z").workplane().circle(0.25).cutThruAll() self.assertEqual(7, c.faces().size()) # Now cut it in half sideways result = c.faces(">Y").workplane(-0.5).split(keepTop=False, keepBottom=True) # stack will have both halves, original will be unchanged # one solid is on the stack self.assertEqual(1, result.solids().size()) self.assertEqual(8, result.solids().item(0).faces().size()) def testSplitError(self): # Test split produces the correct error when called with no solid to split. w = Workplane().hLine(1).vLine(1).close() with raises(ValueError): w.split(keepTop=True) # Split should raise ValueError when called with no side kept with raises(ValueError): w.split(keepTop=False, keepBottom=False) def testBoxDefaults(self): """ Tests creating a single box """ s = Workplane("XY").box(2, 3, 4) self.assertEqual(1, s.solids().size()) self.saveModel(s) def testSimpleShell(self): """ Create s simple box """ s1 = Workplane("XY").box(2, 2, 2).faces("+Z").shell(0.05) self.saveModel(s1) self.assertEqual(23, s1.faces().size()) s2 = ( Workplane() .ellipse(4, 2) .extrude(4) .faces(">Z") .shell(+2, kind="intersection") ) self.assertEqual(5, s2.faces().size()) s3 = Workplane().ellipse(4, 2).extrude(4).faces(">Z").shell(+2, kind="arc") self.assertEqual(6, s3.faces().size()) # test error on no solid found s4 = Workplane().hLine(1).vLine(1).close() with raises(ValueError): s4.shell(1) def testClosedShell(self): """ Create a hollow box """ s1 = Workplane("XY").box(2, 2, 2).shell(-0.1) self.assertEqual(12, s1.faces().size()) self.assertTrue(s1.val().isValid()) s2 = Workplane("XY").box(2, 2, 2).shell(0.1) self.assertEqual(32, s2.faces().size()) self.assertTrue(s2.val().isValid()) pts = [(1.0, 0.0), (0.3, 0.2), (0.0, 0.0), (0.3, -0.1), (1.0, -0.03)] s3 = Workplane().polyline(pts).close().extrude(1).shell(-0.05) self.assertTrue(s3.val().isValid()) s4_shape = Workplane("XY").box(2, 2, 2).val() # test that None and empty list both work and are equivalent s4_shell_1 = s4_shape.shell(faceList=None, thickness=-0.1) s4_shell_2 = s4_shape.shell(faceList=[], thickness=-0.1) # this should be the same as the first shape self.assertEqual(len(s4_shell_1.Faces()), s1.faces().size()) self.assertEqual(len(s4_shell_2.Faces()), s1.faces().size()) def testOpenCornerShell(self): s = Workplane("XY").box(1, 1, 1) s1 = s.faces("+Z") s1.add(s.faces("+Y")).add(s.faces("+X")) self.saveModel(s1.shell(0.2)) # Tests the list option variation of add s1 = s.faces("+Z") s1.add(s.faces("+Y")).add([s.faces("+X")]) # Tests the raw object option variation of add s1 = s.faces("+Z") s1.add(s.faces("+Y")).add(s.faces("+X").val().wrapped) def testTopFaceFillet(self): s = Workplane("XY").box(1, 1, 1).faces("+Z").edges().fillet(0.1) self.assertEqual(s.faces().size(), 10) self.saveModel(s) def testBoxPointList(self): """ Tests creating an array of boxes """ s = ( Workplane("XY") .rect(4.0, 4.0, forConstruction=True) .vertices() .box(0.25, 0.25, 0.25, combine=True) ) # 1 object, 4 solids because the object is a compound self.assertEqual(4, s.solids().size()) self.assertEqual(1, s.size()) self.saveModel(s) s = ( Workplane("XY") .rect(4.0, 4.0, forConstruction=True) .vertices() .box(0.25, 0.25, 0.25, combine=False) ) # 4 objects, 4 solids, because each is a separate solid self.assertEqual(4, s.size()) self.assertEqual(4, s.solids().size()) def testBoxCombine(self): s = ( Workplane("XY") .box(4, 4, 0.5) .faces(">Z") .workplane() .rect(3, 3, forConstruction=True) .vertices() .box(0.25, 0.25, 0.25, combine=True) ) self.saveModel(s) self.assertEqual(1, s.solids().size()) # we should have one big solid # should have 26 faces. 6 for the box, and 4x5 for the smaller cubes self.assertEqual(26, s.faces().size()) def testBoxCentered(self): x, y, z = 10, 11, 12 # check that the bottom corner is where we expect it for all possible combinations of centered b = [True, False] expected_x = [-x / 2, 0] expected_y = [-y / 2, 0] expected_z = [-z / 2, 0] for (xopt, xval), (yopt, yval), (zopt, zval) in product( zip(b, expected_x), zip(b, expected_y), zip(b, expected_z) ): s = ( Workplane() .box(x, y, z, centered=(xopt, yopt, zopt)) .vertices("<X and <Y and <Z") ) self.assertEqual(s.size(), 1) self.assertTupleAlmostEquals(s.val().toTuple(), (xval, yval, zval), 3) # check centered=True produces the same result as centered=(True, True, True) for val in b: s0 = Workplane().box(x, y, z, centered=val).vertices(">X and >Y and >Z") self.assertEqual(s0.size(), 1) s1 = ( Workplane() .box(x, y, z, centered=(val, val, val)) .vertices(">X and >Y and >Z") ) self.assertEqual(s0.size(), 1) self.assertTupleAlmostEquals(s0.val().toTuple(), s1.val().toTuple(), 3) def testSphereDefaults(self): s = Workplane("XY").sphere(10) self.saveModel(s) # Until FreeCAD fixes their sphere operation self.assertEqual(1, s.solids().size()) self.assertEqual(1, s.faces().size()) def testSphereCustom(self): s = Workplane("XY").sphere( 10, angle1=0, angle2=90, angle3=360, centered=(False, False, False) ) self.saveModel(s) self.assertEqual(1, s.solids().size()) self.assertEqual(2, s.faces().size()) # check that the bottom corner is where we expect it for all possible combinations of centered radius = 10 for (xopt, xval), (yopt, yval), (zopt, zval) in product( zip((True, False), (0, radius)), repeat=3 ): s = Workplane().sphere(radius, centered=(xopt, yopt, zopt)) self.assertEqual(s.size(), 1) self.assertTupleAlmostEquals( s.val().Center().toTuple(), (xval, yval, zval), 3 ) # check centered=True produces the same result as centered=(True, True, True) for val in (True, False): s0 = Workplane().sphere(radius, centered=val) self.assertEqual(s0.size(), 1) s1 = Workplane().sphere(radius, centered=(val, val, val)) self.assertEqual(s0.size(), 1) self.assertTupleAlmostEquals( s0.val().Center().toTuple(), s1.val().Center().toTuple(), 3 ) def testSpherePointList(self): s = ( Workplane("XY") .rect(4.0, 4.0, forConstruction=True) .vertices() .sphere(0.25, combine=False) ) # self.saveModel(s) # Until FreeCAD fixes their sphere operation self.assertEqual(4, s.solids().size()) self.assertEqual(4, s.faces().size()) def testSphereCombine(self): s = ( Workplane("XY") .rect(4.0, 4.0, forConstruction=True) .vertices() .sphere(2.25, combine=True) ) # self.saveModel(s) # Until FreeCAD fixes their sphere operation self.assertEqual(1, s.solids().size()) self.assertEqual(4, s.faces().size()) def testCylinderDefaults(self): s = Workplane("XY").cylinder(20, 10) self.assertEqual(1, s.size()) self.assertEqual(1, s.solids().size()) self.assertEqual(3, s.faces().size()) self.assertEqual(2, s.vertices().size()) self.assertTupleAlmostEquals(s.val().Center().toTuple(), (0, 0, 0), 3) def testCylinderCentering(self): radius = 10 height = 40 b = (True, False) expected_x = (0, radius) expected_y = (0, radius) expected_z = (0, height / 2) for (xopt, xval), (yopt, yval), (zopt, zval) in product( zip(b, expected_x), zip(b, expected_y), zip(b, expected_z) ): s = Workplane("XY").cylinder(height, radius, centered=(xopt, yopt, zopt)) self.assertEqual(1, s.size()) self.assertTupleAlmostEquals( s.val().Center().toTuple(), (xval, yval, zval), 3 ) # check centered=True produces the same result as centered=(True, True, True) for val in b: s0 = Workplane("XY").cylinder(height, radius, centered=val) self.assertEqual(s0.size(), 1) s1 = Workplane("XY").cylinder(height, radius, centered=(val, val, val)) self.assertEqual(s1.size(), 1) self.assertTupleAlmostEquals( s0.val().Center().toTuple(), s1.val().Center().toTuple(), 3 ) def testWedgeDefaults(self): s = Workplane("XY").wedge(10, 10, 10, 5, 5, 5, 5) self.saveModel(s) self.assertEqual(1, s.solids().size()) self.assertEqual(5, s.faces().size()) self.assertEqual(5, s.vertices().size()) def testWedgeCentering(self): s = Workplane("XY").wedge( 10, 10, 10, 5, 5, 5, 5, centered=(False, False, False) ) # self.saveModel(s) self.assertEqual(1, s.solids().size()) self.assertEqual(5, s.faces().size()) self.assertEqual(5, s.vertices().size()) # check that the bottom corner is where we expect it for all possible combinations of centered x, y, z = 10, 11, 12 b = [True, False] expected_x = [-x / 2, 0] expected_y = [-y / 2, 0] expected_z = [-z / 2, 0] for (xopt, xval), (yopt, yval), (zopt, zval) in product( zip(b, expected_x), zip(b, expected_y), zip(b, expected_z) ): s = ( Workplane() .wedge(x, y, z, 2, 2, x - 2, z - 2, centered=(xopt, yopt, zopt)) .vertices("<X and <Y and <Z") ) self.assertEqual(s.size(), 1) self.assertTupleAlmostEquals(s.val().toTuple(), (xval, yval, zval), 3) # check centered=True produces the same result as centered=(True, True, True) for val in b: s0 = ( Workplane() .wedge(x, y, z, 2, 2, x - 2, z - 2, centered=val) .vertices(">X and >Z") ) self.assertEqual(s0.size(), 1) s1 = ( Workplane() .wedge(x, y, z, 2, 2, x - 2, z - 2, centered=(val, val, val)) .vertices(">X and >Z") ) self.assertEqual(s0.size(), 1) self.assertTupleAlmostEquals(s0.val().toTuple(), s1.val().toTuple(), 3) def testWedgePointList(self): s = ( Workplane("XY") .rect(4.0, 4.0, forConstruction=True) .vertices() .wedge(10, 10, 10, 5, 5, 5, 5, combine=False) ) # self.saveModel(s) self.assertEqual(4, s.solids().size()) self.assertEqual(20, s.faces().size()) self.assertEqual(20, s.vertices().size()) def testWedgeCombined(self): s = ( Workplane("XY") .rect(4.0, 4.0, forConstruction=True) .vertices() .wedge(10, 10, 10, 5, 5, 5, 5, combine=True) ) # self.saveModel(s) self.assertEqual(1, s.solids().size()) self.assertEqual(12, s.faces().size()) self.assertEqual(16, s.vertices().size()) def testQuickStartXY(self): s = ( Workplane(Plane.XY()) .box(2, 4, 0.5) .faces(">Z") .workplane() .rect(1.5, 3.5, forConstruction=True) .vertices() .cskHole(0.125, 0.25, 82, depth=None) ) self.assertEqual(1, s.solids().size()) self.assertEqual(14, s.faces().size()) self.saveModel(s) def testQuickStartYZ(self): s = ( Workplane(Plane.YZ()) .box(2, 4, 0.5) .faces(">X") .workplane() .rect(1.5, 3.5, forConstruction=True) .vertices() .cskHole(0.125, 0.25, 82, depth=None) ) self.assertEqual(1, s.solids().size()) self.assertEqual(14, s.faces().size()) self.saveModel(s) def testQuickStartXZ(self): s = ( Workplane(Plane.XZ()) .box(2, 4, 0.5) .faces(">Y") .workplane() .rect(1.5, 3.5, forConstruction=True) .vertices() .cskHole(0.125, 0.25, 82, depth=None) ) self.assertEqual(1, s.solids().size()) self.assertEqual(14, s.faces().size()) self.saveModel(s) def testDoubleTwistedLoft(self): s = ( Workplane("XY") .polygon(8, 20.0) .workplane(offset=4.0) .transformed(rotate=Vector(0, 0, 15.0)) .polygon(8, 20) .loft() ) s2 = ( Workplane("XY") .polygon(8, 20.0) .workplane(offset=-4.0) .transformed(rotate=Vector(0, 0, 15.0)) .polygon(8, 20) .loft() ) # self.assertEquals(10,s.faces().size()) # self.assertEquals(1,s.solids().size()) s3 = s.combineSolids(s2) self.saveModel(s3) def testTwistedLoft(self): s = ( Workplane("XY") .polygon(8, 20.0) .workplane(offset=4.0) .transformed(rotate=Vector(0, 0, 15.0)) .polygon(8, 20) .loft() ) self.assertEqual(10, s.faces().size()) self.assertEqual(1, s.solids().size()) self.saveModel(s) def testUnions(self): # duplicates a memory problem of some kind reported when combining lots of objects s = Workplane("XY").rect(0.5, 0.5).extrude(5.0) o = [] beginTime = time.time() for i in range(15): t = Workplane("XY").center(10.0 * i, 0).rect(0.5, 0.5).extrude(5.0) o.append(t) # union stuff for oo in o: s = s.union(oo) print("Total time %0.3f" % (time.time() - beginTime)) # Test unioning a Solid object s = Workplane(Plane.XY()) currentS = s.rect(2.0, 2.0).extrude(0.5) toUnion = s.rect(1.0, 1.0).extrude(1.0) resS = currentS.union(toUnion) self.assertEqual(11, resS.faces().size()) with self.assertRaises(ValueError): resS.union(toUnion.faces().val()) # Test syntactic sugar [__add__ method] sugar1 = currentS | toUnion sugar2 = currentS + toUnion self.assertEqual(resS.faces().size(), sugar1.faces().size()) self.assertEqual(resS.faces().size(), sugar2.faces().size()) def testCombine(self): s = Workplane(Plane.XY()) objects1 = s.rect(2.0, 2.0).extrude(0.5).faces(">Z").rect(1.0, 1.0).extrude(0.5) objects1.combine() self.assertEqual(11, objects1.faces().size()) objects1 = s.rect(2.0, 2.0).extrude(0.5) objects2 = s.rect(1.0, 1.0).extrude(0.5).translate((0, 0, 0.5)) objects2 = objects1.add(objects2).combine(glue=True, tol=None) self.assertEqual(11, objects2.faces().size()) def testCombineSolidsInLoop(self): # duplicates a memory problem of some kind reported when combining lots of objects s = Workplane("XY").rect(0.5, 0.5).extrude(5.0) o = [] beginTime = time.time() for i in range(15): t = Workplane("XY").center(10.0 * i, 0).rect(0.5, 0.5).extrude(5.0) o.append(t) # append the 'good way' for oo in o: s.add(oo) s = s.combineSolids() print("Total time %0.3f" % (time.time() - beginTime)) self.saveModel(s) def testClean(self): """ Tests the `clean()` method which is called automatically. """ # make a cube with a splitter edge on one of the faces # autosimplify should remove the splitter s = ( Workplane("XY") .moveTo(0, 0) .line(5, 0) .line(5, 0) .line(0, 10) .line(-10, 0) .close() .extrude(10) ) self.assertEqual(6, s.faces().size()) # test removal of splitter caused by union operation s = Workplane("XY").box(10, 10, 10).union(Workplane("XY").box(20, 10, 10)) self.assertEqual(6, s.faces().size()) # test removal of splitter caused by extrude+combine operation s = ( Workplane("XY") .box(10, 10, 10) .faces(">Y") .workplane() .rect(5, 10, True) .extrude(20) ) self.assertEqual(10, s.faces().size()) # test removal of splitter caused by double hole operation s = ( Workplane("XY") .box(10, 10, 10) .faces(">Z") .workplane() .hole(3, 5) .faces(">Z") .workplane() .hole(3, 10) ) self.assertEqual(7, s.faces().size()) # test removal of splitter caused by cutThruAll s = ( Workplane("XY") .box(10, 10, 10) .faces(">Y") .workplane() .rect(10, 5) .cutBlind(-5) .faces(">Z") .workplane(centerOption="CenterOfMass") .center(0, 2.5) .rect(5, 5) .cutThruAll() ) self.assertEqual(18, s.faces().size()) # test removal of splitter with box s = Workplane("XY").box(5, 5, 5).box(10, 5, 2) self.assertEqual(14, s.faces().size()) def testNoClean(self): """ Test the case when clean is disabled. """ # test disabling autoSimplify s = ( Workplane("XY") .moveTo(0, 0) .line(5, 0) .line(5, 0) .line(0, 10) .line(-10, 0) .close() .extrude(10, clean=False) ) self.assertEqual(7, s.faces().size()) s = ( Workplane("XY") .box(10, 10, 10) .union(Workplane("XY").box(20, 10, 10), clean=False) ) self.assertEqual(14, s.faces().size()) s = ( Workplane("XY") .box(10, 10, 10) .faces(">Y") .workplane() .rect(5, 10, True) .extrude(20, clean=False) ) self.assertEqual(12, s.faces().size()) def testExplicitClean(self): """ Test running of `clean()` method explicitly. """ s = ( Workplane("XY") .moveTo(0, 0) .line(5, 0) .line(5, 0) .line(0, 10) .line(-10, 0) .close() .extrude(10, clean=False) .clean() ) self.assertEqual(6, s.faces().size()) def testPlanes(self): """ Test other planes other than the normal ones (XY, YZ) """ # ZX plane s = Workplane(Plane.ZX()) result = ( s.rect(2.0, 4.0) .extrude(0.5) .faces(">Z") .workplane() .rect(1.5, 3.5, forConstruction=True) .vertices() .cskHole(0.125, 0.25, 82, depth=None) ) self.saveModel(result) # YX plane s = Workplane(Plane.YX()) result = ( s.rect(2.0, 4.0) .extrude(0.5) .faces(">Z") .workplane() .rect(1.5, 3.5, forConstruction=True) .vertices() .cskHole(0.125, 0.25, 82, depth=None) ) self.saveModel(result) # YX plane s = Workplane(Plane.YX()) result = ( s.rect(2.0, 4.0) .extrude(0.5) .faces(">Z") .workplane() .rect(1.5, 3.5, forConstruction=True) .vertices() .cskHole(0.125, 0.25, 82, depth=None) ) self.saveModel(result) # ZY plane s = Workplane(Plane.ZY()) result = ( s.rect(2.0, 4.0) .extrude(0.5) .faces(">Z") .workplane() .rect(1.5, 3.5, forConstruction=True) .vertices() .cskHole(0.125, 0.25, 82, depth=None) ) self.saveModel(result) # front plane s = Workplane(Plane.front()) result = ( s.rect(2.0, 4.0) .extrude(0.5) .faces(">Z") .workplane() .rect(1.5, 3.5, forConstruction=True) .vertices() .cskHole(0.125, 0.25, 82, depth=None) ) self.saveModel(result) # back plane s = Workplane(Plane.back()) result = ( s.rect(2.0, 4.0) .extrude(0.5) .faces(">Z") .workplane() .rect(1.5, 3.5, forConstruction=True) .vertices() .cskHole(0.125, 0.25, 82, depth=None) ) self.saveModel(result) # left plane s = Workplane(Plane.left()) result = ( s.rect(2.0, 4.0) .extrude(0.5) .faces(">Z") .workplane() .rect(1.5, 3.5, forConstruction=True) .vertices() .cskHole(0.125, 0.25, 82, depth=None) ) self.saveModel(result) # right plane s = Workplane(Plane.right()) result = ( s.rect(2.0, 4.0) .extrude(0.5) .faces(">Z") .workplane() .rect(1.5, 3.5, forConstruction=True) .vertices() .cskHole(0.125, 0.25, 82, depth=None) ) self.saveModel(result) # top plane s = Workplane(Plane.top()) result = ( s.rect(2.0, 4.0) .extrude(0.5) .faces(">Z") .workplane() .rect(1.5, 3.5, forConstruction=True) .vertices() .cskHole(0.125, 0.25, 82, depth=None) ) self.saveModel(result) # bottom plane s = Workplane(Plane.bottom()) result = ( s.rect(2.0, 4.0) .extrude(0.5) .faces(">Z") .workplane() .rect(1.5, 3.5, forConstruction=True) .vertices() .cskHole(0.125, 0.25, 82, depth=None) ) self.saveModel(result) def testIsInside(self): """ Testing if one box is inside of another. """ box1 = Workplane(Plane.XY()).box(10, 10, 10) box2 = Workplane(Plane.XY()).box(5, 5, 5) self.assertFalse(box2.val().BoundingBox().isInside(box1.val().BoundingBox())) self.assertTrue(box1.val().BoundingBox().isInside(box2.val().BoundingBox())) def testCup(self): """ UOM = "mm" # # PARAMETERS and PRESETS # These parameters can be manipulated by end users # bottomDiameter = FloatParam(min=10.0,presets={'default':50.0,'tumbler':50.0,'shot':35.0,'tea':50.0,'saucer':100.0},group="Basics", desc="Bottom diameter") topDiameter = FloatParam(min=10.0,presets={'default':85.0,'tumbler':85.0,'shot':50.0,'tea':51.0,'saucer':400.0 },group="Basics", desc="Top diameter") thickness = FloatParam(min=0.1,presets={'default':2.0,'tumbler':2.0,'shot':2.66,'tea':2.0,'saucer':2.0},group="Basics", desc="Thickness") height = FloatParam(min=1.0,presets={'default':80.0,'tumbler':80.0,'shot':59.0,'tea':125.0,'saucer':40.0},group="Basics", desc="Overall height") lipradius = FloatParam(min=1.0,presets={'default':1.0,'tumbler':1.0,'shot':0.8,'tea':1.0,'saucer':1.0},group="Basics", desc="Lip Radius") bottomThickness = FloatParam(min=1.0,presets={'default':5.0,'tumbler':5.0,'shot':10.0,'tea':10.0,'saucer':5.0},group="Basics", desc="BottomThickness") # # Your build method. It must return a solid object # def build(): br = bottomDiameter.value / 2.0 tr = topDiameter.value / 2.0 t = thickness.value s1 = Workplane("XY").circle(br).workplane(offset=height.value).circle(tr).loft() s2 = Workplane("XY").workplane(offset=bottomThickness.value).circle(br - t ).workplane(offset=height.value - t ).circle(tr - t).loft() cup = s1.cut(s2) cup.faces(">Z").edges().fillet(lipradius.value) return cup """ # for some reason shell doesn't work on this simple shape. how disappointing! td = 50.0 bd = 20.0 h = 10.0 t = 1.0 s1 = Workplane("XY").circle(bd).workplane(offset=h).circle(td).loft() s2 = ( Workplane("XY") .workplane(offset=t) .circle(bd - (2.0 * t)) .workplane(offset=(h - t)) .circle(td - (2.0 * t)) .loft() ) s3 = s1.cut(s2) self.saveModel(s3) def testEnclosure(self): """ Builds an electronics enclosure Original FreeCAD script: 81 source statements ,not including variables This script: 34 """ # parameter definitions p_outerWidth = 100.0 # Outer width of box enclosure p_outerLength = 150.0 # Outer length of box enclosure p_outerHeight = 50.0 # Outer height of box enclosure p_thickness = 3.0 # Thickness of the box walls p_sideRadius = 10.0 # Radius for the curves around the sides of the bo # Radius for the curves on the top and bottom edges of the box p_topAndBottomRadius = 2.0 # How far in from the edges the screwposts should be place. p_screwpostInset = 12.0 # Inner Diameter of the screwpost holes, should be roughly screw diameter not including threads p_screwpostID = 4.0 # Outer Diameter of the screwposts.\nDetermines overall thickness of the posts p_screwpostOD = 10.0 p_boreDiameter = 8.0 # Diameter of the counterbore hole, if any p_boreDepth = 1.0 # Depth of the counterbore hole, if # Outer diameter of countersink. Should roughly match the outer diameter of the screw head p_countersinkDiameter = 0.0 # Countersink angle (complete angle between opposite sides, not from center to one side) p_countersinkAngle = 90.0 # Whether to place the lid with the top facing down or not. p_flipLid = True # Height of lip on the underside of the lid.\nSits inside the box body for a snug fit. p_lipHeight = 1.0 # outer shell oshell = ( Workplane("XY") .rect(p_outerWidth, p_outerLength) .extrude(p_outerHeight + p_lipHeight) ) # weird geometry happens if we make the fillets in the wrong order if p_sideRadius > p_topAndBottomRadius: oshell = ( oshell.edges("|Z") .fillet(p_sideRadius) .edges("#Z") .fillet(p_topAndBottomRadius) ) else: oshell = ( oshell.edges("#Z") .fillet(p_topAndBottomRadius) .edges("|Z") .fillet(p_sideRadius) ) # inner shell ishell = ( oshell.faces("<Z") .workplane(p_thickness, True) .rect( (p_outerWidth - 2.0 * p_thickness), (p_outerLength - 2.0 * p_thickness) ) .extrude((p_outerHeight - 2.0 * p_thickness), False) ) # set combine false to produce just the new boss ishell = ishell.edges("|Z").fillet(p_sideRadius - p_thickness) # make the box outer box box = oshell.cut(ishell) # make the screwposts POSTWIDTH = p_outerWidth - 2.0 * p_screwpostInset POSTLENGTH = p_outerLength - 2.0 * p_screwpostInset box = ( box.faces(">Z") .workplane(-p_thickness) .rect(POSTWIDTH, POSTLENGTH, forConstruction=True) .vertices() .circle(p_screwpostOD / 2.0) .circle(p_screwpostID / 2.0) .extrude((-1.0) * (p_outerHeight + p_lipHeight - p_thickness), True) ) # split lid into top and bottom parts (lid, bottom) = ( box.faces(">Z") .workplane(-p_thickness - p_lipHeight) .split(keepTop=True, keepBottom=True) .all() ) # splits into two solids # translate the lid, and subtract the bottom from it to produce the lid inset lowerLid = lid.translate((0, 0, -p_lipHeight)) cutlip = lowerLid.cut(bottom).translate( (p_outerWidth + p_thickness, 0, p_thickness - p_outerHeight + p_lipHeight) ) # compute centers for counterbore/countersink or counterbore topOfLidCenters = ( cutlip.faces(">Z") .workplane() .rect(POSTWIDTH, POSTLENGTH, forConstruction=True) .vertices() ) # add holes of the desired type if p_boreDiameter > 0 and p_boreDepth > 0: topOfLid = topOfLidCenters.cboreHole( p_screwpostID, p_boreDiameter, p_boreDepth, (2.0) * p_thickness ) elif p_countersinkDiameter > 0 and p_countersinkAngle > 0: topOfLid = topOfLidCenters.cskHole( p_screwpostID, p_countersinkDiameter, p_countersinkAngle, (2.0) * p_thickness, ) else: topOfLid = topOfLidCenters.hole(p_screwpostID, (2.0) * p_thickness) # flip lid upside down if desired if p_flipLid: topOfLid.rotateAboutCenter((1, 0, 0), 180) # return the combined result result = topOfLid.union(bottom) self.saveModel(result) def testExtrude(self): """ Test extrude """ r = 1.0 h = 1.0 decimal_places = 9.0 # extrude in one direction s = Workplane("XY").circle(r).extrude(h, both=False) top_face = s.faces(">Z") bottom_face = s.faces("<Z") # calculate the distance between the top and the bottom face delta = top_face.val().Center().sub(bottom_face.val().Center()) self.assertTupleAlmostEquals(delta.toTuple(), (0.0, 0.0, h), decimal_places) # extrude symmetrically s = Workplane("XY").circle(r).extrude(h, both=True) self.assertTrue(len(s.val().Solids()) == 1) top_face = s.faces(">Z") bottom_face = s.faces("<Z") # calculate the distance between the top and the bottom face delta = top_face.val().Center().sub(bottom_face.val().Center()) self.assertTupleAlmostEquals( delta.toTuple(), (0.0, 0.0, 2.0 * h), decimal_places ) # check that non-conplanar extrusion raises with self.assertRaises(ValueError): Workplane().box(1, 1, 1).faces().circle(0.1).extrude(0.1) def testTaperedExtrudeCutBlind(self): h = 1.0 r = 1.0 t = 5 # extrude with a positive taper s = Workplane("XY").circle(r).extrude(h, taper=t) top_face = s.faces(">Z") bottom_face = s.faces("<Z") # top and bottom face area delta = top_face.val().Area() - bottom_face.val().Area() self.assertTrue(delta < 0) # extrude with a negative taper s = Workplane("XY").circle(r).extrude(h, taper=-t) top_face = s.faces(">Z") bottom_face = s.faces("<Z") # top and bottom face area delta = top_face.val().Area() - bottom_face.val().Area() self.assertTrue(delta > 0) # cut a tapered hole s = ( Workplane("XY") .rect(2 * r, 2 * r) .extrude(2 * h) .faces(">Z") .workplane() .rect(r, r) .cutBlind(-h, taper=t) ) middle_face = s.faces(">Z[-2]") self.assertTrue(middle_face.val().Area() < 1) def testClose(self): # Close without endPoint and startPoint coincide. # Create a half-circle a = Workplane(Plane.XY()).sagittaArc((10, 0), 2).close().extrude(2) # Close when endPoint and startPoint coincide. # Create a double half-circle b = ( Workplane(Plane.XY()) .sagittaArc((10, 0), 2) .sagittaArc((0, 0), 2) .close() .extrude(2) ) # The b shape shall have twice the volume of the a shape. self.assertAlmostEqual(a.val().Volume() * 2.0, b.val().Volume()) # Testcase 3 from issue #238 thickness = 3.0 length = 10.0 width = 5.0 obj1 = ( Workplane("XY", origin=(0, 0, -thickness / 2)) .moveTo(length / 2, 0) .threePointArc((0, width / 2), (-length / 2, 0)) .threePointArc((0, -width / 2), (length / 2, 0)) .close() .extrude(thickness) ) os_x = 8.0 # Offset in X os_y = -19.5 # Offset in Y obj2 = ( Workplane("YZ", origin=(os_x, os_y, -thickness / 2)) .moveTo(os_x + length / 2, os_y) .sagittaArc((os_x - length / 2, os_y), width / 2) .sagittaArc((os_x + length / 2, os_y), width / 2) .close() .extrude(thickness) ) # The obj1 shape shall have the same volume as the obj2 shape. self.assertAlmostEqual(obj1.val().Volume(), obj2.val().Volume()) def testText(self): global testdataDir box = Workplane("XY").box(4, 4, 0.5) obj1 = ( box.faces(">Z") .workplane() .text( "CQ 2.0", 0.5, -0.05, cut=True, halign="left", valign="bottom", font="Sans", ) ) # combined object should have smaller volume self.assertGreater(box.val().Volume(), obj1.val().Volume()) obj2 = ( box.faces(">Z") .workplane() .text("CQ 2.0", 0.5, 0.05, cut=False, combine=True, font="Sans") ) # combined object should have bigger volume self.assertLess(box.val().Volume(), obj2.val().Volume()) # verify that the number of top faces is correct (NB: this is font specific) self.assertEqual(len(obj2.faces(">Z").vals()), 5) obj3 = ( box.faces(">Z") .workplane() .text( "CQ 2.0", 0.5, 0.05, cut=False, combine=False, halign="right", valign="top", font="Sans", ) ) # verify that the number of solids is correct self.assertEqual(len(obj3.solids().vals()), 5) obj4 = ( box.faces(">Z") .workplane() .text( "CQ 2.0", 0.5, 0.05, fontPath=os.path.join(testdataDir, "OpenSans-Regular.ttf"), cut=False, combine=False, halign="right", valign="top", font="Sans", ) ) # verify that the number of solids is correct self.assertEqual(len(obj4.solids().vals()), 5) # test to see if non-existent file causes segfault obj5 = ( box.faces(">Z") .workplane() .text( "CQ 2.0", 0.5, 0.05, fontPath=os.path.join(testdataDir, "OpenSans-Irregular.ttf"), cut=False, combine=False, halign="right", valign="top", font="Sans", ) ) # verify that the number of solids is correct self.assertEqual(len(obj5.solids().vals()), 5) # check it doesn't fall over with int sizes obj1 = ( box.faces(">Z") .workplane() .text( "CQ 2.0", 10, -1, cut=True, halign="left", valign="bottom", font="Sans", ) ) def testParametricCurve(self): from math import sin, cos, pi k = 4 r = 1 func = lambda t: ( r * (k + 1) * cos(t) - r * cos((k + 1) * t), r * (k + 1) * sin(t) - r * sin((k + 1) * t), ) res_open = Workplane("XY").parametricCurve(func).extrude(3) # open profile generates an invalid solid self.assertFalse(res_open.solids().val().isValid()) res_closed = ( Workplane("XY").parametricCurve(func, start=0, stop=2 * pi).extrude(3) ) # closed profile will generate a valid solid with 3 faces self.assertTrue(res_closed.solids().val().isValid()) self.assertEqual(len(res_closed.faces().vals()), 3) res_edge = Workplane("XY").parametricCurve(func, makeWire=False) self.assertEqual(len(res_edge.ctx.pendingEdges), 1) self.assertEqual(len(res_edge.ctx.pendingWires), 0) def testMakeShellSolid(self): c0 = math.sqrt(2) / 4 vertices = [[c0, -c0, c0], [c0, c0, -c0], [-c0, c0, c0], [-c0, -c0, -c0]] faces_ixs = [[0, 1, 2, 0], [1, 0, 3, 1], [2, 3, 0, 2], [3, 2, 1, 3]] faces = [] for ixs in faces_ixs: lines = [] for v1, v2 in zip(ixs, ixs[1:]): lines.append( Edge.makeLine(Vector(*vertices[v1]), Vector(*vertices[v2])) ) wire = Wire.combine(lines)[0] faces.append(Face.makeFromWires(wire)) shell = Shell.makeShell(faces) solid = Solid.makeSolid(shell) self.assertTrue(shell.isValid()) self.assertTrue(solid.isValid()) self.assertEqual(len(solid.Vertices()), 4) self.assertEqual(len(solid.Faces()), 4) def testIsInsideSolid(self): # test solid model = Workplane("XY").box(10, 10, 10) solid = model.val() # get first object on stack self.assertTrue(solid.isInside((0, 0, 0))) self.assertFalse(solid.isInside((10, 10, 10))) self.assertTrue(solid.isInside((Vector(3, 3, 3)))) self.assertFalse(solid.isInside((Vector(30.0, 30.0, 30.0)))) self.assertTrue(solid.isInside((0, 0, 4.99), tolerance=0.1)) self.assertTrue(solid.isInside((0, 0, 5))) # check point on surface self.assertTrue(solid.isInside((0, 0, 5.01), tolerance=0.1)) self.assertFalse(solid.isInside((0, 0, 5.1), tolerance=0.1)) # test compound solid model = Workplane("XY").box(10, 10, 10) model = model.moveTo(50, 50).box(10, 10, 10) solid = model.val() self.assertTrue(solid.isInside((0, 0, 0))) self.assertTrue(solid.isInside((50, 50, 0))) self.assertFalse(solid.isInside((50, 56, 0))) # make sure raises on non solid model = Workplane("XY").rect(10, 10) solid = model.val() with self.assertRaises(AttributeError): solid.isInside((0, 0, 0)) # test solid with an internal void void = Workplane("XY").box(10, 10, 10) model = Workplane("XY").box(100, 100, 100).cut(void) solid = model.val() self.assertFalse(solid.isInside((0, 0, 0))) self.assertTrue(solid.isInside((40, 40, 40))) self.assertFalse(solid.isInside((55, 55, 55))) def testWorkplaneCenterOptions(self): """ Test options for specifying origin of workplane """ decimal_places = 9 pts = [(0, 0), (90, 0), (90, 30), (30, 30), (30, 60), (0.0, 60)] r = Workplane("XY").polyline(pts).close().extrude(10.0) origin = ( r.faces(">Z") .workplane(centerOption="ProjectedOrigin") .plane.origin.toTuple() ) self.assertTupleAlmostEquals(origin, (0.0, 0.0, 10.0), decimal_places) origin = ( r.faces(">Z").workplane(centerOption="CenterOfMass").plane.origin.toTuple() ) self.assertTupleAlmostEquals(origin, (37.5, 22.5, 10.0), decimal_places) origin = ( r.faces(">Z") .workplane(centerOption="CenterOfBoundBox") .plane.origin.toTuple() ) self.assertTupleAlmostEquals(origin, (45.0, 30.0, 10.0), decimal_places) origin = ( r.faces(">Z") .workplane(centerOption="ProjectedOrigin", origin=(30, 10, 20)) .plane.origin.toTuple() ) self.assertTupleAlmostEquals(origin, (30.0, 10.0, 10.0), decimal_places) origin = ( r.faces(">Z") .workplane(centerOption="ProjectedOrigin", origin=Vector(30, 10, 20)) .plane.origin.toTuple() ) self.assertTupleAlmostEquals(origin, (30.0, 10.0, 10.0), decimal_places) with self.assertRaises(ValueError): origin = r.faces(">Z").workplane(centerOption="undefined") # test case where plane origin is shifted with center call r = ( r.faces(">Z") .workplane(centerOption="ProjectedOrigin") .center(30, 0) .hole(90) ) origin = ( r.faces(">Z") .workplane(centerOption="ProjectedOrigin") .plane.origin.toTuple() ) self.assertTupleAlmostEquals(origin, (30.0, 0.0, 10.0), decimal_places) origin = ( r.faces(">Z") .workplane(centerOption="ProjectedOrigin", origin=(0, 0, 0)) .plane.origin.toTuple() ) self.assertTupleAlmostEquals(origin, (0.0, 0.0, 10.0), decimal_places) # make sure projection works in all directions r = Workplane("YZ").polyline(pts).close().extrude(10.0) origin = ( r.faces(">X") .workplane(centerOption="ProjectedOrigin") .plane.origin.toTuple() ) self.assertTupleAlmostEquals(origin, (10.0, 0.0, 0.0), decimal_places) origin = ( r.faces(">X").workplane(centerOption="CenterOfMass").plane.origin.toTuple() ) self.assertTupleAlmostEquals(origin, (10.0, 37.5, 22.5), decimal_places) origin = ( r.faces(">X") .workplane(centerOption="CenterOfBoundBox") .plane.origin.toTuple() ) self.assertTupleAlmostEquals(origin, (10.0, 45.0, 30.0), decimal_places) r = Workplane("XZ").polyline(pts).close().extrude(10.0) origin = ( r.faces("<Y") .workplane(centerOption="ProjectedOrigin") .plane.origin.toTuple() ) self.assertTupleAlmostEquals(origin, (0.0, -10.0, 0.0), decimal_places) origin = ( r.faces("<Y").workplane(centerOption="CenterOfMass").plane.origin.toTuple() ) self.assertTupleAlmostEquals(origin, (37.5, -10.0, 22.5), decimal_places) origin = ( r.faces("<Y") .workplane(centerOption="CenterOfBoundBox") .plane.origin.toTuple() ) self.assertTupleAlmostEquals(origin, (45.0, -10.0, 30.0), decimal_places) def testFindSolid(self): r = Workplane("XY").pushPoints([(-2, 0), (2, 0)]).box(1, 1, 1, combine=False) # there should be two solids on the stack self.assertEqual(len(r.objects), 2) self.assertTrue(isinstance(r.val(), Solid)) # find solid should return a compound of two solids s = r.findSolid() self.assertEqual(len(s.Solids()), 2) self.assertTrue(isinstance(s, Compound)) # if no solids are found, should raise ValueError w = Workplane().hLine(1).close() with raises(ValueError): w.findSolid() def testSlot2D(self): decimal_places = 9 # Ensure it produces a solid with the correct volume result = Workplane("XY").slot2D(4, 1, 0).extrude(1) self.assertAlmostEqual(result.val().Volume(), 3.785398163, decimal_places) # Test for proper expected behaviour when cutting box = Workplane("XY").box(5, 5, 1) result = box.faces(">Z").workplane().slot2D(4, 1, 0).cutThruAll() self.assertAlmostEqual(result.val().Volume(), 21.214601837, decimal_places) result = box.faces(">Z").workplane().slot2D(4, 1, 0).cutBlind(-0.5) self.assertAlmostEqual(result.val().Volume(), 23.107300918, decimal_places) # Test to see if slot is rotated correctly result = Workplane("XY").slot2D(4, 1, 45).extrude(1) point = result.faces(">Z").edges(">X").first().val().startPoint().toTuple() self.assertTupleAlmostEquals( point, (0.707106781, 1.414213562, 1.0), decimal_places ) def test_assembleEdges(self): # Plate with 5 sides and 2 bumps, one side is not co-planar with the other sides # Passes an open wire to assembleEdges so that IsDone is true but Error returns 2 to test the warning functionality. edge_points = [ [-7.0, -7.0, 0.0], [-3.0, -10.0, 3.0], [7.0, -7.0, 0.0], [7.0, 7.0, 0.0], [-7.0, 7.0, 0.0], ] edge_wire = Workplane("XY").polyline( [(-7.0, -7.0), (7.0, -7.0), (7.0, 7.0), (-7.0, 7.0)] ) edge_wire = edge_wire.add( Workplane("YZ") .workplane() .transformed(offset=Vector(0, 0, -7), rotate=Vector(45, 0, 0)) .spline([(-7.0, 0.0), (3, -3), (7.0, 0.0)]) ) edge_wire = [o.vals()[0] for o in edge_wire.all()] edge_wire = Wire.assembleEdges(edge_wire) # Embossed star, need to change optional parameters to obtain nice looking result. r1 = 3.0 r2 = 10.0 fn = 6 edge_points = [ [r1 * math.cos(i * math.pi / fn), r1 * math.sin(i * math.pi / fn)] if i % 2 == 0 else [r2 * math.cos(i * math.pi / fn), r2 * math.sin(i * math.pi / fn)] for i in range(2 * fn + 1) ] edge_wire = Workplane("XY").polyline(edge_points) edge_wire = [o.vals()[0] for o in edge_wire.all()] edge_wire = Wire.assembleEdges(edge_wire) # Points on hexagonal pattern coordinates, use of pushpoints. r1 = 1.0 fn = 6 edge_points = [ [r1 * math.cos(i * 2 * math.pi / fn), r1 * math.sin(i * 2 * math.pi / fn)] for i in range(fn + 1) ] surface_points = [ [0.25, 0, 0.75], [-0.25, 0, 0.75], [0, 0.25, 0.75], [0, -0.25, 0.75], [0, 0, 2], ] edge_wire = Workplane("XY").polyline(edge_points) edge_wire = [o.vals()[0] for o in edge_wire.all()] edge_wire = Wire.assembleEdges(edge_wire) # Gyroïd, all edges are splines on different workplanes. edge_points = [ [[3.54, 3.54], [1.77, 0.0], [3.54, -3.54]], [[-3.54, -3.54], [0.0, -1.77], [3.54, -3.54]], [[-3.54, -3.54], [0.0, -1.77], [3.54, -3.54]], [[-3.54, -3.54], [-1.77, 0.0], [-3.54, 3.54]], [[3.54, 3.54], [0.0, 1.77], [-3.54, 3.54]], [[3.54, 3.54], [0.0, 1.77], [-3.54, 3.54]], ] plane_list = ["XZ", "XY", "YZ", "XZ", "YZ", "XY"] offset_list = [-3.54, 3.54, 3.54, 3.54, -3.54, -3.54] edge_wire = ( Workplane(plane_list[0]) .workplane(offset=-offset_list[0]) .spline(edge_points[0]) ) for i in range(len(edge_points) - 1): edge_wire = edge_wire.add( Workplane(plane_list[i + 1]) .workplane(offset=-offset_list[i + 1]) .spline(edge_points[i + 1]) ) edge_wire = [o.vals()[0] for o in edge_wire.all()] edge_wire = Wire.assembleEdges(edge_wire) def testTag(self): # test tagging result = ( Workplane("XY") .pushPoints([(-2, 0), (2, 0)]) .box(1, 1, 1, combine=False) .tag("2 solids") .union(Workplane("XY").box(6, 1, 1)) ) self.assertEqual(len(result.objects), 1) result = result._getTagged("2 solids") self.assertEqual(len(result.objects), 2) with self.assertRaises(ValueError): result = result._getTagged("3 solids") def testCopyWorkplane(self): obj0 = Workplane("XY").box(1, 1, 10).faces(">Z").workplane() obj1 = Workplane("XY").copyWorkplane(obj0).box(1, 1, 1) self.assertTupleAlmostEquals((0, 0, 5), obj1.val().Center().toTuple(), 9) def testWorkplaneFromTagged(self): # create a flat, wide base. Extrude one object 4 units high, another # object on top of it 6 units high. Go back to base plane. Extrude an # object 11 units high. Assert that top face is 11 units high. result = ( Workplane("XY") .box(10, 10, 1, centered=(True, True, False)) .faces(">Z") .workplane() .tag("base") .center(3, 0) .rect(2, 2) .extrude(4) .faces(">Z") .workplane() .circle(1) .extrude(6) .workplaneFromTagged("base") .center(-3, 0) .circle(1) .extrude(11) ) self.assertTupleAlmostEquals( result.faces(">Z").val().Center().toTuple(), (-3, 0, 12), 9 ) def testWorkplaneOrientationOnVertex(self): # create a 10 unit sized cube on the XY plane parent = Workplane("XY").rect(10.0, 10.0).extrude(10) # assert that the direction tuples reflect accordingly assert parent.plane.xDir.toTuple() == approx((1.0, 0.0, 0.0)) assert parent.plane.zDir.toTuple() == approx((0.0, 0.0, 1.0)) # select the <XZ vertex on the <Y face and create a new workplane. child = parent.faces("<Y").vertices("<XZ").workplane() # assert that the direction tuples reflect the new workplane on the <Y face assert child.plane.xDir.toTuple() == approx((1.0, 0.0, -0.0)) assert child.plane.zDir.toTuple() == approx((0.0, -1.0, -0.0)) def testTagSelectors(self): result0 = Workplane("XY").box(1, 1, 1).tag("box").sphere(1) # result is currently a sphere self.assertEqual(1, result0.faces().size()) # a box has 8 vertices self.assertEqual(8, result0.vertices(tag="box").size()) # 6 faces self.assertEqual(6, result0.faces(tag="box").size()) # 12 edges self.assertEqual(12, result0.edges(tag="box").size()) # 6 wires self.assertEqual(6, result0.wires(tag="box").size()) # create two solids, tag them, join to one solid result1 = ( Workplane("XY") .pushPoints([(1, 0), (-1, 0)]) .box(1, 1, 1) .tag("boxes") .sphere(1) ) self.assertEqual(1, result1.solids().size()) self.assertEqual(2, result1.solids(tag="boxes").size()) self.assertEqual(1, result1.shells().size()) self.assertEqual(2, result1.shells(tag="boxes").size()) # create 4 individual objects, tag it, then combine to one compound result2 = ( Workplane("XY") .rect(4, 4) .vertices() .box(1, 1, 1, combine=False) .tag("4 objs") ) result2 = result2.newObject([Compound.makeCompound(result2.objects)]) self.assertEqual(1, result2.compounds().size()) self.assertEqual(0, result2.compounds(tag="4 objs").size()) def test_interpPlate(self): """ Tests the interpPlate() functionalities Numerical values of Areas and Volumes were obtained with the Area() and Volume() functions on a Linux machine under Debian 10 with python 3.7. """ # example from PythonOCC core_geometry_geomplate.py, use of thickness = 0 returns 2D surface. thickness = 0 edge_points = [ [0.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 10.0, 10.0], [0.0, 0.0, 10.0], ] surface_points = [[5.0, 5.0, 5.0]] plate_0 = Workplane("XY").interpPlate(edge_points, surface_points, thickness) self.assertTrue(plate_0.val().isValid()) self.assertAlmostEqual(plate_0.val().Area(), 141.218823892, 1) # Plate with 5 sides and 2 bumps, one side is not co-planar with the other sides thickness = 0.1 edge_points = [ [-7.0, -7.0, 0.0], [-3.0, -10.0, 3.0], [7.0, -7.0, 0.0], [7.0, 7.0, 0.0], [-7.0, 7.0, 0.0], ] edge_wire = Workplane("XY").polyline( [(-7.0, -7.0), (7.0, -7.0), (7.0, 7.0), (-7.0, 7.0)] ) # edge_wire = edge_wire.add(Workplane('YZ').workplane().transformed(offset=Vector(0, 0, -7), rotate=Vector(45, 0, 0)).polyline([(-7.,0.), (3,-3), (7.,0.)])) # In CadQuery Sept-2019 it worked with rotate=Vector(0, 45, 0). In CadQuery Dec-2019 rotate=Vector(45, 0, 0) only closes the wire. edge_wire = edge_wire.add( Workplane("YZ") .workplane() .transformed(offset=Vector(0, 0, -7), rotate=Vector(45, 0, 0)) .spline([(-7.0, 0.0), (3, -3), (7.0, 0.0)]) ) surface_points = [[-3.0, -3.0, -3.0], [3.0, 3.0, 3.0]] plate_1 = Workplane("XY").interpPlate(edge_wire, surface_points, thickness) self.assertTrue(plate_1.val().isValid()) self.assertAlmostEqual(plate_1.val().Volume(), 26.124970206, 2) # Embossed star, need to change optional parameters to obtain nice looking result. r1 = 3.0 r2 = 10.0 fn = 6 thickness = 0.1 edge_points = [ [r1 * math.cos(i * math.pi / fn), r1 * math.sin(i * math.pi / fn)] if i % 2 == 0 else [r2 * math.cos(i * math.pi / fn), r2 * math.sin(i * math.pi / fn)] for i in range(2 * fn + 1) ] edge_wire = Workplane("XY").polyline(edge_points) r2 = 4.5 surface_points = [ [r2 * math.cos(i * math.pi / fn), r2 * math.sin(i * math.pi / fn), 1.0] for i in range(2 * fn) ] + [[0.0, 0.0, -2.0]] plate_2 = Workplane("XY").interpPlate( edge_wire, surface_points, thickness, combine=True, clean=True, degree=3, nbPtsOnCur=15, nbIter=2, anisotropy=False, tol2d=0.00001, tol3d=0.0001, tolAng=0.01, tolCurv=0.1, maxDeg=8, maxSegments=49, ) self.assertTrue(plate_2.val().isValid()) self.assertAlmostEqual(plate_2.val().Volume(), 10.956054314, 0) # Points on hexagonal pattern coordinates, use of pushpoints. r1 = 1.0 N = 3 ca = math.cos(30.0 * math.pi / 180.0) sa = math.sin(30.0 * math.pi / 180.0) # EVEN ROWS pts = [ (-3.0, -3.0), (-1.267949, -3.0), (0.464102, -3.0), (2.196152, -3.0), (-3.0, 0.0), (-1.267949, 0.0), (0.464102, 0.0), (2.196152, 0.0), (-2.133974, -1.5), (-0.401923, -1.5), (1.330127, -1.5), (3.062178, -1.5), (-2.133975, 1.5), (-0.401924, 1.5), (1.330127, 1.5), (3.062178, 1.5), ] # Spike surface thickness = 0.1 fn = 6 edge_points = [ [ r1 * math.cos(i * 2 * math.pi / fn + 30 * math.pi / 180), r1 * math.sin(i * 2 * math.pi / fn + 30 * math.pi / 180), ] for i in range(fn + 1) ] surface_points = [ [ r1 / 4 * math.cos(i * 2 * math.pi / fn + 30 * math.pi / 180), r1 / 4 * math.sin(i * 2 * math.pi / fn + 30 * math.pi / 180), 0.75, ] for i in range(fn + 1) ] + [[0, 0, 2]] edge_wire = Workplane("XY").polyline(edge_points) plate_3 = ( Workplane("XY") .pushPoints(pts) .interpPlate( edge_wire, surface_points, thickness, combine=False, clean=False, degree=2, nbPtsOnCur=20, nbIter=2, anisotropy=False, tol2d=0.00001, tol3d=0.0001, tolAng=0.01, tolCurv=0.1, maxDeg=8, maxSegments=9, ) ) self.assertTrue(plate_3.val().isValid()) self.assertAlmostEqual(plate_3.val().Volume(), 0.45893954685189414, 1) # Gyroïd, all edges are splines on different workplanes. thickness = 0.1 edge_points = [ [[3.54, 3.54], [1.77, 0.0], [3.54, -3.54]], [[-3.54, -3.54], [0.0, -1.77], [3.54, -3.54]], [[-3.54, -3.54], [0.0, -1.77], [3.54, -3.54]], [[-3.54, -3.54], [-1.77, 0.0], [-3.54, 3.54]], [[3.54, 3.54], [0.0, 1.77], [-3.54, 3.54]], [[3.54, 3.54], [0.0, 1.77], [-3.54, 3.54]], ] plane_list = ["XZ", "XY", "YZ", "XZ", "YZ", "XY"] offset_list = [-3.54, 3.54, 3.54, 3.54, -3.54, -3.54] edge_wire = ( Workplane(plane_list[0]) .workplane(offset=-offset_list[0]) .spline(edge_points[0]) ) for i in range(len(edge_points) - 1): edge_wire = edge_wire.add( Workplane(plane_list[i + 1]) .workplane(offset=-offset_list[i + 1]) .spline(edge_points[i + 1]) ) surface_points = [[0, 0, 0]] plate_4 = Workplane("XY").interpPlate(edge_wire, surface_points, thickness) self.assertTrue(plate_4.val().isValid()) self.assertAlmostEqual(plate_4.val().Volume(), 7.760559490, 2) def testTangentArcToPoint(self): # create a simple shape with tangents of straight edges and see if it has the correct area s0 = ( Workplane("XY") .hLine(1) .tangentArcPoint((1, 1), relative=False) .hLineTo(0) .tangentArcPoint((0, 0), relative=False) .close() .extrude(1) ) area0 = s0.faces(">Z").val().Area() self.assertAlmostEqual(area0, (1 + math.pi * 0.5 ** 2), 4) # test relative coords s1 = ( Workplane("XY") .hLine(1) .tangentArcPoint((0, 1), relative=True) .hLineTo(0) .tangentArcPoint((0, -1), relative=True) .close() .extrude(1) ) self.assertTupleAlmostEquals( s1.val().Center().toTuple(), s0.val().Center().toTuple(), 4 ) self.assertAlmostEqual(s1.val().Volume(), s0.val().Volume(), 4) # consecutive tangent arcs s1 = ( Workplane("XY") .vLine(2) .tangentArcPoint((1, 0)) .tangentArcPoint((1, 0)) .tangentArcPoint((1, 0)) .vLine(-2) .close() .extrude(1) ) self.assertAlmostEqual( s1.faces(">Z").val().Area(), 2 * 3 + 0.5 * math.pi * 0.5 ** 2, 4 ) # tangentArc on the end of a spline # spline will be a simple arc of a circle, then finished off with a # tangentArcPoint angles = [idx * 1.5 * math.pi / 10 for idx in range(10)] pts = [(math.sin(a), math.cos(a)) for a in angles] s2 = ( Workplane("XY") .spline(pts) .tangentArcPoint((0, 1), relative=False) .close() .extrude(1) ) # volume should almost be pi, but not accurately because we need to # start with a spline self.assertAlmostEqual(s2.val().Volume(), math.pi, 1) # assert local coords are mapped to global correctly arc0 = Workplane("XZ", origin=(1, 1, 1)).hLine(1).tangentArcPoint((1, 1)).val() self.assertTupleAlmostEquals(arc0.endPoint().toTuple(), (3, 1, 2), 4) # tangentArcPoint with 3-tuple argument w0 = Workplane("XY").lineTo(1, 1).tangentArcPoint((1, 1, 1)).wire() zmax = w0.val().BoundingBox().zmax self.assertAlmostEqual(zmax, 1, 1) def test_findFromEdge(self): part = Workplane("XY", origin=(1, 1, 1)).hLine(1) found_edge = part._findFromEdge(useLocalCoords=False) self.assertTupleAlmostEquals(found_edge.startPoint().toTuple(), (1, 1, 1), 3) self.assertTupleAlmostEquals(found_edge.Center().toTuple(), (1.5, 1, 1), 3) self.assertTupleAlmostEquals(found_edge.endPoint().toTuple(), (2, 1, 1), 3) found_edge = part._findFromEdge(useLocalCoords=True) self.assertTupleAlmostEquals(found_edge.endPoint().toTuple(), (1, 0, 0), 3) # check _findFromEdge can find a spline pts = [(0, 0), (0, 1), (1, 2), (2, 4)] spline0 = Workplane("XZ").spline(pts)._findFromEdge() self.assertTupleAlmostEquals((2, 0, 4), spline0.endPoint().toTuple(), 3) # check method fails if no edge is present part2 = Workplane("XY").box(1, 1, 1) with self.assertRaises(RuntimeError): part2._findFromEdge() with self.assertRaises(RuntimeError): part2._findFromEdge(useLocalCoords=True) def testMakeHelix(self): h = 10 pitch = 1.5 r = 1.2 obj = Wire.makeHelix(pitch, h, r) bb = obj.BoundingBox() self.assertAlmostEqual(bb.zlen, h, 1) def testUnionCompound(self): box1 = Workplane("XY").box(10, 20, 30) box2 = Workplane("YZ").box(10, 20, 30) shape_to_cut = Workplane("XY").box(15, 15, 15).translate((8, 8, 8)) list_of_shapes = [] for o in box1.all(): list_of_shapes.extend(o.vals()) for o in box2.all(): list_of_shapes.extend(o.vals()) obj = Workplane("XY").newObject(list_of_shapes).cut(shape_to_cut) assert obj.val().isValid() def testSection(self): box = Workplane("XY", origin=(1, 2, 3)).box(1, 1, 1) s1 = box.section() s2 = box.section(0.5) self.assertAlmostEqual(s1.faces().val().Area(), 1) self.assertAlmostEqual(s2.faces().val().Area(), 1) line = Workplane("XY").hLine(1) with self.assertRaises(ValueError): line.section() def testGlue(self): box1 = Workplane("XY").rect(1, 1).extrude(2) box2 = Workplane("XY", origin=(0, 1, 0)).rect(1, 1).extrude(1) res = box1.union(box2, glue=True) self.assertEqual(res.faces().size(), 8) obj = obj = ( Workplane("XY").rect(1, 1).extrude(2).moveTo(0, 2).rect(1, 1).extrude(2) ) res = obj.union(box2, glue=True) self.assertEqual(res.faces().size(), 10) def testFuzzyBoolOp(self): eps = 1e-3 box1 = Workplane("XY").box(1, 1, 1) box2 = Workplane("XY", origin=(1 + eps, 0.0)).box(1, 1, 1) box3 = Workplane("XY", origin=(2, 0, 0)).box(1, 1, 1) res = box1.union(box2) res_fuzzy = box1.union(box2, tol=eps) res_fuzzy2 = box1.union(box3).union(box2, tol=eps) self.assertEqual(res.solids().size(), 2) self.assertEqual(res_fuzzy.solids().size(), 1) self.assertEqual(res_fuzzy2.solids().size(), 1) def testLocatedMoved(self): box = Solid.makeBox(1, 1, 1, Vector(-0.5, -0.5, -0.5)) loc = Location(Vector(1, 1, 1)) box1 = box.located(loc) self.assertTupleAlmostEquals(box1.Center().toTuple(), (1, 1, 1), 6) self.assertTupleAlmostEquals(box.Center().toTuple(), (0, 0, 0), 6) box.locate(loc) self.assertTupleAlmostEquals(box.Center().toTuple(), (1, 1, 1), 6) box2 = box.moved(loc) self.assertTupleAlmostEquals(box.Center().toTuple(), (1, 1, 1), 6) self.assertTupleAlmostEquals(box2.Center().toTuple(), (2, 2, 2), 6) box.move(loc) self.assertTupleAlmostEquals(box.Center().toTuple(), (2, 2, 2), 6) def testNullShape(self): from OCP.TopoDS import TopoDS_Shape s = TopoDS_Shape() # make sure raises on non solid with self.assertRaises(ValueError): r = occ_impl.shapes.downcast(s) def testCenterOfBoundBox(self): obj = Workplane().pushPoints([(0, 0), (2, 2)]).box(1, 1, 1) c = obj.workplane(centerOption="CenterOfBoundBox").plane.origin self.assertTupleAlmostEquals(c.toTuple(), (1, 1, 0), 6) def testOffset2D(self): w1 = Workplane().rect(1, 1).offset2D(0.5, "arc") self.assertEqual(w1.edges().size(), 8) w2 = Workplane().rect(1, 1).offset2D(0.5, "tangent") self.assertEqual(w2.edges().size(), 4) w3 = Workplane().rect(1, 1).offset2D(0.5, "intersection") self.assertEqual(w3.edges().size(), 4) w4 = Workplane().pushPoints([(0, 0), (0, 5)]).rect(1, 1).offset2D(-0.5) self.assertEqual(w4.wires().size(), 0) w5 = Workplane().pushPoints([(0, 0), (0, 5)]).rect(1, 1).offset2D(-0.25) self.assertEqual(w5.wires().size(), 2) r = 20 s = 7 t = 1.5 points = [ (0, t / 2), (r / 2 - 1.5 * t, r / 2 - t), (s / 2, r / 2 - t), (s / 2, r / 2), (r / 2, r / 2), (r / 2, s / 2), (r / 2 - t, s / 2), (r / 2 - t, r / 2 - 1.5 * t), (t / 2, 0), ] s = ( Workplane("XY") .polyline(points) .mirrorX() .mirrorY() .offset2D(-0.9) .extrude(1) ) self.assertEqual(s.solids().size(), 4) # test forConstruction # forConstruction=True should place results in objects, not ctx.pendingWires w6 = Workplane().hLine(1).vLine(1).close().offset2D(0.5, forConstruction=True) self.assertEqual(len(w6.ctx.pendingWires), 0) self.assertEqual(w6.size(), 1) self.assertEqual(type(w6.val()), Wire) # make sure the resulting wire has forConstruction set self.assertEqual(w6.val().forConstruction, True) def testConsolidateWires(self): w1 = Workplane().lineTo(0, 1).lineTo(1, 1).consolidateWires() self.assertEqual(w1.size(), 1) w1 = Workplane().consolidateWires() self.assertEqual(w1.size(), 0) def testLocationAt(self): r = 1 e = Wire.makeHelix(r, r, r).Edges()[0] locs_frenet = e.locations([0, 1], frame="frenet") T1 = locs_frenet[0].wrapped.Transformation() T2 = locs_frenet[1].wrapped.Transformation() self.assertAlmostEqual(T1.TranslationPart().X(), r, 6) self.assertAlmostEqual(T2.TranslationPart().X(), r, 6) self.assertAlmostEqual( T1.GetRotation().GetRotationAngle(), -T2.GetRotation().GetRotationAngle(), 6 ) ga = e._geomAdaptor() locs_corrected = e.locations( [ga.FirstParameter(), ga.LastParameter()], mode="parameter", frame="corrected", ) T3 = locs_corrected[0].wrapped.Transformation() T4 = locs_corrected[1].wrapped.Transformation() self.assertAlmostEqual(T3.TranslationPart().X(), r, 6) self.assertAlmostEqual(T4.TranslationPart().X(), r, 6) w = Wire.assembleEdges( [ Edge.makeLine(Vector(), Vector(0, 1)), Edge.makeLine(Vector(0, 1), Vector(1, 1)), ] ) locs_wire = e.locations([0, 1]) T5 = locs_wire[0].wrapped.Transformation() T6 = locs_wire[1].wrapped.Transformation() self.assertAlmostEqual(T5.TranslationPart().X(), r, 0) self.assertAlmostEqual(T6.TranslationPart().X(), r, 1) def testNormal(self): circ = Workplane().circle(1).edges().val() n = circ.normal() self.assertTupleAlmostEquals(n.toTuple(), (0, 0, 1), 6) ell = Workplane().ellipse(1, 2).edges().val() n = ell.normal() self.assertTupleAlmostEquals(n.toTuple(), (0, 0, 1), 6) r = Workplane().rect(1, 2).wires().val() n = r.normal() self.assertTupleAlmostEquals(n.toTuple(), (0, 0, 1), 6) with self.assertRaises(ValueError): edge = Workplane().rect(1, 2).edges().val() n = edge.normal() def testPositionAt(self): # test with an open wire w = Workplane().lineTo(0, 1).lineTo(1, 1).wire().val() p0 = w.positionAt(0.0) p1 = w.positionAt(0.5) p2 = w.positionAt(1.0) self.assertTupleAlmostEquals(p0.toTuple(), (0, 0, 0), 6) self.assertTupleAlmostEquals(p1.toTuple(), (0, 1, 0), 6) self.assertTupleAlmostEquals(p2.toTuple(), (1, 1, 0), 6) p0 = w.positionAt(0.0, mode="param") self.assertTupleAlmostEquals(p0.toTuple(), (0, 0, 0), 6) p0, p1, p2 = w.positions([0.0, 0.25, 0.5]) self.assertTupleAlmostEquals(p0.toTuple(), (0, 0, 0), 6) self.assertTupleAlmostEquals(p1.toTuple(), (0, 0.5, 0), 6) self.assertTupleAlmostEquals(p2.toTuple(), (0, 1, 0), 6) # test with a closed wire w = Workplane().lineTo(0, 1).close().wire().val() p0 = w.positionAt(0.0) p1 = w.positionAt(0.5) p2 = w.positionAt(1.0) self.assertTupleAlmostEquals(p0.toTuple(), p2.toTuple(), 6) self.assertTupleAlmostEquals(p1.toTuple(), (0, 1, 0), 6) def testTangengAt(self): pts = [(0, 0), (-1, 1), (-2, 0), (-1, 0)] path = Workplane("XZ").spline(pts, tangents=((0, 1), (1, 0))).val() self.assertTrue( path.tangentAt(0.0, mode="parameter") == path.tangentAt(0.0, mode="length") ) self.assertFalse( path.tangentAt(0.5, mode="parameter") == path.tangentAt(0.5, mode="length") ) arc = Workplane().radiusArc((2, 0), 1).val() self.assertTupleAlmostEquals( arc.tangentAt(math.pi / 2, "parameter").toTuple(), (1, 0, 0), 6 ) self.assertTupleAlmostEquals( arc.tangentAt(0.5, "length").toTuple(), (1, 0, 0), 6 ) def testEnd(self): with self.assertRaises(ValueError): Workplane().end() self.assertTrue(Workplane().objects == []) self.assertTrue(Workplane().box(1, 1, 1).end().objects == []) self.assertTrue(Workplane().box(1, 1, 1).box(2, 2, 1).end(2).objects == []) def testCutEach(self): # base shape: w = Workplane().box(3, 2, 2) # cutter: c = Workplane().box(2, 2, 2).val() # cut all the corners off w0 = w.vertices().cutEach(lambda loc: c.located(loc)) # we are left with a 1x2x2 box: self.assertAlmostEqual(w0.val().Volume(), 4, 3) # test error on no solid found w1 = Workplane().hLine(1).vLine(1).close() with raises(ValueError): w1.cutEach(lambda loc: c.located(loc)) def testCutBlind(self): # cutBlind is already tested in several of the complicated tests, so this method is short. # test ValueError on no solid found w0 = Workplane().hLine(1).vLine(1).close() with raises(ValueError): w0.cutBlind(1) def testFindFace(self): # if there are no faces to find, should raise ValueError w0 = Workplane() with raises(ValueError): w0.findFace() w1 = Workplane().box(1, 1, 1).faces(">Z") self.assertTrue(isinstance(w1.findFace(), Face)) with raises(ValueError): w1.findFace(searchStack=False) w2 = w1.workplane().circle(0.1).extrude(0.1) self.assertTrue(isinstance(w2.findFace(searchParents=True), Face)) with raises(ValueError): w2.findFace(searchParents=False) def testPopPending(self): # test pending edges w0 = Workplane().hLine(1) self.assertEqual(len(w0.ctx.pendingEdges), 1) edges = w0.ctx.popPendingEdges() self.assertEqual(len(edges), 1) self.assertEqual(edges[0], w0.val()) # pending edges should now be cleared self.assertEqual(len(w0.ctx.pendingEdges), 0) # test pending wires w1 = Workplane().hLine(1).vLine(1).close() wire = w1.val() self.assertEqual(w1.ctx.pendingWires[0], wire) pop_pending_output = w1.ctx.popPendingWires() self.assertEqual(pop_pending_output[0], wire) # pending wires should now be cleared self.assertEqual(len(w1.ctx.pendingWires), 0) # test error when empty pending edges w2 = Workplane() # the following 2 should not raise an exception w2.ctx.popPendingEdges(errorOnEmpty=False) w2.ctx.popPendingWires(errorOnEmpty=False) # empty edges w3 = Workplane().hLine(1).vLine(1).close() with self.assertRaises(ValueError): w3.ctx.popPendingEdges() # empty wires w4 = Workplane().circle(1).extrude(1) with self.assertRaises(ValueError): w4.ctx.popPendingWires() # test via cutBlind w5 = Workplane().circle(1).extrude(1) with self.assertRaises(ValueError): w5.cutBlind(-1) def testCompSolid(self): from OCP.BRepPrimAPI import BRepPrimAPI_MakePrism tool = Solid.makeSphere(1, angleDegrees3=120) shell = tool.Shells()[0] v = Vector(0, 0, 1) builder = BRepPrimAPI_MakePrism(shell.wrapped, v.wrapped) result = Shape.cast(builder.Shape()) self.assertEqual(len(result.CompSolids()), 1) self.assertEqual(len(result.Solids()), 4) def test2Dfillet(self): r = Workplane().rect(1, 2).wires().val() f = Face.makeFromWires(r) verts = r.Vertices() self.assertEqual(len(f.fillet2D(0.5, verts).Vertices()), 6) self.assertEqual(len(r.fillet2D(0.5, verts).Vertices()), 6) self.assertEqual(len(r.fillet2D(0.25, verts).Vertices()), 8) # Test fillet2D with open wire and single vertex w0 = Workplane().hLine(1).vLine(1).wire() w0_verts = w0.vertices(">X and <Y").vals() unfilleted_wire0 = w0.val() filleted_wire0 = unfilleted_wire0.fillet2D(0.5, w0_verts) self.assertEqual(len(filleted_wire0.Vertices()), 4) # the filleted wire is shorter than the original self.assertGreater(unfilleted_wire0.Length() - filleted_wire0.Length(), 0.1) def test2Dchamfer(self): r = Workplane().rect(1, 2).wires().val() f = Face.makeFromWires(r) verts = r.Vertices() self.assertEqual(len(f.chamfer2D(0.5, verts).Vertices()), 6) self.assertEqual(len(r.chamfer2D(0.5, verts).Vertices()), 6) self.assertEqual(len(r.chamfer2D(0.25, verts).Vertices()), 8) r = Workplane().hLine(1).vLine(1).wire().val() vs = r.Vertices() self.assertEqual(len(r.chamfer2D(0.25, [vs[1]]).Vertices()), 4) with raises(ValueError): r.chamfer2D(0.25, [vs[0]]) def testSplineApprox(self): from .naca import naca5305 from math import pi, cos pts = [Vector(e[0], e[1], 0) for e in naca5305] # spline e1 = Edge.makeSplineApprox(pts, 1e-6, maxDeg=6, smoothing=(1, 1, 1)) e2 = Edge.makeSplineApprox(pts, 1e-6, minDeg=2, maxDeg=6) self.assertTrue(e1.isValid()) self.assertTrue(e2.isValid()) self.assertTrue(e1.Length() > e2.Length()) with raises(ValueError): e4 = Edge.makeSplineApprox(pts, 1e-6, maxDeg=3, smoothing=(1, 1, 1.0)) pts_closed = pts + [pts[0]] e3 = Edge.makeSplineApprox(pts_closed) w = Edge.makeSplineApprox(pts).close() self.assertTrue(e3.IsClosed()) self.assertTrue(w.IsClosed()) # Workplane method w1 = Workplane().splineApprox(pts) w2 = Workplane().splineApprox(pts, forConstruction=True) w3 = Workplane().splineApprox(pts, makeWire=True) w4 = Workplane().splineApprox(pts, makeWire=True, forConstruction=True) self.assertEqual(w1.edges().size(), 1) self.assertEqual(len(w1.ctx.pendingEdges), 1) self.assertEqual(w2.edges().size(), 1) self.assertEqual(len(w2.ctx.pendingEdges), 0) self.assertEqual(w3.wires().size(), 1) self.assertEqual(len(w3.ctx.pendingWires), 1) self.assertEqual(w4.wires().size(), 1) self.assertEqual(len(w4.ctx.pendingWires), 0) # spline surface N = 40 T = 20 A = 5 pts = [ [ Vector(i, j, A * cos(2 * pi * i / T) * cos(2 * pi * j / T)) for i in range(N + 1) ] for j in range(N + 1) ] f1 = Face.makeSplineApprox(pts, smoothing=(1, 1, 1), maxDeg=6) f2 = Face.makeSplineApprox(pts) self.assertTrue(f1.isValid()) self.assertTrue(f2.isValid()) with raises(ValueError): f3 = Face.makeSplineApprox(pts, smoothing=(1, 1, 1), maxDeg=3) def testParametricSurface(self): from math import pi, cos r1 = Workplane().parametricSurface( lambda u, v: (u, v, cos(pi * u) * cos(pi * v)), start=-1, stop=1 ) self.assertTrue(r1.faces().val().isValid()) r2 = Workplane().box(1, 1, 3).split(r1) self.assertTrue(r2.solids().val().isValid()) self.assertEqual(r2.solids().size(), 2) def testEdgeWireClose(self): # test with edge e0 = Edge.makeThreePointArc(Vector(0, 0, 0), Vector(1, 1, 0), Vector(0, 2, 0)) self.assertFalse(e0.IsClosed()) w0 = e0.close() self.assertTrue(w0.IsClosed()) # test with already closed edge e1 = Edge.makeCircle(1) self.assertTrue(e1.IsClosed()) e2 = e1.close() self.assertTrue(e2.IsClosed()) self.assertEqual(type(e1), type(e2)) # test with already closed WIRE w1 = Wire.makeCircle(1, Vector(), Vector(0, 0, 1)) self.assertTrue(w1.IsClosed()) w2 = w1.close() self.assertTrue(w1 is w2) def testSplitShape(self): """ Testing the Shape.split method. """ # split an edge with a vertex e0 = Edge.makeCircle(1, (0, 0, 0), (0, 0, 1)) v0 = Vertex.makeVertex(0, 1, 0) list_of_edges = e0.split(v0).Edges() self.assertEqual(len(list_of_edges), 2) self.assertTrue(Vector(0, 1, 0) in [e.endPoint() for e in list_of_edges]) # split a circle with multiple vertices angles = [2 * math.pi * idx / 10 for idx in range(10)] vecs = [Vector(math.sin(a), math.cos(a), 0) for a in angles] vertices = [Vertex.makeVertex(*v.toTuple()) for v in vecs] edges = e0.split(*vertices).Edges() self.assertEqual(len(edges), len(vertices) + 1) endpoints = [e.endPoint() for e in edges] self.assertTrue(all([v in endpoints for v in vecs])) def testBrepImportExport(self): # import/export to file s = Workplane().box(1, 1, 1).val() s.exportBrep("test.brep") si = Shape.importBrep("test.brep") self.assertTrue(si.isValid()) self.assertAlmostEqual(si.Volume(), 1) # import/export to BytesIO from io import BytesIO bio = BytesIO() s.exportBrep(bio) bio.seek(0) si = Shape.importBrep("test.brep") self.assertTrue(si.isValid()) self.assertAlmostEqual(si.Volume(), 1) def testFaceToPln(self): origin = (1, 2, 3) normal = (1, 1, 1) f0 = Face.makePlane(length=None, width=None, basePnt=origin, dir=normal) p0 = f0.toPln() self.assertTrue(Vector(p0.Location()) == Vector(origin)) self.assertTrue(Vector(p0.Axis().Direction()) == Vector(normal).normalized()) origin1 = (0, 0, -3) normal1 = (-1, 1, -1) f1 = Face.makePlane(length=0.1, width=100, basePnt=origin1, dir=normal1) p1 = f1.toPln() self.assertTrue(Vector(p1.Location()) == Vector(origin1)) self.assertTrue(Vector(p1.Axis().Direction()) == Vector(normal1).normalized()) f2 = Workplane().box(1, 1, 10, centered=False).faces(">Z").val() p2 = f2.toPln() self.assertTrue(p2.Contains(f2.Center().toPnt(), 0.1)) self.assertTrue(Vector(p2.Axis().Direction()) == f2.normalAt())
33.749893
164
0.528441
import math, os.path, time, tempfile from random import choice from random import random from random import randrange from itertools import product from pytest import approx, raises from cadquery import * from cadquery import exporters from cadquery import occ_impl from tests import ( BaseTest, writeStringToFile, makeUnitCube, readFileAsString, makeUnitSquareWire, makeCube, ) testdataDir = os.path.join(os.path.dirname(__file__), "testdata") OUTDIR = tempfile.gettempdir() SUMMARY_FILE = os.path.join(OUTDIR, "testSummary.html") SUMMARY_TEMPLATE = """<html> <head> <style type="text/css"> .testResult{ background: #eeeeee; margin: 50px; border: 1px solid black; } </style> </head> <body> <!--TEST_CONTENT--> </body> </html>""" TEST_RESULT_TEMPLATE = """ <div class="testResult"><h3>%(name)s</h3> %(svg)s </div> <!--TEST_CONTENT--> """ writeStringToFile(SUMMARY_TEMPLATE, SUMMARY_FILE) class TestCadQuery(BaseTest): def tearDown(self): svgFile = os.path.join(OUTDIR, self._testMethodName + ".svg") if os.path.exists(svgFile): existingSummary = readFileAsString(SUMMARY_FILE) svgText = readFileAsString(svgFile) svgText = svgText.replace( '<?xml version="1.0" encoding="UTF-8" standalone="no"?>', "" ) existingSummary = existingSummary.replace( "<!--TEST_CONTENT-->", TEST_RESULT_TEMPLATE % (dict(svg=svgText, name=self._testMethodName)), ) writeStringToFile(existingSummary, SUMMARY_FILE) def saveModel(self, shape): shape.exportSvg(os.path.join(OUTDIR, self._testMethodName + ".svg")) shape.val().exportStep(os.path.join(OUTDIR, self._testMethodName + ".step")) def testToOCC(self): r = Workplane("XY").rect(5, 5).extrude(5) r = r.toOCC() import OCP self.assertEqual(type(r), OCP.TopoDS.TopoDS_Compound) def testToSVG(self): r = Workplane("XY").rect(5, 5).extrude(5) r_str = r.toSvg() self.assertTrue(r_str.index('path d="M') > 0) self.assertTrue( r_str.index('line x1="30" y1="-30" x2="58" y2="-15" stroke-width="3"') > 0 ) def testCubePlugin(self): # make the plugin method def makeCubes(self, length): # self refers to the CQ or Workplane object # create the solid s = Solid.makeBox(length, length, length, Vector(0, 0, 0)) # use CQ utility method to iterate over the stack an position the cubes return self.eachpoint(lambda loc: s.located(loc), True) # link the plugin in Workplane.makeCubes = makeCubes # call it result = ( Workplane("XY") .box(6.0, 8.0, 0.5) .faces(">Z") .rect(4.0, 4.0, forConstruction=True) .vertices() ) result = result.makeCubes(1.0) result = result.combineSolids() self.saveModel(result) self.assertEqual(1, result.solids().size()) def testCylinderPlugin(self): def cylinders(self, radius, height): # construct a cylinder at (0,0,0) c = Solid.makeCylinder(radius, height, Vector(0, 0, 0)) # combine all the cylinders into a single compound r = self.eachpoint(lambda loc: c.located(loc), True).combineSolids() return r Workplane.cyl = cylinders # now test. here we want weird workplane to see if the objects are transformed right s = ( Workplane(Plane(Vector((0, 0, 0)), Vector((1, -1, 0)), Vector((1, 1, 0)))) .rect(2.0, 3.0, forConstruction=True) .vertices() .cyl(0.25, 0.5) ) self.assertEqual(4, s.solids().size()) self.saveModel(s) def testPolygonPlugin(self): def rPoly(self, nSides, diameter): def _makePolygon(loc): # pnt is a vector in local coordinates angle = 2.0 * math.pi / nSides pnts = [] for i in range(nSides + 1): pnts.append( Vector( (diameter / 2.0 * math.cos(angle * i)), (diameter / 2.0 * math.sin(angle * i)), 0, ) ) return Wire.makePolygon(pnts).located(loc) return self.eachpoint(_makePolygon, True) Workplane.rPoly = rPoly s = ( Workplane("XY") .box(4.0, 4.0, 0.25) .faces(">Z") .workplane() .rect(2.0, 2.0, forConstruction=True) .vertices() .rPoly(5, 0.5) .cutThruAll() ) # 6 base sides, 4 pentagons, 5 sides each = 26 self.assertEqual(26, s.faces().size()) self.saveModel(s) def testFluentMethodInheritance(self): class ExtendedWorkplane(Workplane): def nonExistentInWorkplane(self): pass # Call an inherited fluent method: wp = ExtendedWorkplane("XY").moveTo(1, 2) # Verify that the inherited method returned an instance of the derived # class: self.assertEqual(type(wp), ExtendedWorkplane) # The following is redundant, but can make the use case clearer. # This must not raise an AttributeError: wp.nonExistentInWorkplane() def testPointList(self): c = CQ(makeUnitCube()) s = c.faces(">Z").workplane().pushPoints([(-0.3, 0.3), (0.3, 0.3), (0, 0)]) self.assertEqual(3, s.size()) # TODO: is the ability to iterate over points with circle really worth it? # maybe we should just require using all() and a loop for this. the semantics and # possible combinations got too hard ( ie, .circle().circle() ) was really odd body = s.circle(0.05).cutThruAll() self.saveModel(body) self.assertEqual(9, body.faces().size()) # Test the case when using eachpoint with only a blank workplane def callback_fn(loc): self.assertEqual( Vector(0, 0, 0), Vector(loc.wrapped.Transformation().TranslationPart()) ) r = Workplane("XY") r.objects = [] r.eachpoint(callback_fn) def testWorkplaneFromFace(self): # make a workplane on the top face s = CQ(makeUnitCube()).faces(">Z").workplane() r = s.circle(0.125).cutBlind(-2.0) self.saveModel(r) # the result should have 7 faces self.assertEqual(7, r.faces().size()) self.assertEqual(type(r.val()), Compound) self.assertEqual(type(r.first().val()), Compound) def testFrontReference(self): # make a workplane on the top face s = CQ(makeUnitCube()).faces("front").workplane() r = s.circle(0.125).cutBlind(-2.0) self.saveModel(r) # the result should have 7 faces self.assertEqual(7, r.faces().size()) self.assertEqual(type(r.val()), Compound) self.assertEqual(type(r.first().val()), Compound) def testRotate(self): box = Workplane("XY").box(1, 1, 5) box.rotate((0, 0, 0), (1, 0, 0), 90) startPoint = box.faces("<Y").edges("<X").first().val().startPoint().toTuple() endPoint = box.faces("<Y").edges("<X").first().val().endPoint().toTuple() self.assertEqual(-0.5, startPoint[0]) self.assertEqual(-0.5, startPoint[1]) self.assertEqual(-2.5, startPoint[2]) self.assertEqual(-0.5, endPoint[0]) self.assertEqual(-0.5, endPoint[1]) self.assertEqual(2.5, endPoint[2]) def testPlaneRotateZNormal(self): for _ in range(100): angle = (random() - 0.5) * 720 xdir = Vector(random(), random(), random()).normalized() rdir = Vector(random(), random(), random()).normalized() zdir = xdir.cross(rdir).normalized() origin = (random(), random(), random()) plane = Plane(origin=origin, xDir=xdir, normal=zdir) rotated = plane.rotated((0, 0, angle)) assert rotated.zDir.toTuple() == approx(zdir.toTuple()) assert rotated.origin.toTuple() == approx(origin) def testPlaneRotateConcat(self): xdir = (1, 0, 0) normal = (0, 0, 1) k = 2.0 ** 0.5 / 2.0 origin = (2, -1, 1) plane = Plane(origin=origin, xDir=xdir, normal=normal) plane = plane.rotated((0, 0, 45)) assert plane.xDir.toTuple() == approx((k, k, 0)) assert plane.yDir.toTuple() == approx((-k, k, 0)) assert plane.zDir.toTuple() == approx((0, 0, 1)) plane = plane.rotated((0, 45, 0)) assert plane.xDir.toTuple() == approx((0.5, 0.5, -k)) assert plane.yDir.toTuple() == approx((-k, k, 0)) assert plane.zDir.toTuple() == approx((0.5, 0.5, k)) assert plane.origin.toTuple() == origin def testPlaneRotateConcatRandom(self): origin = (2, -1, 1) plane = Plane(origin=origin, xDir=(1, 0, 0), normal=(0, 0, 1)) for _ in range(100): before = { 0: plane.xDir.toTuple(), 1: plane.yDir.toTuple(), 2: plane.zDir.toTuple(), } angle = (random() - 0.5) * 720 direction = randrange(3) rotation = [0, 0, 0] rotation[direction] = angle plane = plane.rotated(rotation) after = { 0: plane.xDir.toTuple(), 1: plane.yDir.toTuple(), 2: plane.zDir.toTuple(), } assert before[direction] == approx(after[direction]) assert plane.origin.toTuple() == origin def testPlaneNoXDir(self): for z_dir in [(0, 0, 1), (1, 0, 0), (-1, 0, 0), Vector(-1, 0, 0)]: result = Plane(origin=(1, 2, 3), xDir=None, normal=z_dir) assert result.zDir == Vector(z_dir) assert result.xDir.Length == approx(1) assert result.origin == Vector(1, 2, 3) # unspecified xDir should be the same as xDir=None result2 = Plane(origin=(1, 2, 3), normal=z_dir) assert result2 == result def testPlaneToPln(self): plane = Plane(origin=(1, 2, 3), xDir=(-1, 0, 0), normal=(0, 1, 0)) gppln = plane.toPln() assert Vector(gppln.XAxis().Direction()) == Vector(-1, 0, 0) assert Vector(gppln.YAxis().Direction()) == plane.yDir assert Vector(gppln.Axis().Direction()) == plane.zDir def testRect(self): x = 10 y = 11 s = Workplane().rect(x, y) # a rectangle has 4 sides self.assertEqual(s.edges().size(), 4) # assert that the lower left corner is in the correct spot for all # possible values of centered for centered_x, xval in zip([True, False], [-x / 2, 0]): for centered_y, yval in zip([True, False], [-y / 2, 0]): s = ( Workplane() .rect(x, y, centered=(centered_x, centered_y)) .vertices("<X and <Y") ) self.assertEqual(s.size(), 1) self.assertTupleAlmostEquals(s.val().toTuple(), (xval, yval, 0), 3) # check that centered=True is the same as centered=(True, True) for option0 in [True, False]: v0 = ( Workplane() .rect(x, y, centered=option0) .vertices(">X and >Y") .val() .toTuple() ) v1 = ( Workplane() .rect(x, y, centered=(option0, option0)) .vertices(">X and >Y") .val() .toTuple() ) self.assertTupleAlmostEquals(v0, v1, 3) # test negative lengths r0 = Workplane().rect(-x, -y, centered=False) self.assertTupleAlmostEquals( (0, 0, 0), r0.vertices(">X and >Y").val().toTuple(), 3 ) self.assertTupleAlmostEquals( (-x, -y, 0), r0.vertices("<X and <Y").val().toTuple(), 3 ) # test move plus negative length r1 = Workplane().move(x, y).rect(-x, -y, centered=False) self.assertTupleAlmostEquals( (x, y, 0), r1.vertices(">X and >Y").val().toTuple(), 3 ) self.assertTupleAlmostEquals( (0, 0, 0), r1.vertices("<X and <Y").val().toTuple(), 3 ) # negative length should have no effect with centered=True v2 = Workplane().rect(x, y).vertices(">X and >Y").val().toTuple() v3 = Workplane().rect(-x, -y).vertices(">X and >Y").val().toTuple() self.assertTupleAlmostEquals(v2, v3, 3) def testLoft(self): s = Workplane("XY").circle(4.0).workplane(5.0).rect(2.0, 2.0).loft() self.saveModel(s) # the result should have 7 faces self.assertEqual(1, s.solids().size()) # the resulting loft had a split on the side, not sure why really, i expected only 3 faces self.assertEqual(7, s.faces().size()) def testLoftRaisesValueError(self): s0 = Workplane().hLine(1) # no wires with raises(ValueError): s0.loft() s1 = Workplane("XY").circle(5) # one wire with self.assertRaises(ValueError) as cm: s1.loft() err = cm.exception self.assertEqual(str(err), "More than one wire is required") def testLoftCombine(self): s = ( Workplane("front") .box(4.0, 4.0, 0.25) .faces(">Z") .circle(1.5) .workplane(offset=3.0) .rect(0.75, 0.5) .loft(combine=True) ) self.saveModel(s) # self.assertEqual(1,s.solids().size() ) # self.assertEqual(8,s.faces().size() ) def testRevolveCylinder(self): # The dimensions of the model. These can be modified rather than changing the # shape's code directly. rectangle_width = 10.0 rectangle_length = 10.0 angle_degrees = 360.0 # Test revolve without any options for making a cylinder result = ( Workplane("XY").rect(rectangle_width, rectangle_length, False).revolve() ) self.assertEqual(3, result.faces().size()) self.assertEqual(2, result.vertices().size()) self.assertEqual(3, result.edges().size()) # Test revolve when only setting the angle to revolve through result = ( Workplane("XY") .rect(rectangle_width, rectangle_length, False) .revolve(angle_degrees) ) self.assertEqual(3, result.faces().size()) self.assertEqual(2, result.vertices().size()) self.assertEqual(3, result.edges().size()) result = ( Workplane("XY") .rect(rectangle_width, rectangle_length, False) .revolve(270.0) ) self.assertEqual(5, result.faces().size()) self.assertEqual(6, result.vertices().size()) self.assertEqual(9, result.edges().size()) # Test when passing revolve the angle and the axis of revolution's start point result = ( Workplane("XY") .rect(rectangle_width, rectangle_length) .revolve(angle_degrees, (-5, -5)) ) self.assertEqual(3, result.faces().size()) self.assertEqual(2, result.vertices().size()) self.assertEqual(3, result.edges().size()) result = ( Workplane("XY") .rect(rectangle_width, rectangle_length) .revolve(270.0, (-5, -5)) ) self.assertEqual(5, result.faces().size()) self.assertEqual(6, result.vertices().size()) self.assertEqual(9, result.edges().size()) # Test when passing revolve the angle and both the start and ends of the axis of revolution result = ( Workplane("XY") .rect(rectangle_width, rectangle_length) .revolve(angle_degrees, (-5, -5), (-5, 5)) ) self.assertEqual(3, result.faces().size()) self.assertEqual(2, result.vertices().size()) self.assertEqual(3, result.edges().size()) result = ( Workplane("XY") .rect(rectangle_width, rectangle_length) .revolve(270.0, (-5, -5), (-5, 5)) ) self.assertEqual(5, result.faces().size()) self.assertEqual(6, result.vertices().size()) self.assertEqual(9, result.edges().size()) # Testing all of the above without combine result = ( Workplane("XY") .rect(rectangle_width, rectangle_length) .revolve(angle_degrees, (-5, -5), (-5, 5), False) ) self.assertEqual(3, result.faces().size()) self.assertEqual(2, result.vertices().size()) self.assertEqual(3, result.edges().size()) result = ( Workplane("XY") .rect(rectangle_width, rectangle_length) .revolve(270.0, (-5, -5), (-5, 5), False) ) self.assertEqual(5, result.faces().size()) self.assertEqual(6, result.vertices().size()) self.assertEqual(9, result.edges().size()) def testRevolveDonut(self): # The dimensions of the model. These can be modified rather than changing the # shape's code directly. rectangle_width = 10.0 rectangle_length = 10.0 angle_degrees = 360.0 result = ( Workplane("XY") .rect(rectangle_width, rectangle_length, True) .revolve(angle_degrees, (20, 0), (20, 10)) ) self.assertEqual(4, result.faces().size()) self.assertEqual(4, result.vertices().size()) self.assertEqual(6, result.edges().size()) def testRevolveCone(self): result = Workplane("XY").lineTo(0, 10).lineTo(5, 0).close().revolve() self.assertEqual(2, result.faces().size()) self.assertEqual(2, result.vertices().size()) self.assertEqual(2, result.edges().size()) def testRevolveErrors(self): result = Workplane("XY").lineTo(0, 10).lineTo(5, 0) with raises(ValueError): result.revolve() def testSpline(self): pts = [(0, 0), (0, 1), (1, 2), (2, 4)] # Spline path - just a smoke test path = Workplane("XZ").spline(pts).val() # Closed spline path_closed = Workplane("XZ").spline(pts, periodic=True).val() self.assertTrue(path_closed.IsClosed()) # attempt to build a valid face w = Wire.assembleEdges([path_closed,]) f = Face.makeFromWires(w) self.assertTrue(f.isValid()) # attempt to build an invalid face w = Wire.assembleEdges([path,]) f = Face.makeFromWires(w) self.assertFalse(f.isValid()) # Spline with explicit tangents path_const = Workplane("XZ").spline(pts, tangents=((0, 1), (1, 0))).val() self.assertFalse(path.tangentAt(0) == path_const.tangentAt(0)) self.assertFalse(path.tangentAt(1) == path_const.tangentAt(1)) # test include current path1 = Workplane("XZ").spline(pts[1:], includeCurrent=True).val() self.assertAlmostEqual(path.Length(), path1.Length()) # test tangents and offset plane pts = [(0, 0), (-1, 1), (-2, 0), (-1, 0)] tangents = [(0, 1), (1, 0)] path2 = Workplane("XY", (0, 0, 10)).spline(pts, tangents=tangents) self.assertAlmostEqual(path2.val().tangentAt(0).z, 0) def testSplineWithMultipleTangents(self): points = [(0, 0), (1, 1), (2, 0), (1, -1)] tangents = [(0, 1), (1, 0), (0, -1), (-1, 0)] parameters = range(len(points)) spline = ( Workplane("XY") .spline(points, tangents=tangents, parameters=parameters) .consolidateWires() ) test_point = spline.edges().val().positionAt(2.5, mode="parameter") expected_test_point = Vector(1.875, -0.625, 0.0) self.assertAlmostEqual((test_point - expected_test_point).Length, 0) def testSplineWithSpecifiedAndUnspecifiedTangents(self): points = [(0, 0), (1, 1), (2, 0), (1, -1)] tangents = [(0, 1), None, (0, -1), (-1, 0)] parameters = range(len(points)) spline = ( Workplane("XY") .spline(points, tangents=tangents, parameters=parameters) .consolidateWires() ) test_point = spline.edges().val().positionAt(1.5, mode="parameter") expected_test_point = Vector(1.6875, 0.875, 0.0) self.assertAlmostEqual((test_point - expected_test_point).Length, 0) def testSplineSpecifyingParameters(self): points = [(0, 0), (1, 1), (2, 0), (1, -1)] tangents = [(0, 1), (1, 0), (0, -1), (-1, 0)] spline1 = ( Workplane("XY") .spline(points, tangents=tangents, parameters=[0, 1, 2, 3]) .consolidateWires() ) # Multiply all parameter values by 10: spline2 = ( Workplane("XY") .spline(points, tangents=tangents, parameters=[0, 10, 20, 30]) .consolidateWires() ) # Test point equivalence for parameter, and parameter multiplied by 10: test_point1 = spline1.edges().val().positionAt(1.5, mode="parameter") test_point2 = spline2.edges().val().positionAt(15, mode="parameter") expected_test_point = Vector(1.625, 0.625, 0.0) self.assertAlmostEqual((test_point1 - test_point2).Length, 0) self.assertAlmostEqual((test_point1 - expected_test_point).Length, 0) # test periodic with parameters spline3 = Workplane().spline( points, periodic=True, parameters=[x for x in range(len(points) + 1)] ) self.assertTrue(spline3.val().IsClosed()) def testSplineWithScaleTrue(self): points = [(0, 0), (1, 1), (2, 0), (1, -1)] tangents = [(0, 1), (1, 0), (0, -1), (-1, 0)] parameters = range(len(points)) spline = ( Workplane("XY") .spline(points, tangents=tangents, parameters=parameters, scale=True) .consolidateWires() ) test_point = spline.edges().val().positionAt(0.5, mode="parameter") expected_test_point = Vector(0.375, 0.875, 0.0) self.assertAlmostEqual((test_point - expected_test_point).Length, 0) def testSplineWithScaleFalse(self): points = [(0, 0), (1, 1), (2, 0), (1, -1)] tangents = [(0, 1), (1, 0), (0, -1), (-1, 0)] parameters = range(len(points)) spline = ( Workplane("XY") .spline(points, tangents=tangents, parameters=parameters, scale=False) .consolidateWires() ) test_point = spline.edges().val().positionAt(0.5, mode="parameter") expected_test_point = Vector(0.375, 0.625, 0.0) self.assertAlmostEqual((test_point - expected_test_point).Length, 0) def testSplineTangentMagnitudeBelowToleranceThrows(self): import OCP points = [(0, 0), (1, 1), (2, 0), (1, -1)] # Use a tangent vector with magnitude 0.5: tangents = [(0, 0.5), (1, 0), (0, -1), (-1, 0)] parameters = range(len(points)) # Set tolerance above the 0.5 length of the tangent vector. This # should throw an exception: with raises( (OCP.Standard.Standard_ConstructionError, OCP.Standard.Standard_Failure) ): spline = ( Workplane("XY") .spline(points, tangents=tangents, tol=1) .consolidateWires() ) def testSplineInputValidation(self): points = [(0, 0), (1, 1), (2, 0)] tangents = [(0, 0.5), (1, 0), (0, -1), (-1, 0)] with raises(ValueError): spline = Workplane().spline(points, tangents=tangents) with raises(ValueError): Workplane().spline( points, periodic=False, parameters=[x for x in range(len(points) + 1)], ) with raises(ValueError): Workplane().spline( points, periodic=True, parameters=[x for x in range(len(points))], ) def testRotatedEllipse(self): def rotatePoint(x, y, alpha): # rotation matrix a = alpha * DEG2RAD r = ((math.cos(a), math.sin(a)), (-math.sin(a), math.cos(a))) return ((x * r[0][0] + y * r[1][0]), (x * r[0][1] + y * r[1][1])) def ellipsePoints(r1, r2, a): return (r1 * math.cos(a * DEG2RAD), r2 * math.sin(a * DEG2RAD)) DEG2RAD = math.pi / 180.0 p0 = (10, 20) a1, a2 = 30, -60 r1, r2 = 20, 10 ra = 25 sx_rot, sy_rot = rotatePoint(*ellipsePoints(r1, r2, a1), ra) ex_rot, ey_rot = rotatePoint(*ellipsePoints(r1, r2, a2), ra) # startAtCurrent=False, sense = 1 ellipseArc1 = ( Workplane("XY") .moveTo(*p0) .ellipseArc( r1, r2, startAtCurrent=False, angle1=a1, angle2=a2, rotation_angle=ra ) ) start = ellipseArc1.vertices().objects[0] end = ellipseArc1.vertices().objects[1] self.assertTupleAlmostEquals( (start.X, start.Y), (p0[0] + sx_rot, p0[1] + sy_rot), 3 ) self.assertTupleAlmostEquals( (end.X, end.Y), (p0[0] + ex_rot, p0[1] + ey_rot), 3 ) # startAtCurrent=True, sense = 1 ellipseArc2 = ( Workplane("XY") .moveTo(*p0) .ellipseArc( r1, r2, startAtCurrent=True, angle1=a1, angle2=a2, rotation_angle=ra ) ) start = ellipseArc2.vertices().objects[0] end = ellipseArc2.vertices().objects[1] self.assertTupleAlmostEquals( (start.X, start.Y), (p0[0] + sx_rot - sx_rot, p0[1] + sy_rot - sy_rot), 3 ) self.assertTupleAlmostEquals( (end.X, end.Y), (p0[0] + ex_rot - sx_rot, p0[1] + ey_rot - sy_rot), 3 ) # startAtCurrent=False, sense = -1 ellipseArc3 = ( Workplane("XY") .moveTo(*p0) .ellipseArc( r1, r2, startAtCurrent=False, angle1=a1, angle2=a2, rotation_angle=ra, sense=-1, ) ) start = ellipseArc3.vertices().objects[0] end = ellipseArc3.vertices().objects[1] # swap start and end points for comparison due to different sense self.assertTupleAlmostEquals( (start.X, start.Y), (p0[0] + ex_rot, p0[1] + ey_rot), 3 ) self.assertTupleAlmostEquals( (end.X, end.Y), (p0[0] + sx_rot, p0[1] + sy_rot), 3 ) # startAtCurrent=True, sense = -1 ellipseArc4 = ( Workplane("XY") .moveTo(*p0) .ellipseArc( r1, r2, startAtCurrent=True, angle1=a1, angle2=a2, rotation_angle=ra, sense=-1, makeWire=True, ) ) self.assertEqual(len(ellipseArc4.ctx.pendingWires), 1) start = ellipseArc4.vertices().objects[0] end = ellipseArc4.vertices().objects[1] # swap start and end points for comparison due to different sense self.assertTupleAlmostEquals( (start.X, start.Y), (p0[0] + ex_rot - ex_rot, p0[1] + ey_rot - ey_rot), 3 ) self.assertTupleAlmostEquals( (end.X, end.Y), (p0[0] + sx_rot - ex_rot, p0[1] + sy_rot - ey_rot), 3 ) def testEllipseArcsClockwise(self): ellipseArc = ( Workplane("XY") .moveTo(10, 15) .ellipseArc(5, 4, -10, 190, 45, sense=-1, startAtCurrent=False) ) sp = ellipseArc.val().startPoint() ep = ellipseArc.val().endPoint() self.assertTupleAlmostEquals( (sp.x, sp.y), (7.009330014275797, 11.027027582524015), 3 ) self.assertTupleAlmostEquals( (ep.x, ep.y), (13.972972417475985, 17.990669985724203), 3 ) ellipseArc = ( ellipseArc.ellipseArc(5, 4, -10, 190, 315, sense=-1) .ellipseArc(5, 4, -10, 190, 225, sense=-1) .ellipseArc(5, 4, -10, 190, 135, sense=-1) ) ep = ellipseArc.val().endPoint() self.assertTupleAlmostEquals((sp.x, sp.y), (ep.x, ep.y), 3) def testEllipseArcsCounterClockwise(self): ellipseArc = ( Workplane("XY") .moveTo(10, 15) .ellipseArc(5, 4, -10, 190, 45, startAtCurrent=False) ) sp = ellipseArc.val().startPoint() ep = ellipseArc.val().endPoint() self.assertTupleAlmostEquals( (sp.x, sp.y), (13.972972417475985, 17.990669985724203), 3 ) self.assertTupleAlmostEquals( (ep.x, ep.y), (7.009330014275797, 11.027027582524015), 3 ) ellipseArc = ( ellipseArc.ellipseArc(5, 4, -10, 190, 135) .ellipseArc(5, 4, -10, 190, 225) .ellipseArc(5, 4, -10, 190, 315) ) ep = ellipseArc.val().endPoint() self.assertTupleAlmostEquals((sp.x, sp.y), (ep.x, ep.y), 3) def testEllipseCenterAndMoveTo(self): # Whether we start from a center() call or a moveTo call, it should be the same ellipse Arc p0 = (10, 20) a1, a2 = 30, -60 r1, r2 = 20, 10 ra = 25 ellipseArc1 = ( Workplane("XY") .moveTo(*p0) .ellipseArc( r1, r2, startAtCurrent=False, angle1=a1, angle2=a2, rotation_angle=ra ) ) sp1 = ellipseArc1.val().startPoint() ep1 = ellipseArc1.val().endPoint() ellipseArc2 = ( Workplane("XY") .moveTo(*p0) .ellipseArc( r1, r2, startAtCurrent=False, angle1=a1, angle2=a2, rotation_angle=ra ) ) sp2 = ellipseArc2.val().startPoint() ep2 = ellipseArc2.val().endPoint() self.assertTupleAlmostEquals(sp1.toTuple(), sp2.toTuple(), 3) self.assertTupleAlmostEquals(ep1.toTuple(), ep2.toTuple(), 3) def testMakeEllipse(self): el = Wire.makeEllipse( 1, 2, Vector(0, 0, 0), Vector(0, 0, 1), Vector(1, 0, 0), 0, 90, 45, True, ) self.assertTrue(el.IsClosed()) self.assertTrue(el.isValid()) def testSweep(self): pts = [(0, 0), (0, 1), (1, 2), (2, 4)] # Spline path path = Workplane("XZ").spline(pts) # Test defaults result = Workplane("XY").circle(1.0).sweep(path) self.assertEqual(3, result.faces().size()) self.assertEqual(3, result.edges().size()) # Test with makeSolid False result = Workplane("XY").circle(1.0).sweep(path, makeSolid=False) self.assertEqual(1, result.faces().size()) self.assertEqual(3, result.edges().size()) # Test with isFrenet True result = Workplane("XY").circle(1.0).sweep(path, isFrenet=True) self.assertEqual(3, result.faces().size()) self.assertEqual(3, result.edges().size()) # Test with makeSolid False and isFrenet True result = Workplane("XY").circle(1.0).sweep(path, makeSolid=False, isFrenet=True) self.assertEqual(1, result.faces().size()) self.assertEqual(3, result.edges().size()) # Test rectangle with defaults result = Workplane("XY").rect(1.0, 1.0).sweep(path) self.assertEqual(6, result.faces().size()) self.assertEqual(12, result.edges().size()) # Test fixed normal result = Workplane().circle(0.5).sweep(path, normal=Vector(0, 0, 1)) self.assertTupleAlmostEquals( result.faces(">Z").val().normalAt().toTuple(), (0, 0, 1), 6 ) # Polyline path path = Workplane("XZ").polyline(pts) # Test defaults result = Workplane("XY").circle(0.1).sweep(path, transition="transformed") self.assertEqual(5, result.faces().size()) self.assertEqual(7, result.edges().size()) # Polyline path and one inner profiles path = Workplane("XZ").polyline(pts) # Test defaults result = ( Workplane("XY") .circle(0.2) .circle(0.1) .sweep(path, transition="transformed") ) self.assertEqual(8, result.faces().size()) self.assertEqual(14, result.edges().size()) # Polyline path and different transition settings for t in ("transformed", "right", "round"): path = Workplane("XZ").polyline(pts) result = ( Workplane("XY") .circle(0.2) .rect(0.2, 0.1) .rect(0.1, 0.2) .sweep(path, transition=t) ) self.assertTrue(result.solids().val().isValid()) # Polyline path and multiple inner profiles path = Workplane("XZ").polyline(pts) # Test defaults result = ( Workplane("XY") .circle(0.2) .rect(0.2, 0.1) .rect(0.1, 0.2) .circle(0.1) .sweep(path) ) self.assertTrue(result.solids().val().isValid()) # Arc path path = Workplane("XZ").threePointArc((1.0, 1.5), (0.0, 1.0)) # Test defaults result = Workplane("XY").circle(0.1).sweep(path) self.assertEqual(3, result.faces().size()) self.assertEqual(3, result.edges().size()) # Test aux spine pts1 = [(0, 0), (20, 100)] pts2 = [(0, 20, 0), (20, 0, 100)] path = Workplane("YZ").spline(pts1, tangents=[(0, 1, 0), (0, 1, 0)]) aux_path = Workplane("XY").spline(pts2, tangents=[(0, 0, 1), (0, 0, 1)]) result = Workplane("XY").rect(10, 20).sweep(path, auxSpine=aux_path) bottom = result.faces("<Z") top = result.faces(">Z") v1 = bottom.wires().val().tangentAt(0.0) v2 = top.wires().val().tangentAt(0.0) self.assertAlmostEqual(v1.getAngle(v2), math.pi / 4, 6) # test for ValueError if pending wires is empty w0 = Workplane().hLine(1).vLine(1) with raises(ValueError): w0.sweep(path) # Test aux spine invalid input handling with raises(ValueError): result = ( Workplane("XY") .rect(10, 20) .sweep(path, auxSpine=Workplane().box(1, 1, 1)) ) def testMultisectionSweep(self): # X axis line length 20.0 path = Workplane("XZ").moveTo(-10, 0).lineTo(10, 0) # Sweep a circle from diameter 2.0 to diameter 1.0 to diameter 2.0 along X axis length 10.0 + 10.0 defaultSweep = ( Workplane("YZ") .workplane(offset=-10.0) .circle(2.0) .workplane(offset=10.0) .circle(1.0) .workplane(offset=10.0) .circle(2.0) .sweep(path, multisection=True) ) # We can sweep through different shapes recttocircleSweep = ( Workplane("YZ") .workplane(offset=-10.0) .rect(2.0, 2.0) .workplane(offset=8.0) .circle(1.0) .workplane(offset=4.0) .circle(1.0) .workplane(offset=8.0) .rect(2.0, 2.0) .sweep(path, multisection=True) ) circletorectSweep = ( Workplane("YZ") .workplane(offset=-10.0) .circle(1.0) .workplane(offset=7.0) .rect(2.0, 2.0) .workplane(offset=6.0) .rect(2.0, 2.0) .workplane(offset=7.0) .circle(1.0) .sweep(path, multisection=True) ) # Placement of the Shape is important otherwise could produce unexpected shape specialSweep = ( Workplane("YZ") .circle(1.0) .workplane(offset=10.0) .rect(2.0, 2.0) .sweep(path, multisection=True) ) # Switch to an arc for the path : line l=5.0 then half circle r=4.0 then line l=5.0 path = ( Workplane("XZ") .moveTo(-5, 4) .lineTo(0, 4) .threePointArc((4, 0), (0, -4)) .lineTo(-5, -4) ) # Placement of different shapes should follow the path # cylinder r=1.5 along first line # then sweep along arc from r=1.5 to r=1.0 # then cylinder r=1.0 along last line arcSweep = ( Workplane("YZ") .workplane(offset=-5) .moveTo(0, 4) .circle(1.5) .workplane(offset=5, centerOption="CenterOfMass") .circle(1.5) .moveTo(0, -8) .circle(1.0) .workplane(offset=-5, centerOption="CenterOfMass") .circle(1.0) .sweep(path, multisection=True) ) # Test multisection with normal pts = [(0, 0), (20, 100)] path = Workplane("YZ").spline(pts, tangents=[(0, 1, 0), (0, 1, 0)]) normalSweep = ( Workplane() .rect(10, 10) .workplane(offset=100) .rect(10, 20) .sweep(path, multisection=True, normal=(0, 1, 1)) ) self.assertTupleAlmostEquals( normalSweep.faces("<Z").val().normalAt().toTuple(), Vector(0, -1, -1).normalized().toTuple(), 6, ) self.assertTupleAlmostEquals( normalSweep.faces(">Z").val().normalAt().toTuple(), Vector(0, 1, 1).normalized().toTuple(), 6, ) # Test and saveModel self.assertEqual(1, defaultSweep.solids().size()) self.assertEqual(1, circletorectSweep.solids().size()) self.assertEqual(1, recttocircleSweep.solids().size()) self.assertEqual(1, specialSweep.solids().size()) self.assertEqual(1, arcSweep.solids().size()) self.saveModel(defaultSweep) def testTwistExtrude(self): profile = Workplane("XY").rect(10, 10) r = profile.twistExtrude(10, 45, False) self.assertEqual(6, r.faces().size()) def testTwistExtrudeCombine(self): profile = Workplane("XY").rect(10, 10) r = profile.twistExtrude(10, 45) self.assertEqual(6, r.faces().size()) def testRectArray(self): x_num = 3 y_num = 3 x_spacing = 8.0 y_spacing = 8.0 s = ( Workplane("XY") .box(40, 40, 5, centered=(True, True, True)) .faces(">Z") .workplane() .rarray(x_spacing, y_spacing, x_num, y_num, True) .circle(2.0) .extrude(2.0) ) self.saveModel(s) # 6 faces for the box, 2 faces for each cylinder self.assertEqual(6 + x_num * y_num * 2, s.faces().size()) with raises(ValueError): Workplane().rarray(0, 0, x_num, y_num, True) # check lower and upper corner points are correct for all combinations of centering for x_opt, x_min, x_max in zip( [True, False], [-x_spacing, 0.0], [x_spacing, x_spacing * 2] ): for y_opt, y_min, y_max in zip( [True, False], [-y_spacing, 0.0], [y_spacing, y_spacing * 2] ): s = Workplane().rarray( x_spacing, y_spacing, x_num, y_num, center=(x_opt, y_opt) ) lower = Vector(x_min, y_min, 0) upper = Vector(x_max, y_max, 0) self.assertTrue(lower in s.objects) self.assertTrue(upper in s.objects) # check centered=True is equivalent to centered=(True, True) for val in [True, False]: s0 = Workplane().rarray(x_spacing, y_spacing, x_num, y_num, center=val) s1 = Workplane().rarray( x_spacing, y_spacing, x_num, y_num, center=(val, val) ) # check all the points in s0 are present in s1 self.assertTrue(all(pnt in s1.objects for pnt in s0.objects)) self.assertEqual(s0.size(), s1.size()) def testPolarArray(self): radius = 10 # Test for proper number of elements s = Workplane("XY").polarArray(radius, 0, 180, 1) self.assertEqual(1, s.size()) s = Workplane("XY").polarArray(radius, 0, 180, 6) self.assertEqual(6, s.size()) to_x = lambda l: l.wrapped.Transformation().TranslationPart().X() to_y = lambda l: l.wrapped.Transformation().TranslationPart().Y() to_angle = ( lambda l: l.wrapped.Transformation().GetRotation().GetRotationAngle() * 180.0 / math.pi ) # Test for proper placement when fill == True s = Workplane("XY").polarArray(radius, 0, 180, 3) self.assertAlmostEqual(0, to_y(s.objects[1])) self.assertAlmostEqual(radius, to_x(s.objects[1])) # Test for proper placement when angle to fill is multiple of 360 deg s = Workplane("XY").polarArray(radius, 0, 360, 4) self.assertAlmostEqual(0, to_y(s.objects[1])) self.assertAlmostEqual(radius, to_x(s.objects[1])) # Test for proper placement when fill == False s = Workplane("XY").polarArray(radius, 0, 90, 3, fill=False) self.assertAlmostEqual(0, to_y(s.objects[1])) self.assertAlmostEqual(radius, to_x(s.objects[1])) # Test for proper operation of startAngle s = Workplane("XY").polarArray(radius, 90, 180, 3) self.assertAlmostEqual(radius, to_x(s.objects[0])) self.assertAlmostEqual(0, to_y(s.objects[0])) # Test for local rotation s = Workplane().polarArray(radius, 0, 180, 3) self.assertAlmostEqual(0, to_angle(s.objects[0])) self.assertAlmostEqual(90, to_angle(s.objects[1])) s = Workplane().polarArray(radius, 0, 180, 3, rotate=False) self.assertAlmostEqual(0, to_angle(s.objects[0])) self.assertAlmostEqual(0, to_angle(s.objects[1])) def testNestedCircle(self): s = ( Workplane("XY") .box(40, 40, 5) .pushPoints([(10, 0), (0, 10)]) .circle(4) .circle(2) .extrude(4) ) self.saveModel(s) self.assertEqual(14, s.faces().size()) def testConcentricEllipses(self): concentricEllipses = ( Workplane("XY").center(10, 20).ellipse(100, 10).center(0, 0).ellipse(50, 5) ) v = concentricEllipses.vertices().objects[0] self.assertTupleAlmostEquals((v.X, v.Y), (10 + 50, 20), 3) def testLegoBrick(self): # test making a simple lego brick # which of the below # inputs lbumps = 8 wbumps = 2 # lego brick constants P = 8.0 # nominal pitch c = 0.1 # clearance on each brick side H = 1.2 * P # nominal height of a brick bumpDiam = 4.8 # the standard bump diameter # the nominal thickness of the walls, normally 1.5 t = (P - (2 * c) - bumpDiam) / 2.0 postDiam = P - t # works out to 6.5 total_length = lbumps * P - 2.0 * c total_width = wbumps * P - 2.0 * c # build the brick s = Workplane("XY").box(total_length, total_width, H) # make the base s = s.faces("<Z").shell(-1.0 * t) # shell inwards not outwards s = ( s.faces(">Z") .workplane() .rarray(P, P, lbumps, wbumps, True) .circle(bumpDiam / 2.0) .extrude(1.8) ) # make the bumps on the top # add posts on the bottom. posts are different diameter depending on geometry # solid studs for 1 bump, tubes for multiple, none for 1x1 # this is cheating a little-- how to select the inner face from the shell? tmp = s.faces("<Z").workplane(invert=True) if lbumps > 1 and wbumps > 1: tmp = ( tmp.rarray(P, P, lbumps - 1, wbumps - 1, center=True) .circle(postDiam / 2.0) .circle(bumpDiam / 2.0) .extrude(H - t) ) elif lbumps > 1: tmp = tmp.rarray(P, P, lbumps - 1, 1, center=True).circle(t).extrude(H - t) elif wbumps > 1: tmp = tmp.rarray(P, P, 1, wbumps - 1, center=True).circle(t).extrude(H - t) self.saveModel(s) def testAngledHoles(self): s = ( Workplane("front") .box(4.0, 4.0, 0.25) .faces(">Z") .workplane() .transformed(offset=Vector(0, -1.5, 1.0), rotate=Vector(60, 0, 0)) .rect(1.5, 1.5, forConstruction=True) .vertices() .hole(0.25) ) self.saveModel(s) self.assertEqual(10, s.faces().size()) def testTranslateSolid(self): c = CQ(makeUnitCube()) self.assertAlmostEqual(0.0, c.faces("<Z").vertices().item(0).val().Z, 3) # TODO: it might be nice to provide a version of translate that modifies the existing geometry too d = c.translate(Vector(0, 0, 1.5)) self.assertAlmostEqual(1.5, d.faces("<Z").vertices().item(0).val().Z, 3) def testTranslateWire(self): c = CQ(makeUnitSquareWire()) self.assertAlmostEqual(0.0, c.edges().vertices().item(0).val().Z, 3) d = c.translate(Vector(0, 0, 1.5)) self.assertAlmostEqual(1.5, d.edges().vertices().item(0).val().Z, 3) def testSolidReferencesCombine(self): c = CQ(makeUnitCube()) # the cube is the context solid self.assertEqual(6, c.faces().size()) # cube has six faces r = ( c.faces(">Z").workplane().circle(0.125).extrude(0.5, True) ) # make a boss, not updating the original self.assertEqual(8, r.faces().size()) # just the boss faces self.assertEqual(6, c.faces().size()) # original is not modified def testSolidReferencesCombineTrue(self): s = Workplane(Plane.XY()) r = s.rect(2.0, 2.0).extrude(0.5) # the result of course has 6 faces self.assertEqual(6, r.faces().size()) # the original workplane does not, because it did not have a solid initially self.assertEqual(0, s.faces().size()) t = r.faces(">Z").workplane().rect(0.25, 0.25).extrude(0.5, True) # of course the result has 11 faces self.assertEqual(11, t.faces().size()) # r (being the parent) remains unmodified self.assertEqual(6, r.faces().size()) self.saveModel(r) def testSolidReferenceCombineFalse(self): s = Workplane(Plane.XY()) r = s.rect(2.0, 2.0).extrude(0.5) # the result of course has 6 faces self.assertEqual(6, r.faces().size()) # the original workplane does not, because it did not have a solid initially self.assertEqual(0, s.faces().size()) t = r.faces(">Z").workplane().rect(0.25, 0.25).extrude(0.5, False) # result has 6 faces, because it was not combined with the original self.assertEqual(6, t.faces().size()) self.assertEqual(6, r.faces().size()) # original is unmodified as well # subsequent operations use that context solid afterwards def testSimpleWorkplane(self): s = Workplane(Plane.XY()) r = ( s.rect(2.0, 2.0) .extrude(0.5) .faces(">Z") .workplane() .circle(0.25) .cutBlind(-1.0) ) self.saveModel(r) self.assertEqual(7, r.faces().size()) def testMultiFaceWorkplane(self): s = Workplane("XY").box(1, 1, 1).faces(">Z").rect(1, 0.5).cutBlind(-0.2) w = s.faces(">Z").workplane() o = w.val() # origin of the workplane self.assertAlmostEqual(o.x, 0.0, 3) self.assertAlmostEqual(o.y, 0.0, 3) self.assertAlmostEqual(o.z, 0.5, 3) def testTriangularPrism(self): s = Workplane("XY").lineTo(1, 0).lineTo(1, 1).close().extrude(0.2) self.saveModel(s) def testMultiWireWorkplane(self): s = Workplane(Plane.XY()) r = s.rect(2.0, 2.0).circle(0.25).extrude(0.5) self.saveModel(r) self.assertEqual(7, r.faces().size()) def testConstructionWire(self): s = Workplane(Plane.YZ()) r = ( s.rect(2.0, 2.0) .rect(1.3, 1.3, forConstruction=True) .vertices() .circle(0.125) .extrude(0.5) ) self.saveModel(r) # 10 faces-- 6 plus 4 holes, the vertices of the second rect. self.assertEqual(10, r.faces().size()) def testTwoWorkplanes(self): # base block s = Workplane(Plane.XY()) # TODO: this syntax is nice, but the iteration might not be worth # the complexity. # the simpler and slightly longer version would be: # r = s.rect(2.0,2.0).rect(1.3,1.3,forConstruction=True).vertices() # for c in r.all(): # c.circle(0.125).extrude(0.5,True) r = ( s.rect(2.0, 2.0) .rect(1.3, 1.3, forConstruction=True) .vertices() .circle(0.125) .extrude(0.5) ) # side hole, blind deep 1.9 t = r.faces(">Y").workplane().circle(0.125).cutBlind(-1.9) self.saveModel(t) self.assertEqual(12, t.faces().size()) def testCut(self): s = Workplane(Plane.XY()) currentS = s.rect(2.0, 2.0).extrude(0.5) toCut = s.rect(1.0, 1.0).extrude(0.5) resS = currentS.cut(toCut.val()) self.assertEqual(10, resS.faces().size()) with self.assertRaises(ValueError): currentS.cut(toCut.faces().val()) # Test syntactic sugar [__sub__ method] sugar = currentS - toCut.val() self.assertEqual(resS.faces().size(), sugar.faces().size()) # test ValueError on no solid found s0 = Workplane().hLine(1).vLine(1).close() with raises(ValueError): s0.cut(toCut.val()) def testIntersect(self): s = Workplane(Plane.XY()) currentS = s.rect(2.0, 2.0).extrude(0.5) toIntersect = s.rect(1.0, 1.0).extrude(1) resS = currentS.intersect(toIntersect.val()) self.assertEqual(6, resS.faces().size()) self.assertAlmostEqual(resS.val().Volume(), 0.5) resS = currentS.intersect(toIntersect) self.assertEqual(6, resS.faces().size()) self.assertAlmostEqual(resS.val().Volume(), 0.5) b1 = Workplane("XY").box(1, 1, 1) b2 = Workplane("XY", origin=(0, 0, 0.5)).box(1, 1, 1) resS = b1.intersect(b2) self.assertAlmostEqual(resS.val().Volume(), 0.5) with self.assertRaises(ValueError): b1.intersect(b2.faces().val()) # Test syntactic sugar [__mul__ method] sugar = b1 & b2 self.assertEqual(resS.val().Volume(), sugar.val().Volume()) # raise ValueError when no solid found with raises(ValueError): Workplane().intersect(toIntersect) def testBoundingBox(self): result0 = ( Workplane("XY") .moveTo(10, 0) .lineTo(5, 0) .threePointArc((3.9393, 0.4393), (3.5, 1.5)) .threePointArc((3.0607, 2.5607), (2, 3)) .lineTo(1.5, 3) .threePointArc((0.4393, 3.4393), (0, 4.5)) .lineTo(0, 13.5) .threePointArc((0.4393, 14.5607), (1.5, 15)) .lineTo(28, 15) .lineTo(28, 13.5) .lineTo(24, 13.5) .lineTo(24, 11.5) .lineTo(27, 11.5) .lineTo(27, 10) .lineTo(22, 10) .lineTo(22, 13.2) .lineTo(14.5, 13.2) .lineTo(14.5, 10) .lineTo(12.5, 10) .lineTo(12.5, 13.2) .lineTo(5.5, 13.2) .lineTo(5.5, 2) .threePointArc((5.793, 1.293), (6.5, 1)) .lineTo(10, 1) .close() ) result = result0.extrude(100) bb_center = result.val().BoundingBox().center self.saveModel(result) self.assertAlmostEqual(14.0, bb_center.x, 3) self.assertAlmostEqual(7.5, bb_center.y, 3) self.assertAlmostEqual(50.0, bb_center.z, 3) # The following will raise with the default tolerance of TOL 1e-2 bb = result.val().BoundingBox(tolerance=1e-3) self.assertAlmostEqual(0.0, bb.xmin, 2) self.assertAlmostEqual(28, bb.xmax, 2) self.assertAlmostEqual(0.0, bb.ymin, 2) self.assertAlmostEqual(15.0, bb.ymax, 2) self.assertAlmostEqual(0.0, bb.zmin, 2) self.assertAlmostEqual(100.0, bb.zmax, 2) def testCutThroughAll(self): # base block s = Workplane(Plane.XY()) r = ( s.rect(2.0, 2.0) .rect(1.3, 1.3, forConstruction=True) .vertices() .circle(0.125) .extrude(0.5) ) # thru all without explicit face selection t = r.circle(0.5).cutThruAll() self.assertEqual(11, t.faces().size()) # side hole, thru all t = ( t.faces(">Y") .workplane(centerOption="CenterOfMass") .circle(0.125) .cutThruAll() ) self.saveModel(t) self.assertEqual(13, t.faces().size()) # no planar faces sphere_r = 10.0 r = ( Workplane() .sphere(sphere_r) .workplane() .circle(sphere_r / 2.0) .cutThruAll() .workplane() .transformed(rotate=(90, 0, 0)) .circle(sphere_r / 2.0) .cutThruAll() .workplane() .transformed(rotate=(0, 90, 0)) .circle(sphere_r / 2.0) .cutThruAll() ) self.assertTrue(r.val().isValid()) self.assertEqual(r.faces().size(), 7) # test errors box0 = Workplane().box(1, 1, 1).faces(">Z").workplane().hLine(1) with raises(ValueError): box0.cutThruAll() no_box = Workplane().hLine(1).vLine(1).close() with raises(ValueError): no_box.cutThruAll() def testCutToFaceOffsetNOTIMPLEMENTEDYET(self): # base block s = Workplane(Plane.XY()) r = ( s.rect(2.0, 2.0) .rect(1.3, 1.3, forConstruction=True) .vertices() .circle(0.125) .extrude(0.5) ) # side hole, up to 0.1 from the last face try: t = ( r.faces(">Y") .workplane() .circle(0.125) .cutToOffsetFromFace(r.faces().mminDist(Dir.Y), 0.1) ) # should end up being a blind hole self.assertEqual(10, t.faces().size()) t.first().val().exportStep("c:/temp/testCutToFace.STEP") except: pass # Not Implemented Yet def testWorkplaneOnExistingSolid(self): c = ( CQ(makeUnitCube()) .faces(">Z") .workplane() .circle(0.25) .circle(0.125) .extrude(0.25) ) self.saveModel(c) self.assertEqual(10, c.faces().size()) def testWorkplaneCenterMove(self): # this workplane is centered at x=0.5,y=0.5, the center of the upper face s = ( Workplane("XY").box(1, 1, 1).faces(">Z").workplane().center(-0.5, -0.5) ) # move the center to the corner t = s.circle(0.25).extrude(0.2) # make a boss self.assertEqual(9, t.faces().size()) self.saveModel(t) def testBasicLines(self): global OUTDIR s = Workplane(Plane.XY()) # TODO: extrude() should imply wire() if not done already # most users dont understand what a wire is, they are just drawing r = s.lineTo(1.0, 0).lineTo(0, 1.0).close().wire().extrude(0.25) r.val().exportStep(os.path.join(OUTDIR, "testBasicLinesStep1.STEP")) # no faces on the original workplane self.assertEqual(0, s.faces().size()) # 5 faces on newly created object self.assertEqual(5, r.faces().size()) # now add a circle through a side face r1 = ( r.faces("+XY") .workplane(centerOption="CenterOfMass") .circle(0.08) .cutThruAll() ) self.assertEqual(6, r1.faces().size()) r1.val().exportStep(os.path.join(OUTDIR, "testBasicLinesXY.STEP")) # now add a circle through a top r2 = ( r1.faces("+Z") .workplane(centerOption="CenterOfMass") .circle(0.08) .cutThruAll() ) self.assertEqual(9, r2.faces().size()) r2.val().exportStep(os.path.join(OUTDIR, "testBasicLinesZ.STEP")) self.saveModel(r2) def test2DDrawing(self): s = Workplane(Plane.XY()) r = ( s.lineTo(1.0, 0.0) .lineTo(1.0, 1.0) .threePointArc((1.0, 1.5), (0.0, 1.0)) .lineTo(0.0, 0.0) .moveTo(1.0, 0.0) .lineTo(2.0, 0.0) .lineTo(2.0, 2.0) .threePointArc((2.0, 2.5), (0.0, 2.0)) .lineTo(-2.0, 2.0) .lineTo(-2.0, 0.0) .close() ) self.assertEqual(1, r.wires().size()) # Test the *LineTo functions s = Workplane(Plane.XY()) r = s.hLineTo(1.0).vLineTo(1.0).hLineTo(0.0).close() self.assertEqual(1, r.wire().size()) self.assertEqual(4, r.edges().size()) # Test the *Line functions s = Workplane(Plane.XY()) r = s.hLine(1.0).vLine(1.0).hLine(-1.0).close() self.assertEqual(1, r.wire().size()) self.assertEqual(4, r.edges().size()) # Test the move function s = Workplane(Plane.XY()) r = s.move(1.0, 1.0).hLine(1.0).vLine(1.0).hLine(-1.0).close() self.assertEqual(1, r.wire().size()) self.assertEqual(4, r.edges().size()) self.assertEqual( (1.0, 1.0), ( r.vertices(selectors.NearestToPointSelector((0.0, 0.0, 0.0))) .first() .val() .X, r.vertices(selectors.NearestToPointSelector((0.0, 0.0, 0.0))) .first() .val() .Y, ), ) # Test the sagittaArc and radiusArc functions a1 = Workplane(Plane.YZ()).threePointArc((5, 1), (10, 0)) a2 = Workplane(Plane.YZ()).sagittaArc((10, 0), -1) a3 = Workplane(Plane.YZ()).threePointArc((6, 2), (12, 0)) a4 = Workplane(Plane.YZ()).radiusArc((12, 0), -10) assert a1.edges().first().val().geomType() == "CIRCLE" assert a2.edges().first().val().geomType() == "CIRCLE" assert a3.edges().first().val().geomType() == "CIRCLE" assert a4.edges().first().val().geomType() == "CIRCLE" assert a1.edges().first().val().Length() == a2.edges().first().val().Length() assert a3.edges().first().val().Length() == a4.edges().first().val().Length() def testPolarLines(self): # Test the PolarLine* functions s = Workplane(Plane.XY()) r = ( s.polarLine(10, 45) .polarLineTo(10, -45) .polarLine(10, -180) .polarLine(-10, -90) .close() ) # a single wire, 5 edges self.assertEqual(1, r.wires().size()) self.assertEqual(5, r.wires().edges().size()) def testLargestDimension(self): r = Workplane("XY").box(1, 1, 1) dim = r.largestDimension() self.assertAlmostEqual(1.76, dim, 1) r = Workplane("XY").rect(1, 1).extrude(1) dim = r.largestDimension() self.assertAlmostEqual(1.76, dim, 1) r = Workplane("XY") with raises(ValueError): r.largestDimension() def testOccBottle(self): L = 20.0 w = 6.0 t = 3.0 s = Workplane(Plane.XY()) # draw half the profile of the bottle p = ( s.center(-L / 2.0, 0) .vLine(w / 2.0) .threePointArc((L / 2.0, w / 2.0 + t), (L, w / 2.0)) .vLine(-w / 2.0) .mirrorX() .extrude(30.0, True) ) # make the neck p.faces(">Z").workplane().circle(3.0).extrude( 2.0, True ) # .edges().fillet(0.05) # make a shell p.faces(">Z").shell(0.3) self.saveModel(p) def testSplineShape(self): s = Workplane(Plane.XY()) sPnts = [ (2.75, 1.5), (2.5, 1.75), (2.0, 1.5), (1.5, 1.0), (1.0, 1.25), (0.5, 1.0), (0, 1.0), ] r = s.lineTo(3.0, 0).lineTo(3.0, 1.0).spline(sPnts).close() r = r.extrude(0.5) self.saveModel(r) def testSimpleMirror(self): s = ( Workplane("XY") .lineTo(2, 2) .threePointArc((3, 1), (2, 0)) .mirrorX() .extrude(0.25) ) self.assertEqual(6, s.faces().size()) self.saveModel(s) def testUnorderedMirror(self): r = 20 s = 7 t = 1.5 points = [ (0, 0), (0, t / 2), (r / 2 - 1.5 * t, r / 2 - t), (s / 2, r / 2 - t), (s / 2, r / 2), (r / 2, r / 2), (r / 2, s / 2), (r / 2 - t, s / 2), (r / 2 - t, r / 2 - 1.5 * t), (t / 2, 0), ] r = Workplane("XY").polyline(points).mirrorX() self.assertEqual(1, r.wires().size()) self.assertEqual(18, r.edges().size()) # try the same with includeCurrent=True r = Workplane("XY").polyline(points[1:], includeCurrent=True).mirrorX() self.assertEqual(1, r.wires().size()) self.assertEqual(18, r.edges().size()) def testChainedMirror(self): r = 20 s = 7 t = 1.5 points = [ (0, t / 2), (r / 2 - 1.5 * t, r / 2 - t), (s / 2, r / 2 - t), (s / 2, r / 2), (r / 2, r / 2), (r / 2, s / 2), (r / 2 - t, s / 2), (r / 2 - t, r / 2 - 1.5 * t), (t / 2, 0), ] r = Workplane("XY").polyline(points).mirrorX().mirrorY().extrude(1).faces(">Z") self.assertEqual(1, r.wires().size()) self.assertEqual(32, r.edges().size()) # TODO: Re-work testIbeam test below now that chaining works # TODO: Add toLocalCoords and toWorldCoords tests def testIbeam(self): s = Workplane(Plane.XY()) L = 100.0 H = 20.0 W = 20.0 t = 1.0 # TODO: for some reason doing 1/4 of the profile and mirroring twice ( .mirrorX().mirrorY() ) # did not work, due to a bug in freecad-- it was losing edges when creating a composite wire. # i just side-stepped it for now pts = [ (0, 0), (0, H / 2.0), (W / 2.0, H / 2.0), (W / 2.0, (H / 2.0 - t)), (t / 2.0, (H / 2.0 - t)), (t / 2.0, (t - H / 2.0)), (W / 2.0, (t - H / 2.0)), (W / 2.0, H / -2.0), (0, H / -2.0), ] r = s.polyline(pts).mirrorY() # these other forms also work res = r.extrude(L) self.saveModel(res) def testCone(self): s = Solid.makeCone(0, 1.0, 2.0) t = CQ(s) self.saveModel(t) self.assertEqual(2, t.faces().size()) def testFillet(self): c = ( CQ(makeUnitCube()) .faces(">Z") .workplane() .circle(0.25) .extrude(0.25, True) .edges("|Z") .fillet(0.2) ) self.saveModel(c) self.assertEqual(12, c.faces().size()) # should raise an error if no solid c1 = Workplane().hLine(1).vLine(1).close() with raises(ValueError): c1.fillet(0.1) def testChamfer(self): cube = CQ(makeUnitCube()).faces(">Z").chamfer(0.1) self.saveModel(cube) self.assertEqual(10, cube.faces().size()) # should raise an error if no solid c1 = Workplane().hLine(1).vLine(1).close() with raises(ValueError): c1.chamfer(0.1) def testChamferAsymmetrical(self): cube = CQ(makeUnitCube()).faces(">Z").chamfer(0.1, 0.2) self.saveModel(cube) self.assertEqual(10, cube.faces().size()) # test if edge lengths are different edge = cube.edges(">Z").vals()[0] self.assertAlmostEqual(0.6, edge.Length(), 3) edge = cube.edges("|Z").vals()[0] self.assertAlmostEqual(0.9, edge.Length(), 3) def testChamferCylinder(self): cylinder = Workplane("XY").circle(1).extrude(1).faces(">Z").chamfer(0.1) self.saveModel(cylinder) self.assertEqual(4, cylinder.faces().size()) def testCounterBores(self): c = CQ(makeCube(3.0)) pnts = [(-1.0, -1.0), (0.0, 0.0), (1.0, 1.0)] c = c.faces(">Z").workplane().pushPoints(pnts).cboreHole(0.1, 0.25, 0.25, 0.75) self.assertEqual(18, c.faces().size()) self.saveModel(c) # Tests the case where the depth of the cboreHole is not specified c2 = CQ(makeCube(3.0)) c2 = c2.faces(">Z").workplane().pushPoints(pnts).cboreHole(0.1, 0.25, 0.25) self.assertEqual(15, c2.faces().size()) def testCounterSinks(self): s = Workplane(Plane.XY()) result = ( s.rect(2.0, 4.0) .extrude(0.5) .faces(">Z") .workplane() .rect(1.5, 3.5, forConstruction=True) .vertices() .cskHole(0.125, 0.25, 82, depth=None) ) self.saveModel(result) def testSplitKeepingHalf(self): # drill a hole in the side c = CQ(makeUnitCube()).faces(">Z").workplane().circle(0.25).cutThruAll() self.assertEqual(7, c.faces().size()) # now cut it in half sideways result = c.faces(">Y").workplane(-0.5).split(keepTop=True) self.saveModel(result) self.assertEqual(8, result.faces().size()) def testSplitKeepingBoth(self): # drill a hole in the side c = CQ(makeUnitCube()).faces(">Z").workplane().circle(0.25).cutThruAll() self.assertEqual(7, c.faces().size()) # now cut it in half sideways result = c.faces(">Y").workplane(-0.5).split(keepTop=True, keepBottom=True) # stack will have both halves, original will be unchanged # two solids are on the stack, eac self.assertEqual(2, result.solids().size()) self.assertEqual(8, result.solids().item(0).faces().size()) self.assertEqual(8, result.solids().item(1).faces().size()) def testSplitKeepingBottom(self): # Drill a hole in the side c = CQ(makeUnitCube()).faces(">Z").workplane().circle(0.25).cutThruAll() self.assertEqual(7, c.faces().size()) # Now cut it in half sideways result = c.faces(">Y").workplane(-0.5).split(keepTop=False, keepBottom=True) # stack will have both halves, original will be unchanged # one solid is on the stack self.assertEqual(1, result.solids().size()) self.assertEqual(8, result.solids().item(0).faces().size()) def testSplitError(self): # Test split produces the correct error when called with no solid to split. w = Workplane().hLine(1).vLine(1).close() with raises(ValueError): w.split(keepTop=True) # Split should raise ValueError when called with no side kept with raises(ValueError): w.split(keepTop=False, keepBottom=False) def testBoxDefaults(self): s = Workplane("XY").box(2, 3, 4) self.assertEqual(1, s.solids().size()) self.saveModel(s) def testSimpleShell(self): s1 = Workplane("XY").box(2, 2, 2).faces("+Z").shell(0.05) self.saveModel(s1) self.assertEqual(23, s1.faces().size()) s2 = ( Workplane() .ellipse(4, 2) .extrude(4) .faces(">Z") .shell(+2, kind="intersection") ) self.assertEqual(5, s2.faces().size()) s3 = Workplane().ellipse(4, 2).extrude(4).faces(">Z").shell(+2, kind="arc") self.assertEqual(6, s3.faces().size()) # test error on no solid found s4 = Workplane().hLine(1).vLine(1).close() with raises(ValueError): s4.shell(1) def testClosedShell(self): s1 = Workplane("XY").box(2, 2, 2).shell(-0.1) self.assertEqual(12, s1.faces().size()) self.assertTrue(s1.val().isValid()) s2 = Workplane("XY").box(2, 2, 2).shell(0.1) self.assertEqual(32, s2.faces().size()) self.assertTrue(s2.val().isValid()) pts = [(1.0, 0.0), (0.3, 0.2), (0.0, 0.0), (0.3, -0.1), (1.0, -0.03)] s3 = Workplane().polyline(pts).close().extrude(1).shell(-0.05) self.assertTrue(s3.val().isValid()) s4_shape = Workplane("XY").box(2, 2, 2).val() # test that None and empty list both work and are equivalent s4_shell_1 = s4_shape.shell(faceList=None, thickness=-0.1) s4_shell_2 = s4_shape.shell(faceList=[], thickness=-0.1) # this should be the same as the first shape self.assertEqual(len(s4_shell_1.Faces()), s1.faces().size()) self.assertEqual(len(s4_shell_2.Faces()), s1.faces().size()) def testOpenCornerShell(self): s = Workplane("XY").box(1, 1, 1) s1 = s.faces("+Z") s1.add(s.faces("+Y")).add(s.faces("+X")) self.saveModel(s1.shell(0.2)) # Tests the list option variation of add s1 = s.faces("+Z") s1.add(s.faces("+Y")).add([s.faces("+X")]) # Tests the raw object option variation of add s1 = s.faces("+Z") s1.add(s.faces("+Y")).add(s.faces("+X").val().wrapped) def testTopFaceFillet(self): s = Workplane("XY").box(1, 1, 1).faces("+Z").edges().fillet(0.1) self.assertEqual(s.faces().size(), 10) self.saveModel(s) def testBoxPointList(self): s = ( Workplane("XY") .rect(4.0, 4.0, forConstruction=True) .vertices() .box(0.25, 0.25, 0.25, combine=True) ) # 1 object, 4 solids because the object is a compound self.assertEqual(4, s.solids().size()) self.assertEqual(1, s.size()) self.saveModel(s) s = ( Workplane("XY") .rect(4.0, 4.0, forConstruction=True) .vertices() .box(0.25, 0.25, 0.25, combine=False) ) # 4 objects, 4 solids, because each is a separate solid self.assertEqual(4, s.size()) self.assertEqual(4, s.solids().size()) def testBoxCombine(self): s = ( Workplane("XY") .box(4, 4, 0.5) .faces(">Z") .workplane() .rect(3, 3, forConstruction=True) .vertices() .box(0.25, 0.25, 0.25, combine=True) ) self.saveModel(s) self.assertEqual(1, s.solids().size()) # we should have one big solid # should have 26 faces. 6 for the box, and 4x5 for the smaller cubes self.assertEqual(26, s.faces().size()) def testBoxCentered(self): x, y, z = 10, 11, 12 # check that the bottom corner is where we expect it for all possible combinations of centered b = [True, False] expected_x = [-x / 2, 0] expected_y = [-y / 2, 0] expected_z = [-z / 2, 0] for (xopt, xval), (yopt, yval), (zopt, zval) in product( zip(b, expected_x), zip(b, expected_y), zip(b, expected_z) ): s = ( Workplane() .box(x, y, z, centered=(xopt, yopt, zopt)) .vertices("<X and <Y and <Z") ) self.assertEqual(s.size(), 1) self.assertTupleAlmostEquals(s.val().toTuple(), (xval, yval, zval), 3) # check centered=True produces the same result as centered=(True, True, True) for val in b: s0 = Workplane().box(x, y, z, centered=val).vertices(">X and >Y and >Z") self.assertEqual(s0.size(), 1) s1 = ( Workplane() .box(x, y, z, centered=(val, val, val)) .vertices(">X and >Y and >Z") ) self.assertEqual(s0.size(), 1) self.assertTupleAlmostEquals(s0.val().toTuple(), s1.val().toTuple(), 3) def testSphereDefaults(self): s = Workplane("XY").sphere(10) self.saveModel(s) # Until FreeCAD fixes their sphere operation self.assertEqual(1, s.solids().size()) self.assertEqual(1, s.faces().size()) def testSphereCustom(self): s = Workplane("XY").sphere( 10, angle1=0, angle2=90, angle3=360, centered=(False, False, False) ) self.saveModel(s) self.assertEqual(1, s.solids().size()) self.assertEqual(2, s.faces().size()) # check that the bottom corner is where we expect it for all possible combinations of centered radius = 10 for (xopt, xval), (yopt, yval), (zopt, zval) in product( zip((True, False), (0, radius)), repeat=3 ): s = Workplane().sphere(radius, centered=(xopt, yopt, zopt)) self.assertEqual(s.size(), 1) self.assertTupleAlmostEquals( s.val().Center().toTuple(), (xval, yval, zval), 3 ) # check centered=True produces the same result as centered=(True, True, True) for val in (True, False): s0 = Workplane().sphere(radius, centered=val) self.assertEqual(s0.size(), 1) s1 = Workplane().sphere(radius, centered=(val, val, val)) self.assertEqual(s0.size(), 1) self.assertTupleAlmostEquals( s0.val().Center().toTuple(), s1.val().Center().toTuple(), 3 ) def testSpherePointList(self): s = ( Workplane("XY") .rect(4.0, 4.0, forConstruction=True) .vertices() .sphere(0.25, combine=False) ) # self.saveModel(s) # Until FreeCAD fixes their sphere operation self.assertEqual(4, s.solids().size()) self.assertEqual(4, s.faces().size()) def testSphereCombine(self): s = ( Workplane("XY") .rect(4.0, 4.0, forConstruction=True) .vertices() .sphere(2.25, combine=True) ) # self.saveModel(s) # Until FreeCAD fixes their sphere operation self.assertEqual(1, s.solids().size()) self.assertEqual(4, s.faces().size()) def testCylinderDefaults(self): s = Workplane("XY").cylinder(20, 10) self.assertEqual(1, s.size()) self.assertEqual(1, s.solids().size()) self.assertEqual(3, s.faces().size()) self.assertEqual(2, s.vertices().size()) self.assertTupleAlmostEquals(s.val().Center().toTuple(), (0, 0, 0), 3) def testCylinderCentering(self): radius = 10 height = 40 b = (True, False) expected_x = (0, radius) expected_y = (0, radius) expected_z = (0, height / 2) for (xopt, xval), (yopt, yval), (zopt, zval) in product( zip(b, expected_x), zip(b, expected_y), zip(b, expected_z) ): s = Workplane("XY").cylinder(height, radius, centered=(xopt, yopt, zopt)) self.assertEqual(1, s.size()) self.assertTupleAlmostEquals( s.val().Center().toTuple(), (xval, yval, zval), 3 ) # check centered=True produces the same result as centered=(True, True, True) for val in b: s0 = Workplane("XY").cylinder(height, radius, centered=val) self.assertEqual(s0.size(), 1) s1 = Workplane("XY").cylinder(height, radius, centered=(val, val, val)) self.assertEqual(s1.size(), 1) self.assertTupleAlmostEquals( s0.val().Center().toTuple(), s1.val().Center().toTuple(), 3 ) def testWedgeDefaults(self): s = Workplane("XY").wedge(10, 10, 10, 5, 5, 5, 5) self.saveModel(s) self.assertEqual(1, s.solids().size()) self.assertEqual(5, s.faces().size()) self.assertEqual(5, s.vertices().size()) def testWedgeCentering(self): s = Workplane("XY").wedge( 10, 10, 10, 5, 5, 5, 5, centered=(False, False, False) ) # self.saveModel(s) self.assertEqual(1, s.solids().size()) self.assertEqual(5, s.faces().size()) self.assertEqual(5, s.vertices().size()) # check that the bottom corner is where we expect it for all possible combinations of centered x, y, z = 10, 11, 12 b = [True, False] expected_x = [-x / 2, 0] expected_y = [-y / 2, 0] expected_z = [-z / 2, 0] for (xopt, xval), (yopt, yval), (zopt, zval) in product( zip(b, expected_x), zip(b, expected_y), zip(b, expected_z) ): s = ( Workplane() .wedge(x, y, z, 2, 2, x - 2, z - 2, centered=(xopt, yopt, zopt)) .vertices("<X and <Y and <Z") ) self.assertEqual(s.size(), 1) self.assertTupleAlmostEquals(s.val().toTuple(), (xval, yval, zval), 3) # check centered=True produces the same result as centered=(True, True, True) for val in b: s0 = ( Workplane() .wedge(x, y, z, 2, 2, x - 2, z - 2, centered=val) .vertices(">X and >Z") ) self.assertEqual(s0.size(), 1) s1 = ( Workplane() .wedge(x, y, z, 2, 2, x - 2, z - 2, centered=(val, val, val)) .vertices(">X and >Z") ) self.assertEqual(s0.size(), 1) self.assertTupleAlmostEquals(s0.val().toTuple(), s1.val().toTuple(), 3) def testWedgePointList(self): s = ( Workplane("XY") .rect(4.0, 4.0, forConstruction=True) .vertices() .wedge(10, 10, 10, 5, 5, 5, 5, combine=False) ) # self.saveModel(s) self.assertEqual(4, s.solids().size()) self.assertEqual(20, s.faces().size()) self.assertEqual(20, s.vertices().size()) def testWedgeCombined(self): s = ( Workplane("XY") .rect(4.0, 4.0, forConstruction=True) .vertices() .wedge(10, 10, 10, 5, 5, 5, 5, combine=True) ) # self.saveModel(s) self.assertEqual(1, s.solids().size()) self.assertEqual(12, s.faces().size()) self.assertEqual(16, s.vertices().size()) def testQuickStartXY(self): s = ( Workplane(Plane.XY()) .box(2, 4, 0.5) .faces(">Z") .workplane() .rect(1.5, 3.5, forConstruction=True) .vertices() .cskHole(0.125, 0.25, 82, depth=None) ) self.assertEqual(1, s.solids().size()) self.assertEqual(14, s.faces().size()) self.saveModel(s) def testQuickStartYZ(self): s = ( Workplane(Plane.YZ()) .box(2, 4, 0.5) .faces(">X") .workplane() .rect(1.5, 3.5, forConstruction=True) .vertices() .cskHole(0.125, 0.25, 82, depth=None) ) self.assertEqual(1, s.solids().size()) self.assertEqual(14, s.faces().size()) self.saveModel(s) def testQuickStartXZ(self): s = ( Workplane(Plane.XZ()) .box(2, 4, 0.5) .faces(">Y") .workplane() .rect(1.5, 3.5, forConstruction=True) .vertices() .cskHole(0.125, 0.25, 82, depth=None) ) self.assertEqual(1, s.solids().size()) self.assertEqual(14, s.faces().size()) self.saveModel(s) def testDoubleTwistedLoft(self): s = ( Workplane("XY") .polygon(8, 20.0) .workplane(offset=4.0) .transformed(rotate=Vector(0, 0, 15.0)) .polygon(8, 20) .loft() ) s2 = ( Workplane("XY") .polygon(8, 20.0) .workplane(offset=-4.0) .transformed(rotate=Vector(0, 0, 15.0)) .polygon(8, 20) .loft() ) # self.assertEquals(10,s.faces().size()) # self.assertEquals(1,s.solids().size()) s3 = s.combineSolids(s2) self.saveModel(s3) def testTwistedLoft(self): s = ( Workplane("XY") .polygon(8, 20.0) .workplane(offset=4.0) .transformed(rotate=Vector(0, 0, 15.0)) .polygon(8, 20) .loft() ) self.assertEqual(10, s.faces().size()) self.assertEqual(1, s.solids().size()) self.saveModel(s) def testUnions(self): # duplicates a memory problem of some kind reported when combining lots of objects s = Workplane("XY").rect(0.5, 0.5).extrude(5.0) o = [] beginTime = time.time() for i in range(15): t = Workplane("XY").center(10.0 * i, 0).rect(0.5, 0.5).extrude(5.0) o.append(t) # union stuff for oo in o: s = s.union(oo) print("Total time %0.3f" % (time.time() - beginTime)) # Test unioning a Solid object s = Workplane(Plane.XY()) currentS = s.rect(2.0, 2.0).extrude(0.5) toUnion = s.rect(1.0, 1.0).extrude(1.0) resS = currentS.union(toUnion) self.assertEqual(11, resS.faces().size()) with self.assertRaises(ValueError): resS.union(toUnion.faces().val()) # Test syntactic sugar [__add__ method] sugar1 = currentS | toUnion sugar2 = currentS + toUnion self.assertEqual(resS.faces().size(), sugar1.faces().size()) self.assertEqual(resS.faces().size(), sugar2.faces().size()) def testCombine(self): s = Workplane(Plane.XY()) objects1 = s.rect(2.0, 2.0).extrude(0.5).faces(">Z").rect(1.0, 1.0).extrude(0.5) objects1.combine() self.assertEqual(11, objects1.faces().size()) objects1 = s.rect(2.0, 2.0).extrude(0.5) objects2 = s.rect(1.0, 1.0).extrude(0.5).translate((0, 0, 0.5)) objects2 = objects1.add(objects2).combine(glue=True, tol=None) self.assertEqual(11, objects2.faces().size()) def testCombineSolidsInLoop(self): # duplicates a memory problem of some kind reported when combining lots of objects s = Workplane("XY").rect(0.5, 0.5).extrude(5.0) o = [] beginTime = time.time() for i in range(15): t = Workplane("XY").center(10.0 * i, 0).rect(0.5, 0.5).extrude(5.0) o.append(t) # append the 'good way' for oo in o: s.add(oo) s = s.combineSolids() print("Total time %0.3f" % (time.time() - beginTime)) self.saveModel(s) def testClean(self): # make a cube with a splitter edge on one of the faces # autosimplify should remove the splitter s = ( Workplane("XY") .moveTo(0, 0) .line(5, 0) .line(5, 0) .line(0, 10) .line(-10, 0) .close() .extrude(10) ) self.assertEqual(6, s.faces().size()) # test removal of splitter caused by union operation s = Workplane("XY").box(10, 10, 10).union(Workplane("XY").box(20, 10, 10)) self.assertEqual(6, s.faces().size()) # test removal of splitter caused by extrude+combine operation s = ( Workplane("XY") .box(10, 10, 10) .faces(">Y") .workplane() .rect(5, 10, True) .extrude(20) ) self.assertEqual(10, s.faces().size()) # test removal of splitter caused by double hole operation s = ( Workplane("XY") .box(10, 10, 10) .faces(">Z") .workplane() .hole(3, 5) .faces(">Z") .workplane() .hole(3, 10) ) self.assertEqual(7, s.faces().size()) # test removal of splitter caused by cutThruAll s = ( Workplane("XY") .box(10, 10, 10) .faces(">Y") .workplane() .rect(10, 5) .cutBlind(-5) .faces(">Z") .workplane(centerOption="CenterOfMass") .center(0, 2.5) .rect(5, 5) .cutThruAll() ) self.assertEqual(18, s.faces().size()) # test removal of splitter with box s = Workplane("XY").box(5, 5, 5).box(10, 5, 2) self.assertEqual(14, s.faces().size()) def testNoClean(self): # test disabling autoSimplify s = ( Workplane("XY") .moveTo(0, 0) .line(5, 0) .line(5, 0) .line(0, 10) .line(-10, 0) .close() .extrude(10, clean=False) ) self.assertEqual(7, s.faces().size()) s = ( Workplane("XY") .box(10, 10, 10) .union(Workplane("XY").box(20, 10, 10), clean=False) ) self.assertEqual(14, s.faces().size()) s = ( Workplane("XY") .box(10, 10, 10) .faces(">Y") .workplane() .rect(5, 10, True) .extrude(20, clean=False) ) self.assertEqual(12, s.faces().size()) def testExplicitClean(self): s = ( Workplane("XY") .moveTo(0, 0) .line(5, 0) .line(5, 0) .line(0, 10) .line(-10, 0) .close() .extrude(10, clean=False) .clean() ) self.assertEqual(6, s.faces().size()) def testPlanes(self): # ZX plane s = Workplane(Plane.ZX()) result = ( s.rect(2.0, 4.0) .extrude(0.5) .faces(">Z") .workplane() .rect(1.5, 3.5, forConstruction=True) .vertices() .cskHole(0.125, 0.25, 82, depth=None) ) self.saveModel(result) # YX plane s = Workplane(Plane.YX()) result = ( s.rect(2.0, 4.0) .extrude(0.5) .faces(">Z") .workplane() .rect(1.5, 3.5, forConstruction=True) .vertices() .cskHole(0.125, 0.25, 82, depth=None) ) self.saveModel(result) # YX plane s = Workplane(Plane.YX()) result = ( s.rect(2.0, 4.0) .extrude(0.5) .faces(">Z") .workplane() .rect(1.5, 3.5, forConstruction=True) .vertices() .cskHole(0.125, 0.25, 82, depth=None) ) self.saveModel(result) # ZY plane s = Workplane(Plane.ZY()) result = ( s.rect(2.0, 4.0) .extrude(0.5) .faces(">Z") .workplane() .rect(1.5, 3.5, forConstruction=True) .vertices() .cskHole(0.125, 0.25, 82, depth=None) ) self.saveModel(result) # front plane s = Workplane(Plane.front()) result = ( s.rect(2.0, 4.0) .extrude(0.5) .faces(">Z") .workplane() .rect(1.5, 3.5, forConstruction=True) .vertices() .cskHole(0.125, 0.25, 82, depth=None) ) self.saveModel(result) # back plane s = Workplane(Plane.back()) result = ( s.rect(2.0, 4.0) .extrude(0.5) .faces(">Z") .workplane() .rect(1.5, 3.5, forConstruction=True) .vertices() .cskHole(0.125, 0.25, 82, depth=None) ) self.saveModel(result) # left plane s = Workplane(Plane.left()) result = ( s.rect(2.0, 4.0) .extrude(0.5) .faces(">Z") .workplane() .rect(1.5, 3.5, forConstruction=True) .vertices() .cskHole(0.125, 0.25, 82, depth=None) ) self.saveModel(result) # right plane s = Workplane(Plane.right()) result = ( s.rect(2.0, 4.0) .extrude(0.5) .faces(">Z") .workplane() .rect(1.5, 3.5, forConstruction=True) .vertices() .cskHole(0.125, 0.25, 82, depth=None) ) self.saveModel(result) # top plane s = Workplane(Plane.top()) result = ( s.rect(2.0, 4.0) .extrude(0.5) .faces(">Z") .workplane() .rect(1.5, 3.5, forConstruction=True) .vertices() .cskHole(0.125, 0.25, 82, depth=None) ) self.saveModel(result) # bottom plane s = Workplane(Plane.bottom()) result = ( s.rect(2.0, 4.0) .extrude(0.5) .faces(">Z") .workplane() .rect(1.5, 3.5, forConstruction=True) .vertices() .cskHole(0.125, 0.25, 82, depth=None) ) self.saveModel(result) def testIsInside(self): box1 = Workplane(Plane.XY()).box(10, 10, 10) box2 = Workplane(Plane.XY()).box(5, 5, 5) self.assertFalse(box2.val().BoundingBox().isInside(box1.val().BoundingBox())) self.assertTrue(box1.val().BoundingBox().isInside(box2.val().BoundingBox())) def testCup(self): # for some reason shell doesn't work on this simple shape. how disappointing! td = 50.0 bd = 20.0 h = 10.0 t = 1.0 s1 = Workplane("XY").circle(bd).workplane(offset=h).circle(td).loft() s2 = ( Workplane("XY") .workplane(offset=t) .circle(bd - (2.0 * t)) .workplane(offset=(h - t)) .circle(td - (2.0 * t)) .loft() ) s3 = s1.cut(s2) self.saveModel(s3) def testEnclosure(self): # parameter definitions p_outerWidth = 100.0 # Outer width of box enclosure p_outerLength = 150.0 # Outer length of box enclosure p_outerHeight = 50.0 # Outer height of box enclosure p_thickness = 3.0 # Thickness of the box walls p_sideRadius = 10.0 # Radius for the curves around the sides of the bo # Radius for the curves on the top and bottom edges of the box p_topAndBottomRadius = 2.0 # How far in from the edges the screwposts should be place. p_screwpostInset = 12.0 # Inner Diameter of the screwpost holes, should be roughly screw diameter not including threads p_screwpostID = 4.0 # Outer Diameter of the screwposts.\nDetermines overall thickness of the posts p_screwpostOD = 10.0 p_boreDiameter = 8.0 # Diameter of the counterbore hole, if any p_boreDepth = 1.0 # Depth of the counterbore hole, if # Outer diameter of countersink. Should roughly match the outer diameter of the screw head p_countersinkDiameter = 0.0 # Countersink angle (complete angle between opposite sides, not from center to one side) p_countersinkAngle = 90.0 # Whether to place the lid with the top facing down or not. p_flipLid = True # Height of lip on the underside of the lid.\nSits inside the box body for a snug fit. p_lipHeight = 1.0 # outer shell oshell = ( Workplane("XY") .rect(p_outerWidth, p_outerLength) .extrude(p_outerHeight + p_lipHeight) ) # weird geometry happens if we make the fillets in the wrong order if p_sideRadius > p_topAndBottomRadius: oshell = ( oshell.edges("|Z") .fillet(p_sideRadius) .edges(" .fillet(p_topAndBottomRadius) ) else: oshell = ( oshell.edges(" .fillet(p_topAndBottomRadius) .edges("|Z") .fillet(p_sideRadius) ) # inner shell ishell = ( oshell.faces("<Z") .workplane(p_thickness, True) .rect( (p_outerWidth - 2.0 * p_thickness), (p_outerLength - 2.0 * p_thickness) ) .extrude((p_outerHeight - 2.0 * p_thickness), False) ) # set combine false to produce just the new boss ishell = ishell.edges("|Z").fillet(p_sideRadius - p_thickness) # make the box outer box box = oshell.cut(ishell) # make the screwposts POSTWIDTH = p_outerWidth - 2.0 * p_screwpostInset POSTLENGTH = p_outerLength - 2.0 * p_screwpostInset box = ( box.faces(">Z") .workplane(-p_thickness) .rect(POSTWIDTH, POSTLENGTH, forConstruction=True) .vertices() .circle(p_screwpostOD / 2.0) .circle(p_screwpostID / 2.0) .extrude((-1.0) * (p_outerHeight + p_lipHeight - p_thickness), True) ) # split lid into top and bottom parts (lid, bottom) = ( box.faces(">Z") .workplane(-p_thickness - p_lipHeight) .split(keepTop=True, keepBottom=True) .all() ) # splits into two solids # translate the lid, and subtract the bottom from it to produce the lid inset lowerLid = lid.translate((0, 0, -p_lipHeight)) cutlip = lowerLid.cut(bottom).translate( (p_outerWidth + p_thickness, 0, p_thickness - p_outerHeight + p_lipHeight) ) # compute centers for counterbore/countersink or counterbore topOfLidCenters = ( cutlip.faces(">Z") .workplane() .rect(POSTWIDTH, POSTLENGTH, forConstruction=True) .vertices() ) # add holes of the desired type if p_boreDiameter > 0 and p_boreDepth > 0: topOfLid = topOfLidCenters.cboreHole( p_screwpostID, p_boreDiameter, p_boreDepth, (2.0) * p_thickness ) elif p_countersinkDiameter > 0 and p_countersinkAngle > 0: topOfLid = topOfLidCenters.cskHole( p_screwpostID, p_countersinkDiameter, p_countersinkAngle, (2.0) * p_thickness, ) else: topOfLid = topOfLidCenters.hole(p_screwpostID, (2.0) * p_thickness) # flip lid upside down if desired if p_flipLid: topOfLid.rotateAboutCenter((1, 0, 0), 180) # return the combined result result = topOfLid.union(bottom) self.saveModel(result) def testExtrude(self): r = 1.0 h = 1.0 decimal_places = 9.0 # extrude in one direction s = Workplane("XY").circle(r).extrude(h, both=False) top_face = s.faces(">Z") bottom_face = s.faces("<Z") # calculate the distance between the top and the bottom face delta = top_face.val().Center().sub(bottom_face.val().Center()) self.assertTupleAlmostEquals(delta.toTuple(), (0.0, 0.0, h), decimal_places) # extrude symmetrically s = Workplane("XY").circle(r).extrude(h, both=True) self.assertTrue(len(s.val().Solids()) == 1) top_face = s.faces(">Z") bottom_face = s.faces("<Z") # calculate the distance between the top and the bottom face delta = top_face.val().Center().sub(bottom_face.val().Center()) self.assertTupleAlmostEquals( delta.toTuple(), (0.0, 0.0, 2.0 * h), decimal_places ) # check that non-conplanar extrusion raises with self.assertRaises(ValueError): Workplane().box(1, 1, 1).faces().circle(0.1).extrude(0.1) def testTaperedExtrudeCutBlind(self): h = 1.0 r = 1.0 t = 5 # extrude with a positive taper s = Workplane("XY").circle(r).extrude(h, taper=t) top_face = s.faces(">Z") bottom_face = s.faces("<Z") # top and bottom face area delta = top_face.val().Area() - bottom_face.val().Area() self.assertTrue(delta < 0) # extrude with a negative taper s = Workplane("XY").circle(r).extrude(h, taper=-t) top_face = s.faces(">Z") bottom_face = s.faces("<Z") # top and bottom face area delta = top_face.val().Area() - bottom_face.val().Area() self.assertTrue(delta > 0) # cut a tapered hole s = ( Workplane("XY") .rect(2 * r, 2 * r) .extrude(2 * h) .faces(">Z") .workplane() .rect(r, r) .cutBlind(-h, taper=t) ) middle_face = s.faces(">Z[-2]") self.assertTrue(middle_face.val().Area() < 1) def testClose(self): # Close without endPoint and startPoint coincide. # Create a half-circle a = Workplane(Plane.XY()).sagittaArc((10, 0), 2).close().extrude(2) # Close when endPoint and startPoint coincide. # Create a double half-circle b = ( Workplane(Plane.XY()) .sagittaArc((10, 0), 2) .sagittaArc((0, 0), 2) .close() .extrude(2) ) # The b shape shall have twice the volume of the a shape. self.assertAlmostEqual(a.val().Volume() * 2.0, b.val().Volume()) # Testcase 3 from issue #238 thickness = 3.0 length = 10.0 width = 5.0 obj1 = ( Workplane("XY", origin=(0, 0, -thickness / 2)) .moveTo(length / 2, 0) .threePointArc((0, width / 2), (-length / 2, 0)) .threePointArc((0, -width / 2), (length / 2, 0)) .close() .extrude(thickness) ) os_x = 8.0 # Offset in X os_y = -19.5 # Offset in Y obj2 = ( Workplane("YZ", origin=(os_x, os_y, -thickness / 2)) .moveTo(os_x + length / 2, os_y) .sagittaArc((os_x - length / 2, os_y), width / 2) .sagittaArc((os_x + length / 2, os_y), width / 2) .close() .extrude(thickness) ) # The obj1 shape shall have the same volume as the obj2 shape. self.assertAlmostEqual(obj1.val().Volume(), obj2.val().Volume()) def testText(self): global testdataDir box = Workplane("XY").box(4, 4, 0.5) obj1 = ( box.faces(">Z") .workplane() .text( "CQ 2.0", 0.5, -0.05, cut=True, halign="left", valign="bottom", font="Sans", ) ) # combined object should have smaller volume self.assertGreater(box.val().Volume(), obj1.val().Volume()) obj2 = ( box.faces(">Z") .workplane() .text("CQ 2.0", 0.5, 0.05, cut=False, combine=True, font="Sans") ) # combined object should have bigger volume self.assertLess(box.val().Volume(), obj2.val().Volume()) # verify that the number of top faces is correct (NB: this is font specific) self.assertEqual(len(obj2.faces(">Z").vals()), 5) obj3 = ( box.faces(">Z") .workplane() .text( "CQ 2.0", 0.5, 0.05, cut=False, combine=False, halign="right", valign="top", font="Sans", ) ) # verify that the number of solids is correct self.assertEqual(len(obj3.solids().vals()), 5) obj4 = ( box.faces(">Z") .workplane() .text( "CQ 2.0", 0.5, 0.05, fontPath=os.path.join(testdataDir, "OpenSans-Regular.ttf"), cut=False, combine=False, halign="right", valign="top", font="Sans", ) ) # verify that the number of solids is correct self.assertEqual(len(obj4.solids().vals()), 5) # test to see if non-existent file causes segfault obj5 = ( box.faces(">Z") .workplane() .text( "CQ 2.0", 0.5, 0.05, fontPath=os.path.join(testdataDir, "OpenSans-Irregular.ttf"), cut=False, combine=False, halign="right", valign="top", font="Sans", ) ) # verify that the number of solids is correct self.assertEqual(len(obj5.solids().vals()), 5) # check it doesn't fall over with int sizes obj1 = ( box.faces(">Z") .workplane() .text( "CQ 2.0", 10, -1, cut=True, halign="left", valign="bottom", font="Sans", ) ) def testParametricCurve(self): from math import sin, cos, pi k = 4 r = 1 func = lambda t: ( r * (k + 1) * cos(t) - r * cos((k + 1) * t), r * (k + 1) * sin(t) - r * sin((k + 1) * t), ) res_open = Workplane("XY").parametricCurve(func).extrude(3) # open profile generates an invalid solid self.assertFalse(res_open.solids().val().isValid()) res_closed = ( Workplane("XY").parametricCurve(func, start=0, stop=2 * pi).extrude(3) ) # closed profile will generate a valid solid with 3 faces self.assertTrue(res_closed.solids().val().isValid()) self.assertEqual(len(res_closed.faces().vals()), 3) res_edge = Workplane("XY").parametricCurve(func, makeWire=False) self.assertEqual(len(res_edge.ctx.pendingEdges), 1) self.assertEqual(len(res_edge.ctx.pendingWires), 0) def testMakeShellSolid(self): c0 = math.sqrt(2) / 4 vertices = [[c0, -c0, c0], [c0, c0, -c0], [-c0, c0, c0], [-c0, -c0, -c0]] faces_ixs = [[0, 1, 2, 0], [1, 0, 3, 1], [2, 3, 0, 2], [3, 2, 1, 3]] faces = [] for ixs in faces_ixs: lines = [] for v1, v2 in zip(ixs, ixs[1:]): lines.append( Edge.makeLine(Vector(*vertices[v1]), Vector(*vertices[v2])) ) wire = Wire.combine(lines)[0] faces.append(Face.makeFromWires(wire)) shell = Shell.makeShell(faces) solid = Solid.makeSolid(shell) self.assertTrue(shell.isValid()) self.assertTrue(solid.isValid()) self.assertEqual(len(solid.Vertices()), 4) self.assertEqual(len(solid.Faces()), 4) def testIsInsideSolid(self): # test solid model = Workplane("XY").box(10, 10, 10) solid = model.val() # get first object on stack self.assertTrue(solid.isInside((0, 0, 0))) self.assertFalse(solid.isInside((10, 10, 10))) self.assertTrue(solid.isInside((Vector(3, 3, 3)))) self.assertFalse(solid.isInside((Vector(30.0, 30.0, 30.0)))) self.assertTrue(solid.isInside((0, 0, 4.99), tolerance=0.1)) self.assertTrue(solid.isInside((0, 0, 5))) # check point on surface self.assertTrue(solid.isInside((0, 0, 5.01), tolerance=0.1)) self.assertFalse(solid.isInside((0, 0, 5.1), tolerance=0.1)) # test compound solid model = Workplane("XY").box(10, 10, 10) model = model.moveTo(50, 50).box(10, 10, 10) solid = model.val() self.assertTrue(solid.isInside((0, 0, 0))) self.assertTrue(solid.isInside((50, 50, 0))) self.assertFalse(solid.isInside((50, 56, 0))) # make sure raises on non solid model = Workplane("XY").rect(10, 10) solid = model.val() with self.assertRaises(AttributeError): solid.isInside((0, 0, 0)) # test solid with an internal void void = Workplane("XY").box(10, 10, 10) model = Workplane("XY").box(100, 100, 100).cut(void) solid = model.val() self.assertFalse(solid.isInside((0, 0, 0))) self.assertTrue(solid.isInside((40, 40, 40))) self.assertFalse(solid.isInside((55, 55, 55))) def testWorkplaneCenterOptions(self): decimal_places = 9 pts = [(0, 0), (90, 0), (90, 30), (30, 30), (30, 60), (0.0, 60)] r = Workplane("XY").polyline(pts).close().extrude(10.0) origin = ( r.faces(">Z") .workplane(centerOption="ProjectedOrigin") .plane.origin.toTuple() ) self.assertTupleAlmostEquals(origin, (0.0, 0.0, 10.0), decimal_places) origin = ( r.faces(">Z").workplane(centerOption="CenterOfMass").plane.origin.toTuple() ) self.assertTupleAlmostEquals(origin, (37.5, 22.5, 10.0), decimal_places) origin = ( r.faces(">Z") .workplane(centerOption="CenterOfBoundBox") .plane.origin.toTuple() ) self.assertTupleAlmostEquals(origin, (45.0, 30.0, 10.0), decimal_places) origin = ( r.faces(">Z") .workplane(centerOption="ProjectedOrigin", origin=(30, 10, 20)) .plane.origin.toTuple() ) self.assertTupleAlmostEquals(origin, (30.0, 10.0, 10.0), decimal_places) origin = ( r.faces(">Z") .workplane(centerOption="ProjectedOrigin", origin=Vector(30, 10, 20)) .plane.origin.toTuple() ) self.assertTupleAlmostEquals(origin, (30.0, 10.0, 10.0), decimal_places) with self.assertRaises(ValueError): origin = r.faces(">Z").workplane(centerOption="undefined") # test case where plane origin is shifted with center call r = ( r.faces(">Z") .workplane(centerOption="ProjectedOrigin") .center(30, 0) .hole(90) ) origin = ( r.faces(">Z") .workplane(centerOption="ProjectedOrigin") .plane.origin.toTuple() ) self.assertTupleAlmostEquals(origin, (30.0, 0.0, 10.0), decimal_places) origin = ( r.faces(">Z") .workplane(centerOption="ProjectedOrigin", origin=(0, 0, 0)) .plane.origin.toTuple() ) self.assertTupleAlmostEquals(origin, (0.0, 0.0, 10.0), decimal_places) # make sure projection works in all directions r = Workplane("YZ").polyline(pts).close().extrude(10.0) origin = ( r.faces(">X") .workplane(centerOption="ProjectedOrigin") .plane.origin.toTuple() ) self.assertTupleAlmostEquals(origin, (10.0, 0.0, 0.0), decimal_places) origin = ( r.faces(">X").workplane(centerOption="CenterOfMass").plane.origin.toTuple() ) self.assertTupleAlmostEquals(origin, (10.0, 37.5, 22.5), decimal_places) origin = ( r.faces(">X") .workplane(centerOption="CenterOfBoundBox") .plane.origin.toTuple() ) self.assertTupleAlmostEquals(origin, (10.0, 45.0, 30.0), decimal_places) r = Workplane("XZ").polyline(pts).close().extrude(10.0) origin = ( r.faces("<Y") .workplane(centerOption="ProjectedOrigin") .plane.origin.toTuple() ) self.assertTupleAlmostEquals(origin, (0.0, -10.0, 0.0), decimal_places) origin = ( r.faces("<Y").workplane(centerOption="CenterOfMass").plane.origin.toTuple() ) self.assertTupleAlmostEquals(origin, (37.5, -10.0, 22.5), decimal_places) origin = ( r.faces("<Y") .workplane(centerOption="CenterOfBoundBox") .plane.origin.toTuple() ) self.assertTupleAlmostEquals(origin, (45.0, -10.0, 30.0), decimal_places) def testFindSolid(self): r = Workplane("XY").pushPoints([(-2, 0), (2, 0)]).box(1, 1, 1, combine=False) # there should be two solids on the stack self.assertEqual(len(r.objects), 2) self.assertTrue(isinstance(r.val(), Solid)) # find solid should return a compound of two solids s = r.findSolid() self.assertEqual(len(s.Solids()), 2) self.assertTrue(isinstance(s, Compound)) # if no solids are found, should raise ValueError w = Workplane().hLine(1).close() with raises(ValueError): w.findSolid() def testSlot2D(self): decimal_places = 9 # Ensure it produces a solid with the correct volume result = Workplane("XY").slot2D(4, 1, 0).extrude(1) self.assertAlmostEqual(result.val().Volume(), 3.785398163, decimal_places) # Test for proper expected behaviour when cutting box = Workplane("XY").box(5, 5, 1) result = box.faces(">Z").workplane().slot2D(4, 1, 0).cutThruAll() self.assertAlmostEqual(result.val().Volume(), 21.214601837, decimal_places) result = box.faces(">Z").workplane().slot2D(4, 1, 0).cutBlind(-0.5) self.assertAlmostEqual(result.val().Volume(), 23.107300918, decimal_places) # Test to see if slot is rotated correctly result = Workplane("XY").slot2D(4, 1, 45).extrude(1) point = result.faces(">Z").edges(">X").first().val().startPoint().toTuple() self.assertTupleAlmostEquals( point, (0.707106781, 1.414213562, 1.0), decimal_places ) def test_assembleEdges(self): # Plate with 5 sides and 2 bumps, one side is not co-planar with the other sides # Passes an open wire to assembleEdges so that IsDone is true but Error returns 2 to test the warning functionality. edge_points = [ [-7.0, -7.0, 0.0], [-3.0, -10.0, 3.0], [7.0, -7.0, 0.0], [7.0, 7.0, 0.0], [-7.0, 7.0, 0.0], ] edge_wire = Workplane("XY").polyline( [(-7.0, -7.0), (7.0, -7.0), (7.0, 7.0), (-7.0, 7.0)] ) edge_wire = edge_wire.add( Workplane("YZ") .workplane() .transformed(offset=Vector(0, 0, -7), rotate=Vector(45, 0, 0)) .spline([(-7.0, 0.0), (3, -3), (7.0, 0.0)]) ) edge_wire = [o.vals()[0] for o in edge_wire.all()] edge_wire = Wire.assembleEdges(edge_wire) # Embossed star, need to change optional parameters to obtain nice looking result. r1 = 3.0 r2 = 10.0 fn = 6 edge_points = [ [r1 * math.cos(i * math.pi / fn), r1 * math.sin(i * math.pi / fn)] if i % 2 == 0 else [r2 * math.cos(i * math.pi / fn), r2 * math.sin(i * math.pi / fn)] for i in range(2 * fn + 1) ] edge_wire = Workplane("XY").polyline(edge_points) edge_wire = [o.vals()[0] for o in edge_wire.all()] edge_wire = Wire.assembleEdges(edge_wire) # Points on hexagonal pattern coordinates, use of pushpoints. r1 = 1.0 fn = 6 edge_points = [ [r1 * math.cos(i * 2 * math.pi / fn), r1 * math.sin(i * 2 * math.pi / fn)] for i in range(fn + 1) ] surface_points = [ [0.25, 0, 0.75], [-0.25, 0, 0.75], [0, 0.25, 0.75], [0, -0.25, 0.75], [0, 0, 2], ] edge_wire = Workplane("XY").polyline(edge_points) edge_wire = [o.vals()[0] for o in edge_wire.all()] edge_wire = Wire.assembleEdges(edge_wire) # Gyroïd, all edges are splines on different workplanes. edge_points = [ [[3.54, 3.54], [1.77, 0.0], [3.54, -3.54]], [[-3.54, -3.54], [0.0, -1.77], [3.54, -3.54]], [[-3.54, -3.54], [0.0, -1.77], [3.54, -3.54]], [[-3.54, -3.54], [-1.77, 0.0], [-3.54, 3.54]], [[3.54, 3.54], [0.0, 1.77], [-3.54, 3.54]], [[3.54, 3.54], [0.0, 1.77], [-3.54, 3.54]], ] plane_list = ["XZ", "XY", "YZ", "XZ", "YZ", "XY"] offset_list = [-3.54, 3.54, 3.54, 3.54, -3.54, -3.54] edge_wire = ( Workplane(plane_list[0]) .workplane(offset=-offset_list[0]) .spline(edge_points[0]) ) for i in range(len(edge_points) - 1): edge_wire = edge_wire.add( Workplane(plane_list[i + 1]) .workplane(offset=-offset_list[i + 1]) .spline(edge_points[i + 1]) ) edge_wire = [o.vals()[0] for o in edge_wire.all()] edge_wire = Wire.assembleEdges(edge_wire) def testTag(self): # test tagging result = ( Workplane("XY") .pushPoints([(-2, 0), (2, 0)]) .box(1, 1, 1, combine=False) .tag("2 solids") .union(Workplane("XY").box(6, 1, 1)) ) self.assertEqual(len(result.objects), 1) result = result._getTagged("2 solids") self.assertEqual(len(result.objects), 2) with self.assertRaises(ValueError): result = result._getTagged("3 solids") def testCopyWorkplane(self): obj0 = Workplane("XY").box(1, 1, 10).faces(">Z").workplane() obj1 = Workplane("XY").copyWorkplane(obj0).box(1, 1, 1) self.assertTupleAlmostEquals((0, 0, 5), obj1.val().Center().toTuple(), 9) def testWorkplaneFromTagged(self): # create a flat, wide base. Extrude one object 4 units high, another # object on top of it 6 units high. Go back to base plane. Extrude an # object 11 units high. Assert that top face is 11 units high. result = ( Workplane("XY") .box(10, 10, 1, centered=(True, True, False)) .faces(">Z") .workplane() .tag("base") .center(3, 0) .rect(2, 2) .extrude(4) .faces(">Z") .workplane() .circle(1) .extrude(6) .workplaneFromTagged("base") .center(-3, 0) .circle(1) .extrude(11) ) self.assertTupleAlmostEquals( result.faces(">Z").val().Center().toTuple(), (-3, 0, 12), 9 ) def testWorkplaneOrientationOnVertex(self): # create a 10 unit sized cube on the XY plane parent = Workplane("XY").rect(10.0, 10.0).extrude(10) # assert that the direction tuples reflect accordingly assert parent.plane.xDir.toTuple() == approx((1.0, 0.0, 0.0)) assert parent.plane.zDir.toTuple() == approx((0.0, 0.0, 1.0)) # select the <XZ vertex on the <Y face and create a new workplane. child = parent.faces("<Y").vertices("<XZ").workplane() # assert that the direction tuples reflect the new workplane on the <Y face assert child.plane.xDir.toTuple() == approx((1.0, 0.0, -0.0)) assert child.plane.zDir.toTuple() == approx((0.0, -1.0, -0.0)) def testTagSelectors(self): result0 = Workplane("XY").box(1, 1, 1).tag("box").sphere(1) # result is currently a sphere self.assertEqual(1, result0.faces().size()) # a box has 8 vertices self.assertEqual(8, result0.vertices(tag="box").size()) # 6 faces self.assertEqual(6, result0.faces(tag="box").size()) # 12 edges self.assertEqual(12, result0.edges(tag="box").size()) # 6 wires self.assertEqual(6, result0.wires(tag="box").size()) # create two solids, tag them, join to one solid result1 = ( Workplane("XY") .pushPoints([(1, 0), (-1, 0)]) .box(1, 1, 1) .tag("boxes") .sphere(1) ) self.assertEqual(1, result1.solids().size()) self.assertEqual(2, result1.solids(tag="boxes").size()) self.assertEqual(1, result1.shells().size()) self.assertEqual(2, result1.shells(tag="boxes").size()) # create 4 individual objects, tag it, then combine to one compound result2 = ( Workplane("XY") .rect(4, 4) .vertices() .box(1, 1, 1, combine=False) .tag("4 objs") ) result2 = result2.newObject([Compound.makeCompound(result2.objects)]) self.assertEqual(1, result2.compounds().size()) self.assertEqual(0, result2.compounds(tag="4 objs").size()) def test_interpPlate(self): # example from PythonOCC core_geometry_geomplate.py, use of thickness = 0 returns 2D surface. thickness = 0 edge_points = [ [0.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 10.0, 10.0], [0.0, 0.0, 10.0], ] surface_points = [[5.0, 5.0, 5.0]] plate_0 = Workplane("XY").interpPlate(edge_points, surface_points, thickness) self.assertTrue(plate_0.val().isValid()) self.assertAlmostEqual(plate_0.val().Area(), 141.218823892, 1) # Plate with 5 sides and 2 bumps, one side is not co-planar with the other sides thickness = 0.1 edge_points = [ [-7.0, -7.0, 0.0], [-3.0, -10.0, 3.0], [7.0, -7.0, 0.0], [7.0, 7.0, 0.0], [-7.0, 7.0, 0.0], ] edge_wire = Workplane("XY").polyline( [(-7.0, -7.0), (7.0, -7.0), (7.0, 7.0), (-7.0, 7.0)] ) # edge_wire = edge_wire.add(Workplane('YZ').workplane().transformed(offset=Vector(0, 0, -7), rotate=Vector(45, 0, 0)).polyline([(-7.,0.), (3,-3), (7.,0.)])) # In CadQuery Sept-2019 it worked with rotate=Vector(0, 45, 0). In CadQuery Dec-2019 rotate=Vector(45, 0, 0) only closes the wire. edge_wire = edge_wire.add( Workplane("YZ") .workplane() .transformed(offset=Vector(0, 0, -7), rotate=Vector(45, 0, 0)) .spline([(-7.0, 0.0), (3, -3), (7.0, 0.0)]) ) surface_points = [[-3.0, -3.0, -3.0], [3.0, 3.0, 3.0]] plate_1 = Workplane("XY").interpPlate(edge_wire, surface_points, thickness) self.assertTrue(plate_1.val().isValid()) self.assertAlmostEqual(plate_1.val().Volume(), 26.124970206, 2) # Embossed star, need to change optional parameters to obtain nice looking result. r1 = 3.0 r2 = 10.0 fn = 6 thickness = 0.1 edge_points = [ [r1 * math.cos(i * math.pi / fn), r1 * math.sin(i * math.pi / fn)] if i % 2 == 0 else [r2 * math.cos(i * math.pi / fn), r2 * math.sin(i * math.pi / fn)] for i in range(2 * fn + 1) ] edge_wire = Workplane("XY").polyline(edge_points) r2 = 4.5 surface_points = [ [r2 * math.cos(i * math.pi / fn), r2 * math.sin(i * math.pi / fn), 1.0] for i in range(2 * fn) ] + [[0.0, 0.0, -2.0]] plate_2 = Workplane("XY").interpPlate( edge_wire, surface_points, thickness, combine=True, clean=True, degree=3, nbPtsOnCur=15, nbIter=2, anisotropy=False, tol2d=0.00001, tol3d=0.0001, tolAng=0.01, tolCurv=0.1, maxDeg=8, maxSegments=49, ) self.assertTrue(plate_2.val().isValid()) self.assertAlmostEqual(plate_2.val().Volume(), 10.956054314, 0) # Points on hexagonal pattern coordinates, use of pushpoints. r1 = 1.0 N = 3 ca = math.cos(30.0 * math.pi / 180.0) sa = math.sin(30.0 * math.pi / 180.0) # EVEN ROWS pts = [ (-3.0, -3.0), (-1.267949, -3.0), (0.464102, -3.0), (2.196152, -3.0), (-3.0, 0.0), (-1.267949, 0.0), (0.464102, 0.0), (2.196152, 0.0), (-2.133974, -1.5), (-0.401923, -1.5), (1.330127, -1.5), (3.062178, -1.5), (-2.133975, 1.5), (-0.401924, 1.5), (1.330127, 1.5), (3.062178, 1.5), ] # Spike surface thickness = 0.1 fn = 6 edge_points = [ [ r1 * math.cos(i * 2 * math.pi / fn + 30 * math.pi / 180), r1 * math.sin(i * 2 * math.pi / fn + 30 * math.pi / 180), ] for i in range(fn + 1) ] surface_points = [ [ r1 / 4 * math.cos(i * 2 * math.pi / fn + 30 * math.pi / 180), r1 / 4 * math.sin(i * 2 * math.pi / fn + 30 * math.pi / 180), 0.75, ] for i in range(fn + 1) ] + [[0, 0, 2]] edge_wire = Workplane("XY").polyline(edge_points) plate_3 = ( Workplane("XY") .pushPoints(pts) .interpPlate( edge_wire, surface_points, thickness, combine=False, clean=False, degree=2, nbPtsOnCur=20, nbIter=2, anisotropy=False, tol2d=0.00001, tol3d=0.0001, tolAng=0.01, tolCurv=0.1, maxDeg=8, maxSegments=9, ) ) self.assertTrue(plate_3.val().isValid()) self.assertAlmostEqual(plate_3.val().Volume(), 0.45893954685189414, 1) # Gyroïd, all edges are splines on different workplanes. thickness = 0.1 edge_points = [ [[3.54, 3.54], [1.77, 0.0], [3.54, -3.54]], [[-3.54, -3.54], [0.0, -1.77], [3.54, -3.54]], [[-3.54, -3.54], [0.0, -1.77], [3.54, -3.54]], [[-3.54, -3.54], [-1.77, 0.0], [-3.54, 3.54]], [[3.54, 3.54], [0.0, 1.77], [-3.54, 3.54]], [[3.54, 3.54], [0.0, 1.77], [-3.54, 3.54]], ] plane_list = ["XZ", "XY", "YZ", "XZ", "YZ", "XY"] offset_list = [-3.54, 3.54, 3.54, 3.54, -3.54, -3.54] edge_wire = ( Workplane(plane_list[0]) .workplane(offset=-offset_list[0]) .spline(edge_points[0]) ) for i in range(len(edge_points) - 1): edge_wire = edge_wire.add( Workplane(plane_list[i + 1]) .workplane(offset=-offset_list[i + 1]) .spline(edge_points[i + 1]) ) surface_points = [[0, 0, 0]] plate_4 = Workplane("XY").interpPlate(edge_wire, surface_points, thickness) self.assertTrue(plate_4.val().isValid()) self.assertAlmostEqual(plate_4.val().Volume(), 7.760559490, 2) def testTangentArcToPoint(self): # create a simple shape with tangents of straight edges and see if it has the correct area s0 = ( Workplane("XY") .hLine(1) .tangentArcPoint((1, 1), relative=False) .hLineTo(0) .tangentArcPoint((0, 0), relative=False) .close() .extrude(1) ) area0 = s0.faces(">Z").val().Area() self.assertAlmostEqual(area0, (1 + math.pi * 0.5 ** 2), 4) # test relative coords s1 = ( Workplane("XY") .hLine(1) .tangentArcPoint((0, 1), relative=True) .hLineTo(0) .tangentArcPoint((0, -1), relative=True) .close() .extrude(1) ) self.assertTupleAlmostEquals( s1.val().Center().toTuple(), s0.val().Center().toTuple(), 4 ) self.assertAlmostEqual(s1.val().Volume(), s0.val().Volume(), 4) # consecutive tangent arcs s1 = ( Workplane("XY") .vLine(2) .tangentArcPoint((1, 0)) .tangentArcPoint((1, 0)) .tangentArcPoint((1, 0)) .vLine(-2) .close() .extrude(1) ) self.assertAlmostEqual( s1.faces(">Z").val().Area(), 2 * 3 + 0.5 * math.pi * 0.5 ** 2, 4 ) # tangentArc on the end of a spline # spline will be a simple arc of a circle, then finished off with a # tangentArcPoint angles = [idx * 1.5 * math.pi / 10 for idx in range(10)] pts = [(math.sin(a), math.cos(a)) for a in angles] s2 = ( Workplane("XY") .spline(pts) .tangentArcPoint((0, 1), relative=False) .close() .extrude(1) ) # volume should almost be pi, but not accurately because we need to # start with a spline self.assertAlmostEqual(s2.val().Volume(), math.pi, 1) # assert local coords are mapped to global correctly arc0 = Workplane("XZ", origin=(1, 1, 1)).hLine(1).tangentArcPoint((1, 1)).val() self.assertTupleAlmostEquals(arc0.endPoint().toTuple(), (3, 1, 2), 4) # tangentArcPoint with 3-tuple argument w0 = Workplane("XY").lineTo(1, 1).tangentArcPoint((1, 1, 1)).wire() zmax = w0.val().BoundingBox().zmax self.assertAlmostEqual(zmax, 1, 1) def test_findFromEdge(self): part = Workplane("XY", origin=(1, 1, 1)).hLine(1) found_edge = part._findFromEdge(useLocalCoords=False) self.assertTupleAlmostEquals(found_edge.startPoint().toTuple(), (1, 1, 1), 3) self.assertTupleAlmostEquals(found_edge.Center().toTuple(), (1.5, 1, 1), 3) self.assertTupleAlmostEquals(found_edge.endPoint().toTuple(), (2, 1, 1), 3) found_edge = part._findFromEdge(useLocalCoords=True) self.assertTupleAlmostEquals(found_edge.endPoint().toTuple(), (1, 0, 0), 3) # check _findFromEdge can find a spline pts = [(0, 0), (0, 1), (1, 2), (2, 4)] spline0 = Workplane("XZ").spline(pts)._findFromEdge() self.assertTupleAlmostEquals((2, 0, 4), spline0.endPoint().toTuple(), 3) # check method fails if no edge is present part2 = Workplane("XY").box(1, 1, 1) with self.assertRaises(RuntimeError): part2._findFromEdge() with self.assertRaises(RuntimeError): part2._findFromEdge(useLocalCoords=True) def testMakeHelix(self): h = 10 pitch = 1.5 r = 1.2 obj = Wire.makeHelix(pitch, h, r) bb = obj.BoundingBox() self.assertAlmostEqual(bb.zlen, h, 1) def testUnionCompound(self): box1 = Workplane("XY").box(10, 20, 30) box2 = Workplane("YZ").box(10, 20, 30) shape_to_cut = Workplane("XY").box(15, 15, 15).translate((8, 8, 8)) list_of_shapes = [] for o in box1.all(): list_of_shapes.extend(o.vals()) for o in box2.all(): list_of_shapes.extend(o.vals()) obj = Workplane("XY").newObject(list_of_shapes).cut(shape_to_cut) assert obj.val().isValid() def testSection(self): box = Workplane("XY", origin=(1, 2, 3)).box(1, 1, 1) s1 = box.section() s2 = box.section(0.5) self.assertAlmostEqual(s1.faces().val().Area(), 1) self.assertAlmostEqual(s2.faces().val().Area(), 1) line = Workplane("XY").hLine(1) with self.assertRaises(ValueError): line.section() def testGlue(self): box1 = Workplane("XY").rect(1, 1).extrude(2) box2 = Workplane("XY", origin=(0, 1, 0)).rect(1, 1).extrude(1) res = box1.union(box2, glue=True) self.assertEqual(res.faces().size(), 8) obj = obj = ( Workplane("XY").rect(1, 1).extrude(2).moveTo(0, 2).rect(1, 1).extrude(2) ) res = obj.union(box2, glue=True) self.assertEqual(res.faces().size(), 10) def testFuzzyBoolOp(self): eps = 1e-3 box1 = Workplane("XY").box(1, 1, 1) box2 = Workplane("XY", origin=(1 + eps, 0.0)).box(1, 1, 1) box3 = Workplane("XY", origin=(2, 0, 0)).box(1, 1, 1) res = box1.union(box2) res_fuzzy = box1.union(box2, tol=eps) res_fuzzy2 = box1.union(box3).union(box2, tol=eps) self.assertEqual(res.solids().size(), 2) self.assertEqual(res_fuzzy.solids().size(), 1) self.assertEqual(res_fuzzy2.solids().size(), 1) def testLocatedMoved(self): box = Solid.makeBox(1, 1, 1, Vector(-0.5, -0.5, -0.5)) loc = Location(Vector(1, 1, 1)) box1 = box.located(loc) self.assertTupleAlmostEquals(box1.Center().toTuple(), (1, 1, 1), 6) self.assertTupleAlmostEquals(box.Center().toTuple(), (0, 0, 0), 6) box.locate(loc) self.assertTupleAlmostEquals(box.Center().toTuple(), (1, 1, 1), 6) box2 = box.moved(loc) self.assertTupleAlmostEquals(box.Center().toTuple(), (1, 1, 1), 6) self.assertTupleAlmostEquals(box2.Center().toTuple(), (2, 2, 2), 6) box.move(loc) self.assertTupleAlmostEquals(box.Center().toTuple(), (2, 2, 2), 6) def testNullShape(self): from OCP.TopoDS import TopoDS_Shape s = TopoDS_Shape() # make sure raises on non solid with self.assertRaises(ValueError): r = occ_impl.shapes.downcast(s) def testCenterOfBoundBox(self): obj = Workplane().pushPoints([(0, 0), (2, 2)]).box(1, 1, 1) c = obj.workplane(centerOption="CenterOfBoundBox").plane.origin self.assertTupleAlmostEquals(c.toTuple(), (1, 1, 0), 6) def testOffset2D(self): w1 = Workplane().rect(1, 1).offset2D(0.5, "arc") self.assertEqual(w1.edges().size(), 8) w2 = Workplane().rect(1, 1).offset2D(0.5, "tangent") self.assertEqual(w2.edges().size(), 4) w3 = Workplane().rect(1, 1).offset2D(0.5, "intersection") self.assertEqual(w3.edges().size(), 4) w4 = Workplane().pushPoints([(0, 0), (0, 5)]).rect(1, 1).offset2D(-0.5) self.assertEqual(w4.wires().size(), 0) w5 = Workplane().pushPoints([(0, 0), (0, 5)]).rect(1, 1).offset2D(-0.25) self.assertEqual(w5.wires().size(), 2) r = 20 s = 7 t = 1.5 points = [ (0, t / 2), (r / 2 - 1.5 * t, r / 2 - t), (s / 2, r / 2 - t), (s / 2, r / 2), (r / 2, r / 2), (r / 2, s / 2), (r / 2 - t, s / 2), (r / 2 - t, r / 2 - 1.5 * t), (t / 2, 0), ] s = ( Workplane("XY") .polyline(points) .mirrorX() .mirrorY() .offset2D(-0.9) .extrude(1) ) self.assertEqual(s.solids().size(), 4) # test forConstruction # forConstruction=True should place results in objects, not ctx.pendingWires w6 = Workplane().hLine(1).vLine(1).close().offset2D(0.5, forConstruction=True) self.assertEqual(len(w6.ctx.pendingWires), 0) self.assertEqual(w6.size(), 1) self.assertEqual(type(w6.val()), Wire) # make sure the resulting wire has forConstruction set self.assertEqual(w6.val().forConstruction, True) def testConsolidateWires(self): w1 = Workplane().lineTo(0, 1).lineTo(1, 1).consolidateWires() self.assertEqual(w1.size(), 1) w1 = Workplane().consolidateWires() self.assertEqual(w1.size(), 0) def testLocationAt(self): r = 1 e = Wire.makeHelix(r, r, r).Edges()[0] locs_frenet = e.locations([0, 1], frame="frenet") T1 = locs_frenet[0].wrapped.Transformation() T2 = locs_frenet[1].wrapped.Transformation() self.assertAlmostEqual(T1.TranslationPart().X(), r, 6) self.assertAlmostEqual(T2.TranslationPart().X(), r, 6) self.assertAlmostEqual( T1.GetRotation().GetRotationAngle(), -T2.GetRotation().GetRotationAngle(), 6 ) ga = e._geomAdaptor() locs_corrected = e.locations( [ga.FirstParameter(), ga.LastParameter()], mode="parameter", frame="corrected", ) T3 = locs_corrected[0].wrapped.Transformation() T4 = locs_corrected[1].wrapped.Transformation() self.assertAlmostEqual(T3.TranslationPart().X(), r, 6) self.assertAlmostEqual(T4.TranslationPart().X(), r, 6) w = Wire.assembleEdges( [ Edge.makeLine(Vector(), Vector(0, 1)), Edge.makeLine(Vector(0, 1), Vector(1, 1)), ] ) locs_wire = e.locations([0, 1]) T5 = locs_wire[0].wrapped.Transformation() T6 = locs_wire[1].wrapped.Transformation() self.assertAlmostEqual(T5.TranslationPart().X(), r, 0) self.assertAlmostEqual(T6.TranslationPart().X(), r, 1) def testNormal(self): circ = Workplane().circle(1).edges().val() n = circ.normal() self.assertTupleAlmostEquals(n.toTuple(), (0, 0, 1), 6) ell = Workplane().ellipse(1, 2).edges().val() n = ell.normal() self.assertTupleAlmostEquals(n.toTuple(), (0, 0, 1), 6) r = Workplane().rect(1, 2).wires().val() n = r.normal() self.assertTupleAlmostEquals(n.toTuple(), (0, 0, 1), 6) with self.assertRaises(ValueError): edge = Workplane().rect(1, 2).edges().val() n = edge.normal() def testPositionAt(self): # test with an open wire w = Workplane().lineTo(0, 1).lineTo(1, 1).wire().val() p0 = w.positionAt(0.0) p1 = w.positionAt(0.5) p2 = w.positionAt(1.0) self.assertTupleAlmostEquals(p0.toTuple(), (0, 0, 0), 6) self.assertTupleAlmostEquals(p1.toTuple(), (0, 1, 0), 6) self.assertTupleAlmostEquals(p2.toTuple(), (1, 1, 0), 6) p0 = w.positionAt(0.0, mode="param") self.assertTupleAlmostEquals(p0.toTuple(), (0, 0, 0), 6) p0, p1, p2 = w.positions([0.0, 0.25, 0.5]) self.assertTupleAlmostEquals(p0.toTuple(), (0, 0, 0), 6) self.assertTupleAlmostEquals(p1.toTuple(), (0, 0.5, 0), 6) self.assertTupleAlmostEquals(p2.toTuple(), (0, 1, 0), 6) # test with a closed wire w = Workplane().lineTo(0, 1).close().wire().val() p0 = w.positionAt(0.0) p1 = w.positionAt(0.5) p2 = w.positionAt(1.0) self.assertTupleAlmostEquals(p0.toTuple(), p2.toTuple(), 6) self.assertTupleAlmostEquals(p1.toTuple(), (0, 1, 0), 6) def testTangengAt(self): pts = [(0, 0), (-1, 1), (-2, 0), (-1, 0)] path = Workplane("XZ").spline(pts, tangents=((0, 1), (1, 0))).val() self.assertTrue( path.tangentAt(0.0, mode="parameter") == path.tangentAt(0.0, mode="length") ) self.assertFalse( path.tangentAt(0.5, mode="parameter") == path.tangentAt(0.5, mode="length") ) arc = Workplane().radiusArc((2, 0), 1).val() self.assertTupleAlmostEquals( arc.tangentAt(math.pi / 2, "parameter").toTuple(), (1, 0, 0), 6 ) self.assertTupleAlmostEquals( arc.tangentAt(0.5, "length").toTuple(), (1, 0, 0), 6 ) def testEnd(self): with self.assertRaises(ValueError): Workplane().end() self.assertTrue(Workplane().objects == []) self.assertTrue(Workplane().box(1, 1, 1).end().objects == []) self.assertTrue(Workplane().box(1, 1, 1).box(2, 2, 1).end(2).objects == []) def testCutEach(self): # base shape: w = Workplane().box(3, 2, 2) # cutter: c = Workplane().box(2, 2, 2).val() # cut all the corners off w0 = w.vertices().cutEach(lambda loc: c.located(loc)) # we are left with a 1x2x2 box: self.assertAlmostEqual(w0.val().Volume(), 4, 3) # test error on no solid found w1 = Workplane().hLine(1).vLine(1).close() with raises(ValueError): w1.cutEach(lambda loc: c.located(loc)) def testCutBlind(self): # cutBlind is already tested in several of the complicated tests, so this method is short. # test ValueError on no solid found w0 = Workplane().hLine(1).vLine(1).close() with raises(ValueError): w0.cutBlind(1) def testFindFace(self): # if there are no faces to find, should raise ValueError w0 = Workplane() with raises(ValueError): w0.findFace() w1 = Workplane().box(1, 1, 1).faces(">Z") self.assertTrue(isinstance(w1.findFace(), Face)) with raises(ValueError): w1.findFace(searchStack=False) w2 = w1.workplane().circle(0.1).extrude(0.1) self.assertTrue(isinstance(w2.findFace(searchParents=True), Face)) with raises(ValueError): w2.findFace(searchParents=False) def testPopPending(self): # test pending edges w0 = Workplane().hLine(1) self.assertEqual(len(w0.ctx.pendingEdges), 1) edges = w0.ctx.popPendingEdges() self.assertEqual(len(edges), 1) self.assertEqual(edges[0], w0.val()) # pending edges should now be cleared self.assertEqual(len(w0.ctx.pendingEdges), 0) # test pending wires w1 = Workplane().hLine(1).vLine(1).close() wire = w1.val() self.assertEqual(w1.ctx.pendingWires[0], wire) pop_pending_output = w1.ctx.popPendingWires() self.assertEqual(pop_pending_output[0], wire) # pending wires should now be cleared self.assertEqual(len(w1.ctx.pendingWires), 0) # test error when empty pending edges w2 = Workplane() # the following 2 should not raise an exception w2.ctx.popPendingEdges(errorOnEmpty=False) w2.ctx.popPendingWires(errorOnEmpty=False) # empty edges w3 = Workplane().hLine(1).vLine(1).close() with self.assertRaises(ValueError): w3.ctx.popPendingEdges() # empty wires w4 = Workplane().circle(1).extrude(1) with self.assertRaises(ValueError): w4.ctx.popPendingWires() # test via cutBlind w5 = Workplane().circle(1).extrude(1) with self.assertRaises(ValueError): w5.cutBlind(-1) def testCompSolid(self): from OCP.BRepPrimAPI import BRepPrimAPI_MakePrism tool = Solid.makeSphere(1, angleDegrees3=120) shell = tool.Shells()[0] v = Vector(0, 0, 1) builder = BRepPrimAPI_MakePrism(shell.wrapped, v.wrapped) result = Shape.cast(builder.Shape()) self.assertEqual(len(result.CompSolids()), 1) self.assertEqual(len(result.Solids()), 4) def test2Dfillet(self): r = Workplane().rect(1, 2).wires().val() f = Face.makeFromWires(r) verts = r.Vertices() self.assertEqual(len(f.fillet2D(0.5, verts).Vertices()), 6) self.assertEqual(len(r.fillet2D(0.5, verts).Vertices()), 6) self.assertEqual(len(r.fillet2D(0.25, verts).Vertices()), 8) # Test fillet2D with open wire and single vertex w0 = Workplane().hLine(1).vLine(1).wire() w0_verts = w0.vertices(">X and <Y").vals() unfilleted_wire0 = w0.val() filleted_wire0 = unfilleted_wire0.fillet2D(0.5, w0_verts) self.assertEqual(len(filleted_wire0.Vertices()), 4) # the filleted wire is shorter than the original self.assertGreater(unfilleted_wire0.Length() - filleted_wire0.Length(), 0.1) def test2Dchamfer(self): r = Workplane().rect(1, 2).wires().val() f = Face.makeFromWires(r) verts = r.Vertices() self.assertEqual(len(f.chamfer2D(0.5, verts).Vertices()), 6) self.assertEqual(len(r.chamfer2D(0.5, verts).Vertices()), 6) self.assertEqual(len(r.chamfer2D(0.25, verts).Vertices()), 8) r = Workplane().hLine(1).vLine(1).wire().val() vs = r.Vertices() self.assertEqual(len(r.chamfer2D(0.25, [vs[1]]).Vertices()), 4) with raises(ValueError): r.chamfer2D(0.25, [vs[0]]) def testSplineApprox(self): from .naca import naca5305 from math import pi, cos pts = [Vector(e[0], e[1], 0) for e in naca5305] # spline e1 = Edge.makeSplineApprox(pts, 1e-6, maxDeg=6, smoothing=(1, 1, 1)) e2 = Edge.makeSplineApprox(pts, 1e-6, minDeg=2, maxDeg=6) self.assertTrue(e1.isValid()) self.assertTrue(e2.isValid()) self.assertTrue(e1.Length() > e2.Length()) with raises(ValueError): e4 = Edge.makeSplineApprox(pts, 1e-6, maxDeg=3, smoothing=(1, 1, 1.0)) pts_closed = pts + [pts[0]] e3 = Edge.makeSplineApprox(pts_closed) w = Edge.makeSplineApprox(pts).close() self.assertTrue(e3.IsClosed()) self.assertTrue(w.IsClosed()) # Workplane method w1 = Workplane().splineApprox(pts) w2 = Workplane().splineApprox(pts, forConstruction=True) w3 = Workplane().splineApprox(pts, makeWire=True) w4 = Workplane().splineApprox(pts, makeWire=True, forConstruction=True) self.assertEqual(w1.edges().size(), 1) self.assertEqual(len(w1.ctx.pendingEdges), 1) self.assertEqual(w2.edges().size(), 1) self.assertEqual(len(w2.ctx.pendingEdges), 0) self.assertEqual(w3.wires().size(), 1) self.assertEqual(len(w3.ctx.pendingWires), 1) self.assertEqual(w4.wires().size(), 1) self.assertEqual(len(w4.ctx.pendingWires), 0) # spline surface N = 40 T = 20 A = 5 pts = [ [ Vector(i, j, A * cos(2 * pi * i / T) * cos(2 * pi * j / T)) for i in range(N + 1) ] for j in range(N + 1) ] f1 = Face.makeSplineApprox(pts, smoothing=(1, 1, 1), maxDeg=6) f2 = Face.makeSplineApprox(pts) self.assertTrue(f1.isValid()) self.assertTrue(f2.isValid()) with raises(ValueError): f3 = Face.makeSplineApprox(pts, smoothing=(1, 1, 1), maxDeg=3) def testParametricSurface(self): from math import pi, cos r1 = Workplane().parametricSurface( lambda u, v: (u, v, cos(pi * u) * cos(pi * v)), start=-1, stop=1 ) self.assertTrue(r1.faces().val().isValid()) r2 = Workplane().box(1, 1, 3).split(r1) self.assertTrue(r2.solids().val().isValid()) self.assertEqual(r2.solids().size(), 2) def testEdgeWireClose(self): # test with edge e0 = Edge.makeThreePointArc(Vector(0, 0, 0), Vector(1, 1, 0), Vector(0, 2, 0)) self.assertFalse(e0.IsClosed()) w0 = e0.close() self.assertTrue(w0.IsClosed()) # test with already closed edge e1 = Edge.makeCircle(1) self.assertTrue(e1.IsClosed()) e2 = e1.close() self.assertTrue(e2.IsClosed()) self.assertEqual(type(e1), type(e2)) # test with already closed WIRE w1 = Wire.makeCircle(1, Vector(), Vector(0, 0, 1)) self.assertTrue(w1.IsClosed()) w2 = w1.close() self.assertTrue(w1 is w2) def testSplitShape(self): # split an edge with a vertex e0 = Edge.makeCircle(1, (0, 0, 0), (0, 0, 1)) v0 = Vertex.makeVertex(0, 1, 0) list_of_edges = e0.split(v0).Edges() self.assertEqual(len(list_of_edges), 2) self.assertTrue(Vector(0, 1, 0) in [e.endPoint() for e in list_of_edges]) # split a circle with multiple vertices angles = [2 * math.pi * idx / 10 for idx in range(10)] vecs = [Vector(math.sin(a), math.cos(a), 0) for a in angles] vertices = [Vertex.makeVertex(*v.toTuple()) for v in vecs] edges = e0.split(*vertices).Edges() self.assertEqual(len(edges), len(vertices) + 1) endpoints = [e.endPoint() for e in edges] self.assertTrue(all([v in endpoints for v in vecs])) def testBrepImportExport(self): # import/export to file s = Workplane().box(1, 1, 1).val() s.exportBrep("test.brep") si = Shape.importBrep("test.brep") self.assertTrue(si.isValid()) self.assertAlmostEqual(si.Volume(), 1) # import/export to BytesIO from io import BytesIO bio = BytesIO() s.exportBrep(bio) bio.seek(0) si = Shape.importBrep("test.brep") self.assertTrue(si.isValid()) self.assertAlmostEqual(si.Volume(), 1) def testFaceToPln(self): origin = (1, 2, 3) normal = (1, 1, 1) f0 = Face.makePlane(length=None, width=None, basePnt=origin, dir=normal) p0 = f0.toPln() self.assertTrue(Vector(p0.Location()) == Vector(origin)) self.assertTrue(Vector(p0.Axis().Direction()) == Vector(normal).normalized()) origin1 = (0, 0, -3) normal1 = (-1, 1, -1) f1 = Face.makePlane(length=0.1, width=100, basePnt=origin1, dir=normal1) p1 = f1.toPln() self.assertTrue(Vector(p1.Location()) == Vector(origin1)) self.assertTrue(Vector(p1.Axis().Direction()) == Vector(normal1).normalized()) f2 = Workplane().box(1, 1, 10, centered=False).faces(">Z").val() p2 = f2.toPln() self.assertTrue(p2.Contains(f2.Center().toPnt(), 0.1)) self.assertTrue(Vector(p2.Axis().Direction()) == f2.normalAt())
true
true
f717ae14e4c0f23eb4e044fafbe02e361dc9be71
6,397
py
Python
src/datadog_api_client/v2/model/incident_service_update_data.py
DataDog/datadog-api-client-python
de2fc57dbde9acf4b8c8eef94ac29911227a62a2
[ "Apache-2.0" ]
32
2021-01-07T15:09:56.000Z
2022-01-30T05:49:23.000Z
src/datadog_api_client/v2/model/incident_service_update_data.py
DataDog/datadog-api-client-python
de2fc57dbde9acf4b8c8eef94ac29911227a62a2
[ "Apache-2.0" ]
228
2020-09-03T14:03:54.000Z
2022-03-31T20:16:12.000Z
src/datadog_api_client/v2/model/incident_service_update_data.py
DataDog/datadog-api-client-python
de2fc57dbde9acf4b8c8eef94ac29911227a62a2
[ "Apache-2.0" ]
12
2020-09-15T21:36:03.000Z
2022-03-31T17:13:17.000Z
# Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License. # This product includes software developed at Datadog (https://www.datadoghq.com/). # Copyright 2019-Present Datadog, Inc. from datadog_api_client.v2.model_utils import ( # noqa: F401 ApiTypeError, ModelComposed, ModelNormal, ModelSimple, cached_property, change_keys_js_to_python, convert_js_args_to_python_args, date, datetime, file_type, none_type, ) def lazy_import(): from datadog_api_client.v2.model.incident_service_relationships import IncidentServiceRelationships from datadog_api_client.v2.model.incident_service_type import IncidentServiceType from datadog_api_client.v2.model.incident_service_update_attributes import IncidentServiceUpdateAttributes globals()["IncidentServiceRelationships"] = IncidentServiceRelationships globals()["IncidentServiceType"] = IncidentServiceType globals()["IncidentServiceUpdateAttributes"] = IncidentServiceUpdateAttributes class IncidentServiceUpdateData(ModelNormal): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. Attributes: allowed_values (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict with a capitalized key describing the allowed value and an allowed value. These dicts store the allowed enum values. attribute_map (dict): The key is attribute name and the value is json key in definition. discriminator_value_class_map (dict): A dict to go from the discriminator variable value to the discriminator class name. validations (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict that stores validations for max_length, min_length, max_items, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, inclusive_minimum, and regex. additional_properties_type (tuple): A tuple of classes accepted as additional properties values. """ allowed_values = {} validations = {} additional_properties_type = None _nullable = False @cached_property def openapi_types(): """ This must be a method because a model may have properties that are of type self, this must run after the class is loaded Returns openapi_types (dict): The key is attribute name and the value is attribute type. """ lazy_import() return { "type": (IncidentServiceType,), # noqa: E501 "attributes": (IncidentServiceUpdateAttributes,), # noqa: E501 "id": (str,), # noqa: E501 "relationships": (IncidentServiceRelationships,), # noqa: E501 } discriminator = None attribute_map = { "type": "type", # noqa: E501 "attributes": "attributes", # noqa: E501 "id": "id", # noqa: E501 "relationships": "relationships", # noqa: E501 } read_only_vars = {} _composed_schemas = {} @convert_js_args_to_python_args def __init__(self, type, *args, **kwargs): # noqa: E501 """IncidentServiceUpdateData - a model defined in OpenAPI Args: type (IncidentServiceType): Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. Defaults to True _path_to_item (tuple/list): This is a list of keys or values to drill down to the model in received_data when deserializing a response _spec_property_naming (bool): True if the variable names in the input data are serialized names, as specified in the OpenAPI document. False if the variable names in the input data are pythonic names, e.g. snake case (default) _configuration (Configuration): the instance to use when deserializing a file_type parameter. If passed, type conversion is attempted If omitted no type conversion is done. _visited_composed_classes (tuple): This stores a tuple of classes that we have traveled through so that if we see that class again we will not use its discriminator again. When traveling through a discriminator, the composed schema that is is traveled through is added to this set. For example if Animal has a discriminator petType and we pass in "Dog", and the class Dog allOf includes Animal, we move through Animal once using the discriminator, and pick Dog. Then in Dog, we will make an instance of the Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) attributes (IncidentServiceUpdateAttributes): [optional] # noqa: E501 id (str): The incident service's ID.. [optional] # noqa: E501 relationships (IncidentServiceRelationships): [optional] # noqa: E501 """ super().__init__(kwargs) self._check_pos_args(args) self.type = type @classmethod @convert_js_args_to_python_args def _from_openapi_data(cls, type, *args, **kwargs): # noqa: E501 """Helper creating a new instance from a response.""" self = super(IncidentServiceUpdateData, cls)._from_openapi_data(kwargs) self._check_pos_args(args) self.type = type return self
41.810458
110
0.612318
from datadog_api_client.v2.model_utils import ( ApiTypeError, ModelComposed, ModelNormal, ModelSimple, cached_property, change_keys_js_to_python, convert_js_args_to_python_args, date, datetime, file_type, none_type, ) def lazy_import(): from datadog_api_client.v2.model.incident_service_relationships import IncidentServiceRelationships from datadog_api_client.v2.model.incident_service_type import IncidentServiceType from datadog_api_client.v2.model.incident_service_update_attributes import IncidentServiceUpdateAttributes globals()["IncidentServiceRelationships"] = IncidentServiceRelationships globals()["IncidentServiceType"] = IncidentServiceType globals()["IncidentServiceUpdateAttributes"] = IncidentServiceUpdateAttributes class IncidentServiceUpdateData(ModelNormal): allowed_values = {} validations = {} additional_properties_type = None _nullable = False @cached_property def openapi_types(): lazy_import() return { "type": (IncidentServiceType,), "attributes": (IncidentServiceUpdateAttributes,), "id": (str,), "relationships": (IncidentServiceRelationships,), } discriminator = None attribute_map = { "type": "type", "attributes": "attributes", "id": "id", "relationships": "relationships", } read_only_vars = {} _composed_schemas = {} @convert_js_args_to_python_args def __init__(self, type, *args, **kwargs): super().__init__(kwargs) self._check_pos_args(args) self.type = type @classmethod @convert_js_args_to_python_args def _from_openapi_data(cls, type, *args, **kwargs): self = super(IncidentServiceUpdateData, cls)._from_openapi_data(kwargs) self._check_pos_args(args) self.type = type return self
true
true
f717ae4b52146d6d410534878463dfe84c747e04
1,598
py
Python
configs/lesa/lesa_mask_rcnn_r50_dconv_c3-c5_8x1_20e.py
Chenglin-Yang/LESA_detection
3238bd9c6f3eb4a2a746837043cd9b3b56c77216
[ "Apache-2.0" ]
4
2021-07-18T08:09:09.000Z
2022-01-06T06:19:00.000Z
configs/lesa/lesa_mask_rcnn_r50_dconv_c3-c5_8x1_20e.py
Chenglin-Yang/LESA_detection
3238bd9c6f3eb4a2a746837043cd9b3b56c77216
[ "Apache-2.0" ]
null
null
null
configs/lesa/lesa_mask_rcnn_r50_dconv_c3-c5_8x1_20e.py
Chenglin-Yang/LESA_detection
3238bd9c6f3eb4a2a746837043cd9b3b56c77216
[ "Apache-2.0" ]
1
2022-01-06T06:18:53.000Z
2022-01-06T06:18:53.000Z
_base_ = [ '../_base_/models/mask_rcnn_r50_fpn.py', '../_base_/datasets/coco_instance_1024.py', '../_base_/schedules/schedule_20e.py', '../_base_/default_runtime.py', ] optimizer = dict(lr=0.01) model = dict( pretrained=\ './checkpoints/lesa_pretrained_imagenet/'+\ 'lesa_resnet50_pretrained/'+\ 'lesa_resnet50/'+\ 'checkpoint.pth', backbone=dict( type='ResNet', strides=(1,2,2,2), wrn=False, dcn=dict(type='DCN', deform_groups=1, fallback_on_stride=False), stage_with_dcn=(False, True, True, True), stage_spatial_res=[256, 128, 64, 32], # 1024: [256, 128, 64, 32], 1280: [320, 160, 80, 40] stage_with_first_conv = [True, True, True, False], lesa=dict( type='LESA', with_cp_UB_terms_only=True, # cp used on the unary and binary terms only. pe_type='detection_qr', # ('classification', 'detection_qr') groups = 8, df_channel_shrink = [2], # df: dynamic fusion df_kernel_size = [1,1], df_group = [1,1], ), stage_with_lesa = (False, False, True, True), ), rpn_head=dict( anchor_generator=dict( type='AnchorGenerator', scales=[8], ratios=[0.5, 1.0, 2.0], strides=[4, 8, 16, 32, 64]), ), ) data_root = 'data/coco/' data = dict( samples_per_gpu=1, workers_per_gpu=1, # test=dict( # ann_file=data_root + 'annotations/image_info_test-dev2017.json', # img_prefix=data_root + 'test2017/'), )
28.535714
98
0.570088
_base_ = [ '../_base_/models/mask_rcnn_r50_fpn.py', '../_base_/datasets/coco_instance_1024.py', '../_base_/schedules/schedule_20e.py', '../_base_/default_runtime.py', ] optimizer = dict(lr=0.01) model = dict( pretrained=\ './checkpoints/lesa_pretrained_imagenet/'+\ 'lesa_resnet50_pretrained/'+\ 'lesa_resnet50/'+\ 'checkpoint.pth', backbone=dict( type='ResNet', strides=(1,2,2,2), wrn=False, dcn=dict(type='DCN', deform_groups=1, fallback_on_stride=False), stage_with_dcn=(False, True, True, True), stage_spatial_res=[256, 128, 64, 32], stage_with_first_conv = [True, True, True, False], lesa=dict( type='LESA', with_cp_UB_terms_only=True, pe_type='detection_qr', groups = 8, df_channel_shrink = [2], df_kernel_size = [1,1], df_group = [1,1], ), stage_with_lesa = (False, False, True, True), ), rpn_head=dict( anchor_generator=dict( type='AnchorGenerator', scales=[8], ratios=[0.5, 1.0, 2.0], strides=[4, 8, 16, 32, 64]), ), ) data_root = 'data/coco/' data = dict( samples_per_gpu=1, workers_per_gpu=1, )
true
true
f717aeda2009266b9983c6e194696efc982f1189
1,312
py
Python
injectable/testing/clear_injectables_util.py
mt3o/injectable
0ffc5c758b63d9391134cd822158e1846999b404
[ "MIT" ]
71
2018-02-05T04:12:27.000Z
2022-02-15T23:08:16.000Z
injectable/testing/clear_injectables_util.py
Euraxluo/injectable
74e640f0911480fb06fa97c1a468c3863541c0fd
[ "MIT" ]
104
2018-02-06T23:37:36.000Z
2021-08-25T04:50:15.000Z
injectable/testing/clear_injectables_util.py
Euraxluo/injectable
74e640f0911480fb06fa97c1a468c3863541c0fd
[ "MIT" ]
13
2019-02-10T18:52:50.000Z
2022-01-26T17:12:35.000Z
from typing import Union, Set from injectable import InjectionContainer from injectable.common_utils import get_dependency_name from injectable.container.injectable import Injectable from injectable.constants import DEFAULT_NAMESPACE def clear_injectables( dependency: Union[type, str], namespace: str = None ) -> Set[Injectable]: """ Utility function to clear all injectables registered for the dependency in a given namespace. Returns a set containing all cleared injectables. :param dependency: class or qualifier of the dependency. :param namespace: (optional) namespace in which the injectable will be registered. Defaults to :const:`injectable.constants.DEFAULT_NAMESPACE`. Usage:: >>> from injectable.testing import clear_injectables >>> clear_injectables("foo") .. versionadded:: 3.3.0 """ namespace = InjectionContainer.NAMESPACES[namespace or DEFAULT_NAMESPACE] if isinstance(dependency, str): injectables = namespace.qualifier_registry[dependency] namespace.qualifier_registry[dependency] = set() else: dependency_name = get_dependency_name(dependency) injectables = namespace.class_registry[dependency_name] namespace.class_registry[dependency_name] = set() return injectables
36.444444
86
0.747713
from typing import Union, Set from injectable import InjectionContainer from injectable.common_utils import get_dependency_name from injectable.container.injectable import Injectable from injectable.constants import DEFAULT_NAMESPACE def clear_injectables( dependency: Union[type, str], namespace: str = None ) -> Set[Injectable]: namespace = InjectionContainer.NAMESPACES[namespace or DEFAULT_NAMESPACE] if isinstance(dependency, str): injectables = namespace.qualifier_registry[dependency] namespace.qualifier_registry[dependency] = set() else: dependency_name = get_dependency_name(dependency) injectables = namespace.class_registry[dependency_name] namespace.class_registry[dependency_name] = set() return injectables
true
true
f717afa83d677a0b51cae1b85b8a1bc081942f7a
5,143
py
Python
setup.py
lead-ratings/python-nvd3
2e677886d7b36f3aca641bbb2cc1117c3589b849
[ "MIT" ]
null
null
null
setup.py
lead-ratings/python-nvd3
2e677886d7b36f3aca641bbb2cc1117c3589b849
[ "MIT" ]
null
null
null
setup.py
lead-ratings/python-nvd3
2e677886d7b36f3aca641bbb2cc1117c3589b849
[ "MIT" ]
null
null
null
#! /usr/bin/env python # coding=utf-8 import os from setuptools import setup, find_packages from fnmatch import fnmatchcase from distutils.util import convert_path def read(*parts): return open(os.path.join(os.path.dirname(__file__), *parts)).read() # Provided as an attribute, so you can append to these instead # of replicating them: standard_exclude = ('*.py', '*.pyc', '*$py.class', '*~', '.*', '*.bak') standard_exclude_directories = ('.*', 'CVS', '_darcs', './build', './dist', 'EGG-INFO', '*.egg-info') # (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org) # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php # Note: you may want to copy this into your setup.py file verbatim, as # you can't import this from another package, when you don't know if # that package is installed yet. def find_package_data(where='.', package='', exclude=standard_exclude, exclude_directories=standard_exclude_directories, only_in_packages=True, show_ignored=False): """ Return a dictionary suitable for use in ``package_data`` in a distutils ``setup.py`` file. The dictionary looks like:: {'package': [files]} Where ``files`` is a list of all the files in that package that don't match anything in ``exclude``. If ``only_in_packages`` is true, then top-level directories that are not packages won't be included (but directories under packages will). Directories matching any pattern in ``exclude_directories`` will be ignored; by default directories with leading ``.``, ``CVS``, and ``_darcs`` will be ignored. If ``show_ignored`` is true, then all the files that aren't included in package data are shown on stderr (for debugging purposes). Note patterns use wildcards, or can be exact paths (including leading ``./``), and all searching is case-insensitive. """ out = {} stack = [(convert_path(where), '', package, only_in_packages)] while stack: where, prefix, package, only_in_packages = stack.pop(0) for name in os.listdir(where): fn = os.path.join(where, name) if os.path.isdir(fn): bad_name = False for pattern in exclude_directories: if (fnmatchcase(name, pattern) or fn.lower() == pattern.lower()): bad_name = True if show_ignored: print ("Directory %s ignored by pattern %s" % (fn, pattern)) break if bad_name: continue if (os.path.isfile(os.path.join(fn, '__init__.py')) and not prefix): if not package: new_package = name else: new_package = package + '.' + name stack.append((fn, '', new_package, False)) else: stack.append((fn, prefix + name + '/', package, only_in_packages)) elif package or not only_in_packages: # is a file bad_name = False for pattern in exclude: if (fnmatchcase(name, pattern) or fn.lower() == pattern.lower()): bad_name = True if show_ignored: print ("File %s ignored by pattern %s" % (fn, pattern)) break if bad_name: continue out.setdefault(package, []).append(prefix + name) return out setup( name='python-nvd3', version='0.13.5', description="Python NVD3 - Chart Library for d3.js", long_description=read('README.rst'), keywords='plot, graph, nvd3, d3', author='Belaid Arezqui', author_email='areski@gmail.com', url='http://github.com/areski/python-nvd3', license='MIT license', py_modules=['nvd3'], namespace_packages=[], test_suite='tests', packages=find_packages(), package_data=find_package_data(), zip_safe=False, install_requires=[ 'setuptools', 'python-slugify==0.0.9', 'Jinja2>=2.7.2' # -*- Extra requirements: -*- ], entry_points={ 'console_scripts': [ 'nvd3 = nvd3:_main', ], }, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Topic :: Multimedia :: Graphics :: Presentation', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
36.735714
88
0.569512
import os from setuptools import setup, find_packages from fnmatch import fnmatchcase from distutils.util import convert_path def read(*parts): return open(os.path.join(os.path.dirname(__file__), *parts)).read() standard_exclude = ('*.py', '*.pyc', '*$py.class', '*~', '.*', '*.bak') standard_exclude_directories = ('.*', 'CVS', '_darcs', './build', './dist', 'EGG-INFO', '*.egg-info') def find_package_data(where='.', package='', exclude=standard_exclude, exclude_directories=standard_exclude_directories, only_in_packages=True, show_ignored=False): out = {} stack = [(convert_path(where), '', package, only_in_packages)] while stack: where, prefix, package, only_in_packages = stack.pop(0) for name in os.listdir(where): fn = os.path.join(where, name) if os.path.isdir(fn): bad_name = False for pattern in exclude_directories: if (fnmatchcase(name, pattern) or fn.lower() == pattern.lower()): bad_name = True if show_ignored: print ("Directory %s ignored by pattern %s" % (fn, pattern)) break if bad_name: continue if (os.path.isfile(os.path.join(fn, '__init__.py')) and not prefix): if not package: new_package = name else: new_package = package + '.' + name stack.append((fn, '', new_package, False)) else: stack.append((fn, prefix + name + '/', package, only_in_packages)) elif package or not only_in_packages: bad_name = False for pattern in exclude: if (fnmatchcase(name, pattern) or fn.lower() == pattern.lower()): bad_name = True if show_ignored: print ("File %s ignored by pattern %s" % (fn, pattern)) break if bad_name: continue out.setdefault(package, []).append(prefix + name) return out setup( name='python-nvd3', version='0.13.5', description="Python NVD3 - Chart Library for d3.js", long_description=read('README.rst'), keywords='plot, graph, nvd3, d3', author='Belaid Arezqui', author_email='areski@gmail.com', url='http://github.com/areski/python-nvd3', license='MIT license', py_modules=['nvd3'], namespace_packages=[], test_suite='tests', packages=find_packages(), package_data=find_package_data(), zip_safe=False, install_requires=[ 'setuptools', 'python-slugify==0.0.9', 'Jinja2>=2.7.2' ], entry_points={ 'console_scripts': [ 'nvd3 = nvd3:_main', ], }, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Topic :: Multimedia :: Graphics :: Presentation', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
true
true
f717afcac3389e0e78ff975905922f94ec7b01ce
55,864
py
Python
lib/arrow/arrow.py
matke-84/script.module.arrow
7aa0903bc846541e4d620f10aca52957ba1e0e5b
[ "Apache-2.0" ]
null
null
null
lib/arrow/arrow.py
matke-84/script.module.arrow
7aa0903bc846541e4d620f10aca52957ba1e0e5b
[ "Apache-2.0" ]
null
null
null
lib/arrow/arrow.py
matke-84/script.module.arrow
7aa0903bc846541e4d620f10aca52957ba1e0e5b
[ "Apache-2.0" ]
null
null
null
""" Provides the :class:`Arrow <arrow.arrow.Arrow>` class, an enhanced ``datetime`` replacement. """ import calendar import sys from datetime import date from datetime import datetime as dt_datetime from datetime import time as dt_time from datetime import timedelta from datetime import tzinfo as dt_tzinfo from math import trunc from time import struct_time from typing import ( Any, ClassVar, Generator, Iterable, List, Mapping, Optional, Tuple, Union, cast, overload, ) from dateutil import tz as dateutil_tz from dateutil.relativedelta import relativedelta from arrow import formatter, locales, parser, util from arrow.locales import TimeFrameLiteral if sys.version_info < (3, 8): # pragma: no cover from typing_extensions import Final, Literal else: from typing import Final, Literal # pragma: no cover TZ_EXPR = Union[dt_tzinfo, str] _T_FRAMES = Literal[ "year", "years", "month", "months", "day", "days", "hour", "hours", "minute", "minutes", "second", "seconds", "microsecond", "microseconds", "week", "weeks", "quarter", "quarters", ] _BOUNDS = Literal["[)", "()", "(]", "[]"] _GRANULARITY = Literal[ "auto", "second", "minute", "hour", "day", "week", "month", "year", ] class Arrow: """An :class:`Arrow <arrow.arrow.Arrow>` object. Implements the ``datetime`` interface, behaving as an aware ``datetime`` while implementing additional functionality. :param year: the calendar year. :param month: the calendar month. :param day: the calendar day. :param hour: (optional) the hour. Defaults to 0. :param minute: (optional) the minute, Defaults to 0. :param second: (optional) the second, Defaults to 0. :param microsecond: (optional) the microsecond. Defaults to 0. :param tzinfo: (optional) A timezone expression. Defaults to UTC. :param fold: (optional) 0 or 1, used to disambiguate repeated times. Defaults to 0. .. _tz-expr: Recognized timezone expressions: - A ``tzinfo`` object. - A ``str`` describing a timezone, similar to 'US/Pacific', or 'Europe/Berlin'. - A ``str`` in ISO 8601 style, as in '+07:00'. - A ``str``, one of the following: 'local', 'utc', 'UTC'. Usage:: >>> import arrow >>> arrow.Arrow(2013, 5, 5, 12, 30, 45) <Arrow [2013-05-05T12:30:45+00:00]> """ resolution: ClassVar[timedelta] = dt_datetime.resolution min: ClassVar["Arrow"] max: ClassVar["Arrow"] _ATTRS: Final[List[str]] = [ "year", "month", "day", "hour", "minute", "second", "microsecond", ] _ATTRS_PLURAL: Final[List[str]] = [f"{a}s" for a in _ATTRS] _MONTHS_PER_QUARTER: Final[int] = 3 _SECS_PER_MINUTE: Final[int] = 60 _SECS_PER_HOUR: Final[int] = 60 * 60 _SECS_PER_DAY: Final[int] = 60 * 60 * 24 _SECS_PER_WEEK: Final[int] = 60 * 60 * 24 * 7 _SECS_PER_MONTH: Final[float] = 60 * 60 * 24 * 30.5 _SECS_PER_YEAR: Final[int] = 60 * 60 * 24 * 365 _SECS_MAP: Final[Mapping[TimeFrameLiteral, float]] = { "second": 1.0, "minute": _SECS_PER_MINUTE, "hour": _SECS_PER_HOUR, "day": _SECS_PER_DAY, "week": _SECS_PER_WEEK, "month": _SECS_PER_MONTH, "year": _SECS_PER_YEAR, } _datetime: dt_datetime def __init__( self, year: int, month: int, day: int, hour: int = 0, minute: int = 0, second: int = 0, microsecond: int = 0, tzinfo: Optional[TZ_EXPR] = None, **kwargs: Any, ) -> None: if tzinfo is None: tzinfo = dateutil_tz.tzutc() # detect that tzinfo is a pytz object (issue #626) elif ( isinstance(tzinfo, dt_tzinfo) and hasattr(tzinfo, "localize") and hasattr(tzinfo, "zone") and tzinfo.zone # type: ignore[attr-defined] ): tzinfo = parser.TzinfoParser.parse(tzinfo.zone) # type: ignore[attr-defined] elif isinstance(tzinfo, str): tzinfo = parser.TzinfoParser.parse(tzinfo) fold = kwargs.get("fold", 0) self._datetime = dt_datetime( year, month, day, hour, minute, second, microsecond, tzinfo, fold=fold ) # factories: single object, both original and from datetime. @classmethod def now(cls, tzinfo: Optional[dt_tzinfo] = None) -> "Arrow": """Constructs an :class:`Arrow <arrow.arrow.Arrow>` object, representing "now" in the given timezone. :param tzinfo: (optional) a ``tzinfo`` object. Defaults to local time. Usage:: >>> arrow.now('Asia/Baku') <Arrow [2019-01-24T20:26:31.146412+04:00]> """ if tzinfo is None: tzinfo = dateutil_tz.tzlocal() dt = dt_datetime.now(tzinfo) return cls( dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, dt.tzinfo, fold=getattr(dt, "fold", 0), ) @classmethod def utcnow(cls) -> "Arrow": """Constructs an :class:`Arrow <arrow.arrow.Arrow>` object, representing "now" in UTC time. Usage:: >>> arrow.utcnow() <Arrow [2019-01-24T16:31:40.651108+00:00]> """ dt = dt_datetime.now(dateutil_tz.tzutc()) return cls( dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, dt.tzinfo, fold=getattr(dt, "fold", 0), ) @classmethod def fromtimestamp( cls, timestamp: Union[int, float, str], tzinfo: Optional[TZ_EXPR] = None, ) -> "Arrow": """Constructs an :class:`Arrow <arrow.arrow.Arrow>` object from a timestamp, converted to the given timezone. :param timestamp: an ``int`` or ``float`` timestamp, or a ``str`` that converts to either. :param tzinfo: (optional) a ``tzinfo`` object. Defaults to local time. """ if tzinfo is None: tzinfo = dateutil_tz.tzlocal() elif isinstance(tzinfo, str): tzinfo = parser.TzinfoParser.parse(tzinfo) if not util.is_timestamp(timestamp): raise ValueError(f"The provided timestamp {timestamp!r} is invalid.") timestamp = util.normalize_timestamp(float(timestamp)) dt = dt_datetime.fromtimestamp(timestamp, tzinfo) return cls( dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, dt.tzinfo, fold=getattr(dt, "fold", 0), ) @classmethod def utcfromtimestamp(cls, timestamp: Union[int, float, str]) -> "Arrow": """Constructs an :class:`Arrow <arrow.arrow.Arrow>` object from a timestamp, in UTC time. :param timestamp: an ``int`` or ``float`` timestamp, or a ``str`` that converts to either. """ if not util.is_timestamp(timestamp): raise ValueError(f"The provided timestamp {timestamp!r} is invalid.") timestamp = util.normalize_timestamp(float(timestamp)) dt = dt_datetime.utcfromtimestamp(timestamp) return cls( dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, dateutil_tz.tzutc(), fold=getattr(dt, "fold", 0), ) @classmethod def fromdatetime(cls, dt: dt_datetime, tzinfo: Optional[TZ_EXPR] = None) -> "Arrow": """Constructs an :class:`Arrow <arrow.arrow.Arrow>` object from a ``datetime`` and optional replacement timezone. :param dt: the ``datetime`` :param tzinfo: (optional) A :ref:`timezone expression <tz-expr>`. Defaults to ``dt``'s timezone, or UTC if naive. If you only want to replace the timezone of naive datetimes:: >>> dt datetime.datetime(2013, 5, 5, 0, 0, tzinfo=tzutc()) >>> arrow.Arrow.fromdatetime(dt, dt.tzinfo or 'US/Pacific') <Arrow [2013-05-05T00:00:00+00:00]> """ try: if dt.tzinfo is None: tzinfo = dateutil_tz.tzutc() else: tzinfo = dt.tzinfo except: tzinfo = dateutil_tz.tzutc() try: return cls( dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, tzinfo, fold=getattr(dt, "fold", 0), ) except: return cls( 1980, 1, 1, 0, 0, 0, 0, tzinfo, fold=0, ) @classmethod def fromdate(cls, date: date, tzinfo: Optional[TZ_EXPR] = None) -> "Arrow": """Constructs an :class:`Arrow <arrow.arrow.Arrow>` object from a ``date`` and optional replacement timezone. Time values are set to 0. :param date: the ``date`` :param tzinfo: (optional) A :ref:`timezone expression <tz-expr>`. Defaults to UTC. """ if tzinfo is None: tzinfo = dateutil_tz.tzutc() return cls(date.year, date.month, date.day, tzinfo=tzinfo) @classmethod def strptime( cls, date_str: str, fmt: str, tzinfo: Optional[TZ_EXPR] = None ) -> "Arrow": """Constructs an :class:`Arrow <arrow.arrow.Arrow>` object from a date string and format, in the style of ``datetime.strptime``. Optionally replaces the parsed timezone. :param date_str: the date string. :param fmt: the format string. :param tzinfo: (optional) A :ref:`timezone expression <tz-expr>`. Defaults to the parsed timezone if ``fmt`` contains a timezone directive, otherwise UTC. Usage:: >>> arrow.Arrow.strptime('20-01-2019 15:49:10', '%d-%m-%Y %H:%M:%S') <Arrow [2019-01-20T15:49:10+00:00]> """ dt = dt_datetime.strptime(date_str, fmt) if tzinfo is None: tzinfo = dt.tzinfo return cls( dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, tzinfo, fold=getattr(dt, "fold", 0), ) @classmethod def fromordinal(cls, ordinal: int) -> "Arrow": """Constructs an :class:`Arrow <arrow.arrow.Arrow>` object corresponding to the Gregorian Ordinal. :param ordinal: an ``int`` corresponding to a Gregorian Ordinal. Usage:: >>> arrow.fromordinal(737741) <Arrow [2020-11-12T00:00:00+00:00]> """ util.validate_ordinal(ordinal) dt = dt_datetime.fromordinal(ordinal) return cls( dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, dt.tzinfo, fold=getattr(dt, "fold", 0), ) # factories: ranges and spans @classmethod def range( cls, frame: _T_FRAMES, start: Union["Arrow", dt_datetime], end: Union["Arrow", dt_datetime, None] = None, tz: Optional[TZ_EXPR] = None, limit: Optional[int] = None, ) -> Generator["Arrow", None, None]: """Returns an iterator of :class:`Arrow <arrow.arrow.Arrow>` objects, representing points in time between two inputs. :param frame: The timeframe. Can be any ``datetime`` property (day, hour, minute...). :param start: A datetime expression, the start of the range. :param end: (optional) A datetime expression, the end of the range. :param tz: (optional) A :ref:`timezone expression <tz-expr>`. Defaults to ``start``'s timezone, or UTC if ``start`` is naive. :param limit: (optional) A maximum number of tuples to return. **NOTE**: The ``end`` or ``limit`` must be provided. Call with ``end`` alone to return the entire range. Call with ``limit`` alone to return a maximum # of results from the start. Call with both to cap a range at a maximum # of results. **NOTE**: ``tz`` internally **replaces** the timezones of both ``start`` and ``end`` before iterating. As such, either call with naive objects and ``tz``, or aware objects from the same timezone and no ``tz``. Supported frame values: year, quarter, month, week, day, hour, minute, second. Recognized datetime expressions: - An :class:`Arrow <arrow.arrow.Arrow>` object. - A ``datetime`` object. Usage:: >>> start = datetime(2013, 5, 5, 12, 30) >>> end = datetime(2013, 5, 5, 17, 15) >>> for r in arrow.Arrow.range('hour', start, end): ... print(repr(r)) ... <Arrow [2013-05-05T12:30:00+00:00]> <Arrow [2013-05-05T13:30:00+00:00]> <Arrow [2013-05-05T14:30:00+00:00]> <Arrow [2013-05-05T15:30:00+00:00]> <Arrow [2013-05-05T16:30:00+00:00]> **NOTE**: Unlike Python's ``range``, ``end`` *may* be included in the returned iterator:: >>> start = datetime(2013, 5, 5, 12, 30) >>> end = datetime(2013, 5, 5, 13, 30) >>> for r in arrow.Arrow.range('hour', start, end): ... print(repr(r)) ... <Arrow [2013-05-05T12:30:00+00:00]> <Arrow [2013-05-05T13:30:00+00:00]> """ _, frame_relative, relative_steps = cls._get_frames(frame) tzinfo = cls._get_tzinfo(start.tzinfo if tz is None else tz) start = cls._get_datetime(start).replace(tzinfo=tzinfo) end, limit = cls._get_iteration_params(end, limit) end = cls._get_datetime(end).replace(tzinfo=tzinfo) current = cls.fromdatetime(start) original_day = start.day day_is_clipped = False i = 0 while current <= end and i < limit: i += 1 yield current values = [getattr(current, f) for f in cls._ATTRS] current = cls(*values, tzinfo=tzinfo).shift( # type: ignore **{frame_relative: relative_steps} ) if frame in ["month", "quarter", "year"] and current.day < original_day: day_is_clipped = True if day_is_clipped and not cls._is_last_day_of_month(current): current = current.replace(day=original_day) def span( self, frame: _T_FRAMES, count: int = 1, bounds: _BOUNDS = "[)", exact: bool = False, ) -> Tuple["Arrow", "Arrow"]: """Returns two new :class:`Arrow <arrow.arrow.Arrow>` objects, representing the timespan of the :class:`Arrow <arrow.arrow.Arrow>` object in a given timeframe. :param frame: the timeframe. Can be any ``datetime`` property (day, hour, minute...). :param count: (optional) the number of frames to span. :param bounds: (optional) a ``str`` of either '()', '(]', '[)', or '[]' that specifies whether to include or exclude the start and end values in the span. '(' excludes the start, '[' includes the start, ')' excludes the end, and ']' includes the end. If the bounds are not specified, the default bound '[)' is used. :param exact: (optional) whether to have the start of the timespan begin exactly at the time specified by ``start`` and the end of the timespan truncated so as not to extend beyond ``end``. Supported frame values: year, quarter, month, week, day, hour, minute, second. Usage:: >>> arrow.utcnow() <Arrow [2013-05-09T03:32:36.186203+00:00]> >>> arrow.utcnow().span('hour') (<Arrow [2013-05-09T03:00:00+00:00]>, <Arrow [2013-05-09T03:59:59.999999+00:00]>) >>> arrow.utcnow().span('day') (<Arrow [2013-05-09T00:00:00+00:00]>, <Arrow [2013-05-09T23:59:59.999999+00:00]>) >>> arrow.utcnow().span('day', count=2) (<Arrow [2013-05-09T00:00:00+00:00]>, <Arrow [2013-05-10T23:59:59.999999+00:00]>) >>> arrow.utcnow().span('day', bounds='[]') (<Arrow [2013-05-09T00:00:00+00:00]>, <Arrow [2013-05-10T00:00:00+00:00]>) """ util.validate_bounds(bounds) frame_absolute, frame_relative, relative_steps = self._get_frames(frame) if frame_absolute == "week": attr = "day" elif frame_absolute == "quarter": attr = "month" else: attr = frame_absolute floor = self if not exact: index = self._ATTRS.index(attr) frames = self._ATTRS[: index + 1] values = [getattr(self, f) for f in frames] for _ in range(3 - len(values)): values.append(1) floor = self.__class__(*values, tzinfo=self.tzinfo) # type: ignore if frame_absolute == "week": floor = floor.shift(days=-(self.isoweekday() - 1)) elif frame_absolute == "quarter": floor = floor.shift(months=-((self.month - 1) % 3)) ceil = floor.shift(**{frame_relative: count * relative_steps}) if bounds[0] == "(": floor = floor.shift(microseconds=+1) if bounds[1] == ")": ceil = ceil.shift(microseconds=-1) return floor, ceil def floor(self, frame: _T_FRAMES) -> "Arrow": """Returns a new :class:`Arrow <arrow.arrow.Arrow>` object, representing the "floor" of the timespan of the :class:`Arrow <arrow.arrow.Arrow>` object in a given timeframe. Equivalent to the first element in the 2-tuple returned by :func:`span <arrow.arrow.Arrow.span>`. :param frame: the timeframe. Can be any ``datetime`` property (day, hour, minute...). Usage:: >>> arrow.utcnow().floor('hour') <Arrow [2013-05-09T03:00:00+00:00]> """ return self.span(frame)[0] def ceil(self, frame: _T_FRAMES) -> "Arrow": """Returns a new :class:`Arrow <arrow.arrow.Arrow>` object, representing the "ceiling" of the timespan of the :class:`Arrow <arrow.arrow.Arrow>` object in a given timeframe. Equivalent to the second element in the 2-tuple returned by :func:`span <arrow.arrow.Arrow.span>`. :param frame: the timeframe. Can be any ``datetime`` property (day, hour, minute...). Usage:: >>> arrow.utcnow().ceil('hour') <Arrow [2013-05-09T03:59:59.999999+00:00]> """ return self.span(frame)[1] @classmethod def span_range( cls, frame: _T_FRAMES, start: dt_datetime, end: dt_datetime, tz: Optional[TZ_EXPR] = None, limit: Optional[int] = None, bounds: _BOUNDS = "[)", exact: bool = False, ) -> Iterable[Tuple["Arrow", "Arrow"]]: """Returns an iterator of tuples, each :class:`Arrow <arrow.arrow.Arrow>` objects, representing a series of timespans between two inputs. :param frame: The timeframe. Can be any ``datetime`` property (day, hour, minute...). :param start: A datetime expression, the start of the range. :param end: (optional) A datetime expression, the end of the range. :param tz: (optional) A :ref:`timezone expression <tz-expr>`. Defaults to ``start``'s timezone, or UTC if ``start`` is naive. :param limit: (optional) A maximum number of tuples to return. :param bounds: (optional) a ``str`` of either '()', '(]', '[)', or '[]' that specifies whether to include or exclude the start and end values in each span in the range. '(' excludes the start, '[' includes the start, ')' excludes the end, and ']' includes the end. If the bounds are not specified, the default bound '[)' is used. :param exact: (optional) whether to have the first timespan start exactly at the time specified by ``start`` and the final span truncated so as not to extend beyond ``end``. **NOTE**: The ``end`` or ``limit`` must be provided. Call with ``end`` alone to return the entire range. Call with ``limit`` alone to return a maximum # of results from the start. Call with both to cap a range at a maximum # of results. **NOTE**: ``tz`` internally **replaces** the timezones of both ``start`` and ``end`` before iterating. As such, either call with naive objects and ``tz``, or aware objects from the same timezone and no ``tz``. Supported frame values: year, quarter, month, week, day, hour, minute, second. Recognized datetime expressions: - An :class:`Arrow <arrow.arrow.Arrow>` object. - A ``datetime`` object. **NOTE**: Unlike Python's ``range``, ``end`` will *always* be included in the returned iterator of timespans. Usage: >>> start = datetime(2013, 5, 5, 12, 30) >>> end = datetime(2013, 5, 5, 17, 15) >>> for r in arrow.Arrow.span_range('hour', start, end): ... print(r) ... (<Arrow [2013-05-05T12:00:00+00:00]>, <Arrow [2013-05-05T12:59:59.999999+00:00]>) (<Arrow [2013-05-05T13:00:00+00:00]>, <Arrow [2013-05-05T13:59:59.999999+00:00]>) (<Arrow [2013-05-05T14:00:00+00:00]>, <Arrow [2013-05-05T14:59:59.999999+00:00]>) (<Arrow [2013-05-05T15:00:00+00:00]>, <Arrow [2013-05-05T15:59:59.999999+00:00]>) (<Arrow [2013-05-05T16:00:00+00:00]>, <Arrow [2013-05-05T16:59:59.999999+00:00]>) (<Arrow [2013-05-05T17:00:00+00:00]>, <Arrow [2013-05-05T17:59:59.999999+00:00]>) """ tzinfo = cls._get_tzinfo(start.tzinfo if tz is None else tz) start = cls.fromdatetime(start, tzinfo).span(frame, exact=exact)[0] end = cls.fromdatetime(end, tzinfo) _range = cls.range(frame, start, end, tz, limit) if not exact: for r in _range: yield r.span(frame, bounds=bounds, exact=exact) for r in _range: floor, ceil = r.span(frame, bounds=bounds, exact=exact) if ceil > end: ceil = end if bounds[1] == ")": ceil += relativedelta(microseconds=-1) if floor == end: break elif floor + relativedelta(microseconds=-1) == end: break yield floor, ceil @classmethod def interval( cls, frame: _T_FRAMES, start: dt_datetime, end: dt_datetime, interval: int = 1, tz: Optional[TZ_EXPR] = None, bounds: _BOUNDS = "[)", exact: bool = False, ) -> Iterable[Tuple["Arrow", "Arrow"]]: """Returns an iterator of tuples, each :class:`Arrow <arrow.arrow.Arrow>` objects, representing a series of intervals between two inputs. :param frame: The timeframe. Can be any ``datetime`` property (day, hour, minute...). :param start: A datetime expression, the start of the range. :param end: (optional) A datetime expression, the end of the range. :param interval: (optional) Time interval for the given time frame. :param tz: (optional) A timezone expression. Defaults to UTC. :param bounds: (optional) a ``str`` of either '()', '(]', '[)', or '[]' that specifies whether to include or exclude the start and end values in the intervals. '(' excludes the start, '[' includes the start, ')' excludes the end, and ']' includes the end. If the bounds are not specified, the default bound '[)' is used. :param exact: (optional) whether to have the first timespan start exactly at the time specified by ``start`` and the final interval truncated so as not to extend beyond ``end``. Supported frame values: year, quarter, month, week, day, hour, minute, second Recognized datetime expressions: - An :class:`Arrow <arrow.arrow.Arrow>` object. - A ``datetime`` object. Recognized timezone expressions: - A ``tzinfo`` object. - A ``str`` describing a timezone, similar to 'US/Pacific', or 'Europe/Berlin'. - A ``str`` in ISO 8601 style, as in '+07:00'. - A ``str``, one of the following: 'local', 'utc', 'UTC'. Usage: >>> start = datetime(2013, 5, 5, 12, 30) >>> end = datetime(2013, 5, 5, 17, 15) >>> for r in arrow.Arrow.interval('hour', start, end, 2): ... print r ... (<Arrow [2013-05-05T12:00:00+00:00]>, <Arrow [2013-05-05T13:59:59.999999+00:00]>) (<Arrow [2013-05-05T14:00:00+00:00]>, <Arrow [2013-05-05T15:59:59.999999+00:00]>) (<Arrow [2013-05-05T16:00:00+00:00]>, <Arrow [2013-05-05T17:59:59.999999+00:0]>) """ if interval < 1: raise ValueError("interval has to be a positive integer") spanRange = iter( cls.span_range(frame, start, end, tz, bounds=bounds, exact=exact) ) while True: try: intvlStart, intvlEnd = next(spanRange) for _ in range(interval - 1): try: _, intvlEnd = next(spanRange) except StopIteration: continue yield intvlStart, intvlEnd except StopIteration: return # representations def __repr__(self) -> str: return f"<{self.__class__.__name__} [{self.__str__()}]>" def __str__(self) -> str: return self._datetime.isoformat() def __format__(self, formatstr: str) -> str: if len(formatstr) > 0: return self.format(formatstr) return str(self) def __hash__(self) -> int: return self._datetime.__hash__() # attributes and properties def __getattr__(self, name: str) -> int: if name == "week": return self.isocalendar()[1] if name == "quarter": return int((self.month - 1) / self._MONTHS_PER_QUARTER) + 1 if not name.startswith("_"): value: Optional[int] = getattr(self._datetime, name, None) if value is not None: return value return cast(int, object.__getattribute__(self, name)) @property def tzinfo(self) -> dt_tzinfo: """Gets the ``tzinfo`` of the :class:`Arrow <arrow.arrow.Arrow>` object. Usage:: >>> arw=arrow.utcnow() >>> arw.tzinfo tzutc() """ # In Arrow, `_datetime` cannot be naive. return cast(dt_tzinfo, self._datetime.tzinfo) @property def datetime(self) -> dt_datetime: """Returns a datetime representation of the :class:`Arrow <arrow.arrow.Arrow>` object. Usage:: >>> arw=arrow.utcnow() >>> arw.datetime datetime.datetime(2019, 1, 24, 16, 35, 27, 276649, tzinfo=tzutc()) """ return self._datetime @property def naive(self) -> dt_datetime: """Returns a naive datetime representation of the :class:`Arrow <arrow.arrow.Arrow>` object. Usage:: >>> nairobi = arrow.now('Africa/Nairobi') >>> nairobi <Arrow [2019-01-23T19:27:12.297999+03:00]> >>> nairobi.naive datetime.datetime(2019, 1, 23, 19, 27, 12, 297999) """ return self._datetime.replace(tzinfo=None) def timestamp(self) -> float: """Returns a timestamp representation of the :class:`Arrow <arrow.arrow.Arrow>` object, in UTC time. Usage:: >>> arrow.utcnow().timestamp 1548260567 """ return self._datetime.timestamp() @property def int_timestamp(self) -> int: """Returns a timestamp representation of the :class:`Arrow <arrow.arrow.Arrow>` object, in UTC time. Usage:: >>> arrow.utcnow().int_timestamp 1548260567 """ return int(self.timestamp()) @property def float_timestamp(self) -> float: """Returns a floating-point representation of the :class:`Arrow <arrow.arrow.Arrow>` object, in UTC time. Usage:: >>> arrow.utcnow().float_timestamp 1548260516.830896 """ return self.timestamp() @property def fold(self) -> int: """ Returns the ``fold`` value of the :class:`Arrow <arrow.arrow.Arrow>` object. """ return self._datetime.fold @property def ambiguous(self) -> bool: """ Returns a boolean indicating whether the :class:`Arrow <arrow.arrow.Arrow>` object is ambiguous.""" return dateutil_tz.datetime_ambiguous(self._datetime) @property def imaginary(self) -> bool: """Indicates whether the :class: `Arrow <arrow.arrow.Arrow>` object exists in the current timezone.""" return not dateutil_tz.datetime_exists(self._datetime) # mutation and duplication. def clone(self) -> "Arrow": """Returns a new :class:`Arrow <arrow.arrow.Arrow>` object, cloned from the current one. Usage: >>> arw = arrow.utcnow() >>> cloned = arw.clone() """ return self.fromdatetime(self._datetime) def replace(self, **kwargs: Any) -> "Arrow": """Returns a new :class:`Arrow <arrow.arrow.Arrow>` object with attributes updated according to inputs. Use property names to set their value absolutely:: >>> import arrow >>> arw = arrow.utcnow() >>> arw <Arrow [2013-05-11T22:27:34.787885+00:00]> >>> arw.replace(year=2014, month=6) <Arrow [2014-06-11T22:27:34.787885+00:00]> You can also replace the timezone without conversion, using a :ref:`timezone expression <tz-expr>`:: >>> arw.replace(tzinfo=tz.tzlocal()) <Arrow [2013-05-11T22:27:34.787885-07:00]> """ absolute_kwargs = {} for key, value in kwargs.items(): if key in self._ATTRS: absolute_kwargs[key] = value elif key in ["week", "quarter"]: raise ValueError(f"Setting absolute {key} is not supported.") elif key not in ["tzinfo", "fold"]: raise ValueError(f"Unknown attribute: {key!r}.") current = self._datetime.replace(**absolute_kwargs) tzinfo = kwargs.get("tzinfo") if tzinfo is not None: tzinfo = self._get_tzinfo(tzinfo) current = current.replace(tzinfo=tzinfo) fold = kwargs.get("fold") if fold is not None: current = current.replace(fold=fold) return self.fromdatetime(current) def shift(self, **kwargs: Any) -> "Arrow": """Returns a new :class:`Arrow <arrow.arrow.Arrow>` object with attributes updated according to inputs. Use pluralized property names to relatively shift their current value: >>> import arrow >>> arw = arrow.utcnow() >>> arw <Arrow [2013-05-11T22:27:34.787885+00:00]> >>> arw.shift(years=1, months=-1) <Arrow [2014-04-11T22:27:34.787885+00:00]> Day-of-the-week relative shifting can use either Python's weekday numbers (Monday = 0, Tuesday = 1 .. Sunday = 6) or using dateutil.relativedelta's day instances (MO, TU .. SU). When using weekday numbers, the returned date will always be greater than or equal to the starting date. Using the above code (which is a Saturday) and asking it to shift to Saturday: >>> arw.shift(weekday=5) <Arrow [2013-05-11T22:27:34.787885+00:00]> While asking for a Monday: >>> arw.shift(weekday=0) <Arrow [2013-05-13T22:27:34.787885+00:00]> """ relative_kwargs = {} additional_attrs = ["weeks", "quarters", "weekday"] for key, value in kwargs.items(): if key in self._ATTRS_PLURAL or key in additional_attrs: relative_kwargs[key] = value else: supported_attr = ", ".join(self._ATTRS_PLURAL + additional_attrs) raise ValueError( f"Invalid shift time frame. Please select one of the following: {supported_attr}." ) # core datetime does not support quarters, translate to months. relative_kwargs.setdefault("months", 0) relative_kwargs["months"] += ( relative_kwargs.pop("quarters", 0) * self._MONTHS_PER_QUARTER ) current = self._datetime + relativedelta(**relative_kwargs) if not dateutil_tz.datetime_exists(current): current = dateutil_tz.resolve_imaginary(current) return self.fromdatetime(current) def to(self, tz: TZ_EXPR) -> "Arrow": """Returns a new :class:`Arrow <arrow.arrow.Arrow>` object, converted to the target timezone. :param tz: A :ref:`timezone expression <tz-expr>`. Usage:: >>> utc = arrow.utcnow() >>> utc <Arrow [2013-05-09T03:49:12.311072+00:00]> >>> utc.to('US/Pacific') <Arrow [2013-05-08T20:49:12.311072-07:00]> >>> utc.to(tz.tzlocal()) <Arrow [2013-05-08T20:49:12.311072-07:00]> >>> utc.to('-07:00') <Arrow [2013-05-08T20:49:12.311072-07:00]> >>> utc.to('local') <Arrow [2013-05-08T20:49:12.311072-07:00]> >>> utc.to('local').to('utc') <Arrow [2013-05-09T03:49:12.311072+00:00]> """ if not isinstance(tz, dt_tzinfo): tz = parser.TzinfoParser.parse(tz) dt = self._datetime.astimezone(tz) return self.__class__( dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, dt.tzinfo, fold=getattr(dt, "fold", 0), ) # string output and formatting def format(self, fmt: str = "YYYY-MM-DD HH:mm:ssZZ", locale: str = "en_us") -> str: """Returns a string representation of the :class:`Arrow <arrow.arrow.Arrow>` object, formatted according to a format string. :param fmt: the format string. :param locale: the locale to format. Usage:: >>> arrow.utcnow().format('YYYY-MM-DD HH:mm:ss ZZ') '2013-05-09 03:56:47 -00:00' >>> arrow.utcnow().format('X') '1368071882' >>> arrow.utcnow().format('MMMM DD, YYYY') 'May 09, 2013' >>> arrow.utcnow().format() '2013-05-09 03:56:47 -00:00' """ return formatter.DateTimeFormatter(locale).format(self._datetime, fmt) def humanize( self, other: Union["Arrow", dt_datetime, None] = None, locale: str = "en_us", only_distance: bool = False, granularity: Union[_GRANULARITY, List[_GRANULARITY]] = "auto", ) -> str: """Returns a localized, humanized representation of a relative difference in time. :param other: (optional) an :class:`Arrow <arrow.arrow.Arrow>` or ``datetime`` object. Defaults to now in the current :class:`Arrow <arrow.arrow.Arrow>` object's timezone. :param locale: (optional) a ``str`` specifying a locale. Defaults to 'en_us'. :param only_distance: (optional) returns only time difference eg: "11 seconds" without "in" or "ago" part. :param granularity: (optional) defines the precision of the output. Set it to strings 'second', 'minute', 'hour', 'day', 'week', 'month' or 'year' or a list of any combination of these strings Usage:: >>> earlier = arrow.utcnow().shift(hours=-2) >>> earlier.humanize() '2 hours ago' >>> later = earlier.shift(hours=4) >>> later.humanize(earlier) 'in 4 hours' """ locale_name = locale locale = locales.get_locale(locale) if other is None: utc = dt_datetime.utcnow().replace(tzinfo=dateutil_tz.tzutc()) dt = utc.astimezone(self._datetime.tzinfo) elif isinstance(other, Arrow): dt = other._datetime elif isinstance(other, dt_datetime): if other.tzinfo is None: dt = other.replace(tzinfo=self._datetime.tzinfo) else: dt = other.astimezone(self._datetime.tzinfo) else: raise TypeError( f"Invalid 'other' argument of type {type(other).__name__!r}. " "Argument must be of type None, Arrow, or datetime." ) if isinstance(granularity, list) and len(granularity) == 1: granularity = granularity[0] _delta = int(round((self._datetime - dt).total_seconds())) sign = -1 if _delta < 0 else 1 delta_second = diff = abs(_delta) try: if granularity == "auto": if diff < 10: return locale.describe("now", only_distance=only_distance) if diff < self._SECS_PER_MINUTE: seconds = sign * delta_second return locale.describe( "seconds", seconds, only_distance=only_distance ) elif diff < self._SECS_PER_MINUTE * 2: return locale.describe("minute", sign, only_distance=only_distance) elif diff < self._SECS_PER_HOUR: minutes = sign * max(delta_second // self._SECS_PER_MINUTE, 2) return locale.describe( "minutes", minutes, only_distance=only_distance ) elif diff < self._SECS_PER_HOUR * 2: return locale.describe("hour", sign, only_distance=only_distance) elif diff < self._SECS_PER_DAY: hours = sign * max(delta_second // self._SECS_PER_HOUR, 2) return locale.describe("hours", hours, only_distance=only_distance) elif diff < self._SECS_PER_DAY * 2: return locale.describe("day", sign, only_distance=only_distance) elif diff < self._SECS_PER_WEEK: days = sign * max(delta_second // self._SECS_PER_DAY, 2) return locale.describe("days", days, only_distance=only_distance) elif diff < self._SECS_PER_WEEK * 2: return locale.describe("week", sign, only_distance=only_distance) elif diff < self._SECS_PER_MONTH: weeks = sign * max(delta_second // self._SECS_PER_WEEK, 2) return locale.describe("weeks", weeks, only_distance=only_distance) elif diff < self._SECS_PER_MONTH * 2: return locale.describe("month", sign, only_distance=only_distance) elif diff < self._SECS_PER_YEAR: # TODO revisit for humanization during leap years self_months = self._datetime.year * 12 + self._datetime.month other_months = dt.year * 12 + dt.month months = sign * max(abs(other_months - self_months), 2) return locale.describe( "months", months, only_distance=only_distance ) elif diff < self._SECS_PER_YEAR * 2: return locale.describe("year", sign, only_distance=only_distance) else: years = sign * max(delta_second // self._SECS_PER_YEAR, 2) return locale.describe("years", years, only_distance=only_distance) elif isinstance(granularity, str): granularity = cast(TimeFrameLiteral, granularity) # type: ignore[assignment] if granularity == "second": delta = sign * float(delta_second) if abs(delta) < 2: return locale.describe("now", only_distance=only_distance) elif granularity == "minute": delta = sign * delta_second / self._SECS_PER_MINUTE elif granularity == "hour": delta = sign * delta_second / self._SECS_PER_HOUR elif granularity == "day": delta = sign * delta_second / self._SECS_PER_DAY elif granularity == "week": delta = sign * delta_second / self._SECS_PER_WEEK elif granularity == "month": delta = sign * delta_second / self._SECS_PER_MONTH elif granularity == "year": delta = sign * delta_second / self._SECS_PER_YEAR else: raise ValueError( "Invalid level of granularity. " "Please select between 'second', 'minute', 'hour', 'day', 'week', 'month' or 'year'." ) if trunc(abs(delta)) != 1: granularity += "s" # type: ignore return locale.describe(granularity, delta, only_distance=only_distance) else: timeframes: List[Tuple[TimeFrameLiteral, float]] = [] def gather_timeframes(_delta: float, _frame: TimeFrameLiteral) -> float: if _frame in granularity: value = sign * _delta / self._SECS_MAP[_frame] _delta %= self._SECS_MAP[_frame] if trunc(abs(value)) != 1: timeframes.append( (cast(TimeFrameLiteral, _frame + "s"), value) ) else: timeframes.append((_frame, value)) return _delta delta = float(delta_second) frames: Tuple[TimeFrameLiteral, ...] = ( "year", "month", "week", "day", "hour", "minute", "second", ) for frame in frames: delta = gather_timeframes(delta, frame) if len(timeframes) < len(granularity): raise ValueError( "Invalid level of granularity. " "Please select between 'second', 'minute', 'hour', 'day', 'week', 'month' or 'year'." ) return locale.describe_multi(timeframes, only_distance=only_distance) except KeyError as e: raise ValueError( f"Humanization of the {e} granularity is not currently translated in the {locale_name!r} locale. " "Please consider making a contribution to this locale." ) # query functions def is_between( self, start: "Arrow", end: "Arrow", bounds: _BOUNDS = "()", ) -> bool: """Returns a boolean denoting whether the specified date and time is between the start and end dates and times. :param start: an :class:`Arrow <arrow.arrow.Arrow>` object. :param end: an :class:`Arrow <arrow.arrow.Arrow>` object. :param bounds: (optional) a ``str`` of either '()', '(]', '[)', or '[]' that specifies whether to include or exclude the start and end values in the range. '(' excludes the start, '[' includes the start, ')' excludes the end, and ']' includes the end. If the bounds are not specified, the default bound '()' is used. Usage:: >>> start = arrow.get(datetime(2013, 5, 5, 12, 30, 10)) >>> end = arrow.get(datetime(2013, 5, 5, 12, 30, 36)) >>> arrow.get(datetime(2013, 5, 5, 12, 30, 27)).is_between(start, end) True >>> start = arrow.get(datetime(2013, 5, 5)) >>> end = arrow.get(datetime(2013, 5, 8)) >>> arrow.get(datetime(2013, 5, 8)).is_between(start, end, '[]') True >>> start = arrow.get(datetime(2013, 5, 5)) >>> end = arrow.get(datetime(2013, 5, 8)) >>> arrow.get(datetime(2013, 5, 8)).is_between(start, end, '[)') False """ util.validate_bounds(bounds) if not isinstance(start, Arrow): raise TypeError( f"Cannot parse start date argument type of {type(start)!r}." ) if not isinstance(end, Arrow): raise TypeError(f"Cannot parse end date argument type of {type(start)!r}.") include_start = bounds[0] == "[" include_end = bounds[1] == "]" target_ts = self.float_timestamp start_ts = start.float_timestamp end_ts = end.float_timestamp return ( (start_ts <= target_ts <= end_ts) and (include_start or start_ts < target_ts) and (include_end or target_ts < end_ts) ) # datetime methods def date(self) -> date: """Returns a ``date`` object with the same year, month and day. Usage:: >>> arrow.utcnow().date() datetime.date(2019, 1, 23) """ return self._datetime.date() def time(self) -> dt_time: """Returns a ``time`` object with the same hour, minute, second, microsecond. Usage:: >>> arrow.utcnow().time() datetime.time(12, 15, 34, 68352) """ return self._datetime.time() def timetz(self) -> dt_time: """Returns a ``time`` object with the same hour, minute, second, microsecond and tzinfo. Usage:: >>> arrow.utcnow().timetz() datetime.time(12, 5, 18, 298893, tzinfo=tzutc()) """ return self._datetime.timetz() def astimezone(self, tz: Optional[dt_tzinfo]) -> dt_datetime: """Returns a ``datetime`` object, converted to the specified timezone. :param tz: a ``tzinfo`` object. Usage:: >>> pacific=arrow.now('US/Pacific') >>> nyc=arrow.now('America/New_York').tzinfo >>> pacific.astimezone(nyc) datetime.datetime(2019, 1, 20, 10, 24, 22, 328172, tzinfo=tzfile('/usr/share/zoneinfo/America/New_York')) """ return self._datetime.astimezone(tz) def utcoffset(self) -> Optional[timedelta]: """Returns a ``timedelta`` object representing the whole number of minutes difference from UTC time. Usage:: >>> arrow.now('US/Pacific').utcoffset() datetime.timedelta(-1, 57600) """ return self._datetime.utcoffset() def dst(self) -> Optional[timedelta]: """Returns the daylight savings time adjustment. Usage:: >>> arrow.utcnow().dst() datetime.timedelta(0) """ return self._datetime.dst() def timetuple(self) -> struct_time: """Returns a ``time.struct_time``, in the current timezone. Usage:: >>> arrow.utcnow().timetuple() time.struct_time(tm_year=2019, tm_mon=1, tm_mday=20, tm_hour=15, tm_min=17, tm_sec=8, tm_wday=6, tm_yday=20, tm_isdst=0) """ return self._datetime.timetuple() def utctimetuple(self) -> struct_time: """Returns a ``time.struct_time``, in UTC time. Usage:: >>> arrow.utcnow().utctimetuple() time.struct_time(tm_year=2019, tm_mon=1, tm_mday=19, tm_hour=21, tm_min=41, tm_sec=7, tm_wday=5, tm_yday=19, tm_isdst=0) """ return self._datetime.utctimetuple() def toordinal(self) -> int: """Returns the proleptic Gregorian ordinal of the date. Usage:: >>> arrow.utcnow().toordinal() 737078 """ return self._datetime.toordinal() def weekday(self) -> int: """Returns the day of the week as an integer (0-6). Usage:: >>> arrow.utcnow().weekday() 5 """ return self._datetime.weekday() def isoweekday(self) -> int: """Returns the ISO day of the week as an integer (1-7). Usage:: >>> arrow.utcnow().isoweekday() 6 """ return self._datetime.isoweekday() def isocalendar(self) -> Tuple[int, int, int]: """Returns a 3-tuple, (ISO year, ISO week number, ISO weekday). Usage:: >>> arrow.utcnow().isocalendar() (2019, 3, 6) """ return self._datetime.isocalendar() def isoformat(self, sep: str = "T", timespec: str = "auto") -> str: """Returns an ISO 8601 formatted representation of the date and time. Usage:: >>> arrow.utcnow().isoformat() '2019-01-19T18:30:52.442118+00:00' """ return self._datetime.isoformat(sep, timespec) def ctime(self) -> str: """Returns a ctime formatted representation of the date and time. Usage:: >>> arrow.utcnow().ctime() 'Sat Jan 19 18:26:50 2019' """ return self._datetime.ctime() def strftime(self, format: str) -> str: """Formats in the style of ``datetime.strftime``. :param format: the format string. Usage:: >>> arrow.utcnow().strftime('%d-%m-%Y %H:%M:%S') '23-01-2019 12:28:17' """ return self._datetime.strftime(format) def for_json(self) -> str: """Serializes for the ``for_json`` protocol of simplejson. Usage:: >>> arrow.utcnow().for_json() '2019-01-19T18:25:36.760079+00:00' """ return self.isoformat() # math def __add__(self, other: Any) -> "Arrow": if isinstance(other, (timedelta, relativedelta)): return self.fromdatetime(self._datetime + other, self._datetime.tzinfo) return NotImplemented def __radd__(self, other: Union[timedelta, relativedelta]) -> "Arrow": return self.__add__(other) @overload def __sub__(self, other: Union[timedelta, relativedelta]) -> "Arrow": pass # pragma: no cover @overload def __sub__(self, other: Union[dt_datetime, "Arrow"]) -> timedelta: pass # pragma: no cover def __sub__(self, other: Any) -> Union[timedelta, "Arrow"]: if isinstance(other, (timedelta, relativedelta)): return self.fromdatetime(self._datetime - other, self._datetime.tzinfo) elif isinstance(other, dt_datetime): return self._datetime - other elif isinstance(other, Arrow): return self._datetime - other._datetime return NotImplemented def __rsub__(self, other: Any) -> timedelta: if isinstance(other, dt_datetime): return other - self._datetime return NotImplemented # comparisons def __eq__(self, other: Any) -> bool: if not isinstance(other, (Arrow, dt_datetime)): return False return self._datetime == self._get_datetime(other) def __ne__(self, other: Any) -> bool: if not isinstance(other, (Arrow, dt_datetime)): return True return not self.__eq__(other) def __gt__(self, other: Any) -> bool: if not isinstance(other, (Arrow, dt_datetime)): return NotImplemented return self._datetime > self._get_datetime(other) def __ge__(self, other: Any) -> bool: if not isinstance(other, (Arrow, dt_datetime)): return NotImplemented return self._datetime >= self._get_datetime(other) def __lt__(self, other: Any) -> bool: if not isinstance(other, (Arrow, dt_datetime)): return NotImplemented return self._datetime < self._get_datetime(other) def __le__(self, other: Any) -> bool: if not isinstance(other, (Arrow, dt_datetime)): return NotImplemented return self._datetime <= self._get_datetime(other) # internal methods @staticmethod def _get_tzinfo(tz_expr: Optional[TZ_EXPR]) -> dt_tzinfo: if tz_expr is None: return dateutil_tz.tzutc() if isinstance(tz_expr, dt_tzinfo): return tz_expr else: try: return parser.TzinfoParser.parse(tz_expr) except parser.ParserError: raise ValueError(f"{tz_expr!r} not recognized as a timezone.") @classmethod def _get_datetime( cls, expr: Union["Arrow", dt_datetime, int, float, str] ) -> dt_datetime: """Get datetime object for a specified expression.""" if isinstance(expr, Arrow): return expr.datetime elif isinstance(expr, dt_datetime): return expr elif util.is_timestamp(expr): timestamp = float(expr) return cls.utcfromtimestamp(timestamp).datetime else: raise ValueError(f"{expr!r} not recognized as a datetime or timestamp.") @classmethod def _get_frames(cls, name: _T_FRAMES) -> Tuple[str, str, int]: if name in cls._ATTRS: return name, f"{name}s", 1 elif name[-1] == "s" and name[:-1] in cls._ATTRS: return name[:-1], name, 1 elif name in ["week", "weeks"]: return "week", "weeks", 1 elif name in ["quarter", "quarters"]: return "quarter", "months", 3 else: supported = ", ".join( [ "year(s)", "month(s)", "day(s)", "hour(s)", "minute(s)", "second(s)", "microsecond(s)", "week(s)", "quarter(s)", ] ) raise ValueError( f"Range or span over frame {name} not supported. Supported frames: {supported}." ) @classmethod def _get_iteration_params(cls, end: Any, limit: Optional[int]) -> Tuple[Any, int]: if end is None: if limit is None: raise ValueError("One of 'end' or 'limit' is required.") return cls.max, limit else: if limit is None: return end, sys.maxsize return end, limit @staticmethod def _is_last_day_of_month(date: "Arrow") -> bool: return date.day == calendar.monthrange(date.year, date.month)[1] Arrow.min = Arrow.fromdatetime(dt_datetime.min) Arrow.max = Arrow.fromdatetime(dt_datetime.max)
32.47907
132
0.551751
import calendar import sys from datetime import date from datetime import datetime as dt_datetime from datetime import time as dt_time from datetime import timedelta from datetime import tzinfo as dt_tzinfo from math import trunc from time import struct_time from typing import ( Any, ClassVar, Generator, Iterable, List, Mapping, Optional, Tuple, Union, cast, overload, ) from dateutil import tz as dateutil_tz from dateutil.relativedelta import relativedelta from arrow import formatter, locales, parser, util from arrow.locales import TimeFrameLiteral if sys.version_info < (3, 8): from typing_extensions import Final, Literal else: from typing import Final, Literal TZ_EXPR = Union[dt_tzinfo, str] _T_FRAMES = Literal[ "year", "years", "month", "months", "day", "days", "hour", "hours", "minute", "minutes", "second", "seconds", "microsecond", "microseconds", "week", "weeks", "quarter", "quarters", ] _BOUNDS = Literal["[)", "()", "(]", "[]"] _GRANULARITY = Literal[ "auto", "second", "minute", "hour", "day", "week", "month", "year", ] class Arrow: resolution: ClassVar[timedelta] = dt_datetime.resolution min: ClassVar["Arrow"] max: ClassVar["Arrow"] _ATTRS: Final[List[str]] = [ "year", "month", "day", "hour", "minute", "second", "microsecond", ] _ATTRS_PLURAL: Final[List[str]] = [f"{a}s" for a in _ATTRS] _MONTHS_PER_QUARTER: Final[int] = 3 _SECS_PER_MINUTE: Final[int] = 60 _SECS_PER_HOUR: Final[int] = 60 * 60 _SECS_PER_DAY: Final[int] = 60 * 60 * 24 _SECS_PER_WEEK: Final[int] = 60 * 60 * 24 * 7 _SECS_PER_MONTH: Final[float] = 60 * 60 * 24 * 30.5 _SECS_PER_YEAR: Final[int] = 60 * 60 * 24 * 365 _SECS_MAP: Final[Mapping[TimeFrameLiteral, float]] = { "second": 1.0, "minute": _SECS_PER_MINUTE, "hour": _SECS_PER_HOUR, "day": _SECS_PER_DAY, "week": _SECS_PER_WEEK, "month": _SECS_PER_MONTH, "year": _SECS_PER_YEAR, } _datetime: dt_datetime def __init__( self, year: int, month: int, day: int, hour: int = 0, minute: int = 0, second: int = 0, microsecond: int = 0, tzinfo: Optional[TZ_EXPR] = None, **kwargs: Any, ) -> None: if tzinfo is None: tzinfo = dateutil_tz.tzutc() elif ( isinstance(tzinfo, dt_tzinfo) and hasattr(tzinfo, "localize") and hasattr(tzinfo, "zone") and tzinfo.zone ): tzinfo = parser.TzinfoParser.parse(tzinfo.zone) elif isinstance(tzinfo, str): tzinfo = parser.TzinfoParser.parse(tzinfo) fold = kwargs.get("fold", 0) self._datetime = dt_datetime( year, month, day, hour, minute, second, microsecond, tzinfo, fold=fold ) @classmethod def now(cls, tzinfo: Optional[dt_tzinfo] = None) -> "Arrow": if tzinfo is None: tzinfo = dateutil_tz.tzlocal() dt = dt_datetime.now(tzinfo) return cls( dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, dt.tzinfo, fold=getattr(dt, "fold", 0), ) @classmethod def utcnow(cls) -> "Arrow": dt = dt_datetime.now(dateutil_tz.tzutc()) return cls( dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, dt.tzinfo, fold=getattr(dt, "fold", 0), ) @classmethod def fromtimestamp( cls, timestamp: Union[int, float, str], tzinfo: Optional[TZ_EXPR] = None, ) -> "Arrow": if tzinfo is None: tzinfo = dateutil_tz.tzlocal() elif isinstance(tzinfo, str): tzinfo = parser.TzinfoParser.parse(tzinfo) if not util.is_timestamp(timestamp): raise ValueError(f"The provided timestamp {timestamp!r} is invalid.") timestamp = util.normalize_timestamp(float(timestamp)) dt = dt_datetime.fromtimestamp(timestamp, tzinfo) return cls( dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, dt.tzinfo, fold=getattr(dt, "fold", 0), ) @classmethod def utcfromtimestamp(cls, timestamp: Union[int, float, str]) -> "Arrow": if not util.is_timestamp(timestamp): raise ValueError(f"The provided timestamp {timestamp!r} is invalid.") timestamp = util.normalize_timestamp(float(timestamp)) dt = dt_datetime.utcfromtimestamp(timestamp) return cls( dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, dateutil_tz.tzutc(), fold=getattr(dt, "fold", 0), ) @classmethod def fromdatetime(cls, dt: dt_datetime, tzinfo: Optional[TZ_EXPR] = None) -> "Arrow": try: if dt.tzinfo is None: tzinfo = dateutil_tz.tzutc() else: tzinfo = dt.tzinfo except: tzinfo = dateutil_tz.tzutc() try: return cls( dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, tzinfo, fold=getattr(dt, "fold", 0), ) except: return cls( 1980, 1, 1, 0, 0, 0, 0, tzinfo, fold=0, ) @classmethod def fromdate(cls, date: date, tzinfo: Optional[TZ_EXPR] = None) -> "Arrow": if tzinfo is None: tzinfo = dateutil_tz.tzutc() return cls(date.year, date.month, date.day, tzinfo=tzinfo) @classmethod def strptime( cls, date_str: str, fmt: str, tzinfo: Optional[TZ_EXPR] = None ) -> "Arrow": dt = dt_datetime.strptime(date_str, fmt) if tzinfo is None: tzinfo = dt.tzinfo return cls( dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, tzinfo, fold=getattr(dt, "fold", 0), ) @classmethod def fromordinal(cls, ordinal: int) -> "Arrow": util.validate_ordinal(ordinal) dt = dt_datetime.fromordinal(ordinal) return cls( dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, dt.tzinfo, fold=getattr(dt, "fold", 0), ) @classmethod def range( cls, frame: _T_FRAMES, start: Union["Arrow", dt_datetime], end: Union["Arrow", dt_datetime, None] = None, tz: Optional[TZ_EXPR] = None, limit: Optional[int] = None, ) -> Generator["Arrow", None, None]: _, frame_relative, relative_steps = cls._get_frames(frame) tzinfo = cls._get_tzinfo(start.tzinfo if tz is None else tz) start = cls._get_datetime(start).replace(tzinfo=tzinfo) end, limit = cls._get_iteration_params(end, limit) end = cls._get_datetime(end).replace(tzinfo=tzinfo) current = cls.fromdatetime(start) original_day = start.day day_is_clipped = False i = 0 while current <= end and i < limit: i += 1 yield current values = [getattr(current, f) for f in cls._ATTRS] current = cls(*values, tzinfo=tzinfo).shift( **{frame_relative: relative_steps} ) if frame in ["month", "quarter", "year"] and current.day < original_day: day_is_clipped = True if day_is_clipped and not cls._is_last_day_of_month(current): current = current.replace(day=original_day) def span( self, frame: _T_FRAMES, count: int = 1, bounds: _BOUNDS = "[)", exact: bool = False, ) -> Tuple["Arrow", "Arrow"]: util.validate_bounds(bounds) frame_absolute, frame_relative, relative_steps = self._get_frames(frame) if frame_absolute == "week": attr = "day" elif frame_absolute == "quarter": attr = "month" else: attr = frame_absolute floor = self if not exact: index = self._ATTRS.index(attr) frames = self._ATTRS[: index + 1] values = [getattr(self, f) for f in frames] for _ in range(3 - len(values)): values.append(1) floor = self.__class__(*values, tzinfo=self.tzinfo) if frame_absolute == "week": floor = floor.shift(days=-(self.isoweekday() - 1)) elif frame_absolute == "quarter": floor = floor.shift(months=-((self.month - 1) % 3)) ceil = floor.shift(**{frame_relative: count * relative_steps}) if bounds[0] == "(": floor = floor.shift(microseconds=+1) if bounds[1] == ")": ceil = ceil.shift(microseconds=-1) return floor, ceil def floor(self, frame: _T_FRAMES) -> "Arrow": return self.span(frame)[0] def ceil(self, frame: _T_FRAMES) -> "Arrow": return self.span(frame)[1] @classmethod def span_range( cls, frame: _T_FRAMES, start: dt_datetime, end: dt_datetime, tz: Optional[TZ_EXPR] = None, limit: Optional[int] = None, bounds: _BOUNDS = "[)", exact: bool = False, ) -> Iterable[Tuple["Arrow", "Arrow"]]: tzinfo = cls._get_tzinfo(start.tzinfo if tz is None else tz) start = cls.fromdatetime(start, tzinfo).span(frame, exact=exact)[0] end = cls.fromdatetime(end, tzinfo) _range = cls.range(frame, start, end, tz, limit) if not exact: for r in _range: yield r.span(frame, bounds=bounds, exact=exact) for r in _range: floor, ceil = r.span(frame, bounds=bounds, exact=exact) if ceil > end: ceil = end if bounds[1] == ")": ceil += relativedelta(microseconds=-1) if floor == end: break elif floor + relativedelta(microseconds=-1) == end: break yield floor, ceil @classmethod def interval( cls, frame: _T_FRAMES, start: dt_datetime, end: dt_datetime, interval: int = 1, tz: Optional[TZ_EXPR] = None, bounds: _BOUNDS = "[)", exact: bool = False, ) -> Iterable[Tuple["Arrow", "Arrow"]]: if interval < 1: raise ValueError("interval has to be a positive integer") spanRange = iter( cls.span_range(frame, start, end, tz, bounds=bounds, exact=exact) ) while True: try: intvlStart, intvlEnd = next(spanRange) for _ in range(interval - 1): try: _, intvlEnd = next(spanRange) except StopIteration: continue yield intvlStart, intvlEnd except StopIteration: return def __repr__(self) -> str: return f"<{self.__class__.__name__} [{self.__str__()}]>" def __str__(self) -> str: return self._datetime.isoformat() def __format__(self, formatstr: str) -> str: if len(formatstr) > 0: return self.format(formatstr) return str(self) def __hash__(self) -> int: return self._datetime.__hash__() def __getattr__(self, name: str) -> int: if name == "week": return self.isocalendar()[1] if name == "quarter": return int((self.month - 1) / self._MONTHS_PER_QUARTER) + 1 if not name.startswith("_"): value: Optional[int] = getattr(self._datetime, name, None) if value is not None: return value return cast(int, object.__getattribute__(self, name)) @property def tzinfo(self) -> dt_tzinfo: return cast(dt_tzinfo, self._datetime.tzinfo) @property def datetime(self) -> dt_datetime: return self._datetime @property def naive(self) -> dt_datetime: return self._datetime.replace(tzinfo=None) def timestamp(self) -> float: return self._datetime.timestamp() @property def int_timestamp(self) -> int: return int(self.timestamp()) @property def float_timestamp(self) -> float: return self.timestamp() @property def fold(self) -> int: return self._datetime.fold @property def ambiguous(self) -> bool: return dateutil_tz.datetime_ambiguous(self._datetime) @property def imaginary(self) -> bool: return not dateutil_tz.datetime_exists(self._datetime) def clone(self) -> "Arrow": return self.fromdatetime(self._datetime) def replace(self, **kwargs: Any) -> "Arrow": absolute_kwargs = {} for key, value in kwargs.items(): if key in self._ATTRS: absolute_kwargs[key] = value elif key in ["week", "quarter"]: raise ValueError(f"Setting absolute {key} is not supported.") elif key not in ["tzinfo", "fold"]: raise ValueError(f"Unknown attribute: {key!r}.") current = self._datetime.replace(**absolute_kwargs) tzinfo = kwargs.get("tzinfo") if tzinfo is not None: tzinfo = self._get_tzinfo(tzinfo) current = current.replace(tzinfo=tzinfo) fold = kwargs.get("fold") if fold is not None: current = current.replace(fold=fold) return self.fromdatetime(current) def shift(self, **kwargs: Any) -> "Arrow": relative_kwargs = {} additional_attrs = ["weeks", "quarters", "weekday"] for key, value in kwargs.items(): if key in self._ATTRS_PLURAL or key in additional_attrs: relative_kwargs[key] = value else: supported_attr = ", ".join(self._ATTRS_PLURAL + additional_attrs) raise ValueError( f"Invalid shift time frame. Please select one of the following: {supported_attr}." ) relative_kwargs.setdefault("months", 0) relative_kwargs["months"] += ( relative_kwargs.pop("quarters", 0) * self._MONTHS_PER_QUARTER ) current = self._datetime + relativedelta(**relative_kwargs) if not dateutil_tz.datetime_exists(current): current = dateutil_tz.resolve_imaginary(current) return self.fromdatetime(current) def to(self, tz: TZ_EXPR) -> "Arrow": if not isinstance(tz, dt_tzinfo): tz = parser.TzinfoParser.parse(tz) dt = self._datetime.astimezone(tz) return self.__class__( dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, dt.tzinfo, fold=getattr(dt, "fold", 0), ) def format(self, fmt: str = "YYYY-MM-DD HH:mm:ssZZ", locale: str = "en_us") -> str: return formatter.DateTimeFormatter(locale).format(self._datetime, fmt) def humanize( self, other: Union["Arrow", dt_datetime, None] = None, locale: str = "en_us", only_distance: bool = False, granularity: Union[_GRANULARITY, List[_GRANULARITY]] = "auto", ) -> str: locale_name = locale locale = locales.get_locale(locale) if other is None: utc = dt_datetime.utcnow().replace(tzinfo=dateutil_tz.tzutc()) dt = utc.astimezone(self._datetime.tzinfo) elif isinstance(other, Arrow): dt = other._datetime elif isinstance(other, dt_datetime): if other.tzinfo is None: dt = other.replace(tzinfo=self._datetime.tzinfo) else: dt = other.astimezone(self._datetime.tzinfo) else: raise TypeError( f"Invalid 'other' argument of type {type(other).__name__!r}. " "Argument must be of type None, Arrow, or datetime." ) if isinstance(granularity, list) and len(granularity) == 1: granularity = granularity[0] _delta = int(round((self._datetime - dt).total_seconds())) sign = -1 if _delta < 0 else 1 delta_second = diff = abs(_delta) try: if granularity == "auto": if diff < 10: return locale.describe("now", only_distance=only_distance) if diff < self._SECS_PER_MINUTE: seconds = sign * delta_second return locale.describe( "seconds", seconds, only_distance=only_distance ) elif diff < self._SECS_PER_MINUTE * 2: return locale.describe("minute", sign, only_distance=only_distance) elif diff < self._SECS_PER_HOUR: minutes = sign * max(delta_second // self._SECS_PER_MINUTE, 2) return locale.describe( "minutes", minutes, only_distance=only_distance ) elif diff < self._SECS_PER_HOUR * 2: return locale.describe("hour", sign, only_distance=only_distance) elif diff < self._SECS_PER_DAY: hours = sign * max(delta_second // self._SECS_PER_HOUR, 2) return locale.describe("hours", hours, only_distance=only_distance) elif diff < self._SECS_PER_DAY * 2: return locale.describe("day", sign, only_distance=only_distance) elif diff < self._SECS_PER_WEEK: days = sign * max(delta_second // self._SECS_PER_DAY, 2) return locale.describe("days", days, only_distance=only_distance) elif diff < self._SECS_PER_WEEK * 2: return locale.describe("week", sign, only_distance=only_distance) elif diff < self._SECS_PER_MONTH: weeks = sign * max(delta_second // self._SECS_PER_WEEK, 2) return locale.describe("weeks", weeks, only_distance=only_distance) elif diff < self._SECS_PER_MONTH * 2: return locale.describe("month", sign, only_distance=only_distance) elif diff < self._SECS_PER_YEAR: self_months = self._datetime.year * 12 + self._datetime.month other_months = dt.year * 12 + dt.month months = sign * max(abs(other_months - self_months), 2) return locale.describe( "months", months, only_distance=only_distance ) elif diff < self._SECS_PER_YEAR * 2: return locale.describe("year", sign, only_distance=only_distance) else: years = sign * max(delta_second // self._SECS_PER_YEAR, 2) return locale.describe("years", years, only_distance=only_distance) elif isinstance(granularity, str): granularity = cast(TimeFrameLiteral, granularity) if granularity == "second": delta = sign * float(delta_second) if abs(delta) < 2: return locale.describe("now", only_distance=only_distance) elif granularity == "minute": delta = sign * delta_second / self._SECS_PER_MINUTE elif granularity == "hour": delta = sign * delta_second / self._SECS_PER_HOUR elif granularity == "day": delta = sign * delta_second / self._SECS_PER_DAY elif granularity == "week": delta = sign * delta_second / self._SECS_PER_WEEK elif granularity == "month": delta = sign * delta_second / self._SECS_PER_MONTH elif granularity == "year": delta = sign * delta_second / self._SECS_PER_YEAR else: raise ValueError( "Invalid level of granularity. " "Please select between 'second', 'minute', 'hour', 'day', 'week', 'month' or 'year'." ) if trunc(abs(delta)) != 1: granularity += "s" return locale.describe(granularity, delta, only_distance=only_distance) else: timeframes: List[Tuple[TimeFrameLiteral, float]] = [] def gather_timeframes(_delta: float, _frame: TimeFrameLiteral) -> float: if _frame in granularity: value = sign * _delta / self._SECS_MAP[_frame] _delta %= self._SECS_MAP[_frame] if trunc(abs(value)) != 1: timeframes.append( (cast(TimeFrameLiteral, _frame + "s"), value) ) else: timeframes.append((_frame, value)) return _delta delta = float(delta_second) frames: Tuple[TimeFrameLiteral, ...] = ( "year", "month", "week", "day", "hour", "minute", "second", ) for frame in frames: delta = gather_timeframes(delta, frame) if len(timeframes) < len(granularity): raise ValueError( "Invalid level of granularity. " "Please select between 'second', 'minute', 'hour', 'day', 'week', 'month' or 'year'." ) return locale.describe_multi(timeframes, only_distance=only_distance) except KeyError as e: raise ValueError( f"Humanization of the {e} granularity is not currently translated in the {locale_name!r} locale. " "Please consider making a contribution to this locale." ) def is_between( self, start: "Arrow", end: "Arrow", bounds: _BOUNDS = "()", ) -> bool: util.validate_bounds(bounds) if not isinstance(start, Arrow): raise TypeError( f"Cannot parse start date argument type of {type(start)!r}." ) if not isinstance(end, Arrow): raise TypeError(f"Cannot parse end date argument type of {type(start)!r}.") include_start = bounds[0] == "[" include_end = bounds[1] == "]" target_ts = self.float_timestamp start_ts = start.float_timestamp end_ts = end.float_timestamp return ( (start_ts <= target_ts <= end_ts) and (include_start or start_ts < target_ts) and (include_end or target_ts < end_ts) ) def date(self) -> date: return self._datetime.date() def time(self) -> dt_time: return self._datetime.time() def timetz(self) -> dt_time: return self._datetime.timetz() def astimezone(self, tz: Optional[dt_tzinfo]) -> dt_datetime: return self._datetime.astimezone(tz) def utcoffset(self) -> Optional[timedelta]: return self._datetime.utcoffset() def dst(self) -> Optional[timedelta]: return self._datetime.dst() def timetuple(self) -> struct_time: return self._datetime.timetuple() def utctimetuple(self) -> struct_time: return self._datetime.utctimetuple() def toordinal(self) -> int: return self._datetime.toordinal() def weekday(self) -> int: return self._datetime.weekday() def isoweekday(self) -> int: return self._datetime.isoweekday() def isocalendar(self) -> Tuple[int, int, int]: return self._datetime.isocalendar() def isoformat(self, sep: str = "T", timespec: str = "auto") -> str: return self._datetime.isoformat(sep, timespec) def ctime(self) -> str: return self._datetime.ctime() def strftime(self, format: str) -> str: return self._datetime.strftime(format) def for_json(self) -> str: return self.isoformat() def __add__(self, other: Any) -> "Arrow": if isinstance(other, (timedelta, relativedelta)): return self.fromdatetime(self._datetime + other, self._datetime.tzinfo) return NotImplemented def __radd__(self, other: Union[timedelta, relativedelta]) -> "Arrow": return self.__add__(other) @overload def __sub__(self, other: Union[timedelta, relativedelta]) -> "Arrow": pass @overload def __sub__(self, other: Union[dt_datetime, "Arrow"]) -> timedelta: pass def __sub__(self, other: Any) -> Union[timedelta, "Arrow"]: if isinstance(other, (timedelta, relativedelta)): return self.fromdatetime(self._datetime - other, self._datetime.tzinfo) elif isinstance(other, dt_datetime): return self._datetime - other elif isinstance(other, Arrow): return self._datetime - other._datetime return NotImplemented def __rsub__(self, other: Any) -> timedelta: if isinstance(other, dt_datetime): return other - self._datetime return NotImplemented def __eq__(self, other: Any) -> bool: if not isinstance(other, (Arrow, dt_datetime)): return False return self._datetime == self._get_datetime(other) def __ne__(self, other: Any) -> bool: if not isinstance(other, (Arrow, dt_datetime)): return True return not self.__eq__(other) def __gt__(self, other: Any) -> bool: if not isinstance(other, (Arrow, dt_datetime)): return NotImplemented return self._datetime > self._get_datetime(other) def __ge__(self, other: Any) -> bool: if not isinstance(other, (Arrow, dt_datetime)): return NotImplemented return self._datetime >= self._get_datetime(other) def __lt__(self, other: Any) -> bool: if not isinstance(other, (Arrow, dt_datetime)): return NotImplemented return self._datetime < self._get_datetime(other) def __le__(self, other: Any) -> bool: if not isinstance(other, (Arrow, dt_datetime)): return NotImplemented return self._datetime <= self._get_datetime(other) @staticmethod def _get_tzinfo(tz_expr: Optional[TZ_EXPR]) -> dt_tzinfo: if tz_expr is None: return dateutil_tz.tzutc() if isinstance(tz_expr, dt_tzinfo): return tz_expr else: try: return parser.TzinfoParser.parse(tz_expr) except parser.ParserError: raise ValueError(f"{tz_expr!r} not recognized as a timezone.") @classmethod def _get_datetime( cls, expr: Union["Arrow", dt_datetime, int, float, str] ) -> dt_datetime: if isinstance(expr, Arrow): return expr.datetime elif isinstance(expr, dt_datetime): return expr elif util.is_timestamp(expr): timestamp = float(expr) return cls.utcfromtimestamp(timestamp).datetime else: raise ValueError(f"{expr!r} not recognized as a datetime or timestamp.") @classmethod def _get_frames(cls, name: _T_FRAMES) -> Tuple[str, str, int]: if name in cls._ATTRS: return name, f"{name}s", 1 elif name[-1] == "s" and name[:-1] in cls._ATTRS: return name[:-1], name, 1 elif name in ["week", "weeks"]: return "week", "weeks", 1 elif name in ["quarter", "quarters"]: return "quarter", "months", 3 else: supported = ", ".join( [ "year(s)", "month(s)", "day(s)", "hour(s)", "minute(s)", "second(s)", "microsecond(s)", "week(s)", "quarter(s)", ] ) raise ValueError( f"Range or span over frame {name} not supported. Supported frames: {supported}." ) @classmethod def _get_iteration_params(cls, end: Any, limit: Optional[int]) -> Tuple[Any, int]: if end is None: if limit is None: raise ValueError("One of 'end' or 'limit' is required.") return cls.max, limit else: if limit is None: return end, sys.maxsize return end, limit @staticmethod def _is_last_day_of_month(date: "Arrow") -> bool: return date.day == calendar.monthrange(date.year, date.month)[1] Arrow.min = Arrow.fromdatetime(dt_datetime.min) Arrow.max = Arrow.fromdatetime(dt_datetime.max)
true
true
f717aff2b542befa776d914dfd5cc573bbed5908
2,681
py
Python
make/photon/prepare/main.py
gaohuag/harbor
ebe2df06c84c3b6be33901e71d9bf14e80a4c003
[ "Apache-2.0" ]
1
2019-10-24T07:11:38.000Z
2019-10-24T07:11:38.000Z
make/photon/prepare/main.py
gaohuag/harbor
ebe2df06c84c3b6be33901e71d9bf14e80a4c003
[ "Apache-2.0" ]
null
null
null
make/photon/prepare/main.py
gaohuag/harbor
ebe2df06c84c3b6be33901e71d9bf14e80a4c003
[ "Apache-2.0" ]
null
null
null
# pylint: disable=no-value-for-parameter import click from utils.misc import delfile from utils.configs import validate, parse_yaml_config from utils.cert import prepare_ca, SSL_CERT_KEY_PATH, SSL_CERT_PATH, get_secret_key from utils.db import prepare_db from utils.jobservice import prepare_job_service from utils.registry import prepare_registry from utils.registry_ctl import prepare_registry_ctl from utils.core import prepare_core from utils.notary import prepare_notary from utils.log import prepare_log_configs from utils.clair import prepare_clair from utils.clair_adapter import prepare_clair_adapter from utils.chart import prepare_chartmuseum from utils.docker_compose import prepare_docker_compose from utils.nginx import prepare_nginx, nginx_confd_dir from utils.redis import prepare_redis from g import (config_dir, input_config_path, private_key_pem_path, root_crt_path, secret_key_dir, old_private_key_pem_path, old_crt_path) # Main function @click.command() @click.option('--conf', default=input_config_path, help="the path of Harbor configuration file") @click.option('--with-notary', is_flag=True, help="the Harbor instance is to be deployed with notary") @click.option('--with-clair', is_flag=True, help="the Harbor instance is to be deployed with clair") @click.option('--with-chartmuseum', is_flag=True, help="the Harbor instance is to be deployed with chart repository supporting") def main(conf, with_notary, with_clair, with_chartmuseum): delfile(config_dir) config_dict = parse_yaml_config(conf, with_notary=with_notary, with_clair=with_clair, with_chartmuseum=with_chartmuseum) validate(config_dict, notary_mode=with_notary) prepare_log_configs(config_dict) prepare_nginx(config_dict) prepare_core(config_dict, with_notary=with_notary, with_clair=with_clair, with_chartmuseum=with_chartmuseum) prepare_registry(config_dict) prepare_registry_ctl(config_dict) prepare_db(config_dict) prepare_job_service(config_dict) prepare_redis(config_dict) get_secret_key(secret_key_dir) # If Customized cert enabled prepare_ca( private_key_pem_path=private_key_pem_path, root_crt_path=root_crt_path, old_private_key_pem_path=old_private_key_pem_path, old_crt_path=old_crt_path) if with_notary: prepare_notary(config_dict, nginx_confd_dir, SSL_CERT_PATH, SSL_CERT_KEY_PATH) if with_clair: prepare_clair(config_dict) prepare_clair_adapter(config_dict) if with_chartmuseum: prepare_chartmuseum(config_dict) prepare_docker_compose(config_dict, with_clair, with_notary, with_chartmuseum) if __name__ == '__main__': main()
40.621212
128
0.806043
import click from utils.misc import delfile from utils.configs import validate, parse_yaml_config from utils.cert import prepare_ca, SSL_CERT_KEY_PATH, SSL_CERT_PATH, get_secret_key from utils.db import prepare_db from utils.jobservice import prepare_job_service from utils.registry import prepare_registry from utils.registry_ctl import prepare_registry_ctl from utils.core import prepare_core from utils.notary import prepare_notary from utils.log import prepare_log_configs from utils.clair import prepare_clair from utils.clair_adapter import prepare_clair_adapter from utils.chart import prepare_chartmuseum from utils.docker_compose import prepare_docker_compose from utils.nginx import prepare_nginx, nginx_confd_dir from utils.redis import prepare_redis from g import (config_dir, input_config_path, private_key_pem_path, root_crt_path, secret_key_dir, old_private_key_pem_path, old_crt_path) @click.command() @click.option('--conf', default=input_config_path, help="the path of Harbor configuration file") @click.option('--with-notary', is_flag=True, help="the Harbor instance is to be deployed with notary") @click.option('--with-clair', is_flag=True, help="the Harbor instance is to be deployed with clair") @click.option('--with-chartmuseum', is_flag=True, help="the Harbor instance is to be deployed with chart repository supporting") def main(conf, with_notary, with_clair, with_chartmuseum): delfile(config_dir) config_dict = parse_yaml_config(conf, with_notary=with_notary, with_clair=with_clair, with_chartmuseum=with_chartmuseum) validate(config_dict, notary_mode=with_notary) prepare_log_configs(config_dict) prepare_nginx(config_dict) prepare_core(config_dict, with_notary=with_notary, with_clair=with_clair, with_chartmuseum=with_chartmuseum) prepare_registry(config_dict) prepare_registry_ctl(config_dict) prepare_db(config_dict) prepare_job_service(config_dict) prepare_redis(config_dict) get_secret_key(secret_key_dir) prepare_ca( private_key_pem_path=private_key_pem_path, root_crt_path=root_crt_path, old_private_key_pem_path=old_private_key_pem_path, old_crt_path=old_crt_path) if with_notary: prepare_notary(config_dict, nginx_confd_dir, SSL_CERT_PATH, SSL_CERT_KEY_PATH) if with_clair: prepare_clair(config_dict) prepare_clair_adapter(config_dict) if with_chartmuseum: prepare_chartmuseum(config_dict) prepare_docker_compose(config_dict, with_clair, with_notary, with_chartmuseum) if __name__ == '__main__': main()
true
true
f717b0f7dc65a5798b28471eda50f0d297865349
3,637
py
Python
dendropy/dataio/nexmlyielder.py
EnjoyLifeFund/macHighSierra-py36-pkgs
5668b5785296b314ea1321057420bcd077dba9ea
[ "BSD-3-Clause", "BSD-2-Clause", "MIT" ]
null
null
null
dendropy/dataio/nexmlyielder.py
EnjoyLifeFund/macHighSierra-py36-pkgs
5668b5785296b314ea1321057420bcd077dba9ea
[ "BSD-3-Clause", "BSD-2-Clause", "MIT" ]
null
null
null
dendropy/dataio/nexmlyielder.py
EnjoyLifeFund/macHighSierra-py36-pkgs
5668b5785296b314ea1321057420bcd077dba9ea
[ "BSD-3-Clause", "BSD-2-Clause", "MIT" ]
null
null
null
#! /usr/bin/env python ############################################################################## ## DendroPy Phylogenetic Computing Library. ## ## Copyright 2010-2015 Jeet Sukumaran and Mark T. Holder. ## All rights reserved. ## ## See "LICENSE.rst" for terms and conditions of usage. ## ## If you use this work or any portion thereof in published work, ## please cite it as: ## ## Sukumaran, J. and M. T. Holder. 2010. DendroPy: a Python library ## for phylogenetic computing. Bioinformatics 26: 1569-1571. ## ############################################################################## """ Implementation of NEXML-schema tree iterator. """ import sys if not (sys.version_info.major >= 3 and sys.version_info.minor >= 4): from dendropy.utility.filesys import pre_py34_open as open from dendropy.dataio import ioservice from dendropy.dataio import nexmlreader from dendropy.dataio import xmlprocessing class NexmlTreeDataYielder( ioservice.TreeDataYielder, nexmlreader.NexmlReader): def __init__(self, files=None, taxon_namespace=None, tree_type=None, **kwargs): """ Parameters ---------- files : iterable of sources Iterable of sources, which can either be strings specifying file paths or file-like objects open for reading. If a source element is a string, then it is assumed to be a path to a file. Otherwise, the source is assumed to be a file-like object. taxon_namespace : |TaxonNamespace| instance The operational taxonomic unit concept namespace to use to manage taxon definitions. \*\*kwargs : keyword arguments These will be passed directly to the base `nexmlreader.NexusReader` class. See `nexmlreader.NexusReader` for details. """ ioservice.TreeDataYielder.__init__(self, files=files, taxon_namespace=taxon_namespace, tree_type=tree_type) nexmlreader.NexmlReader.__init__(self, **kwargs) self.attached_taxon_namespace = self.taxon_namespace ########################################################################### ## Implementation of DataYielder interface def _yield_items_from_stream(self, stream): xml_doc = xmlprocessing.XmlDocument(file_obj=stream, subelement_factory=self._subelement_factory) self._namespace_registry = xml_doc.namespace_registry xml_root = xml_doc.root self._parse_taxon_namespaces(xml_root) tree_parser = nexmlreader._NexmlTreeParser( id_taxon_map=self._id_taxon_map, annotations_processor_fn=self._parse_annotations, ) for trees_idx, trees_element in enumerate(xml_root.iter_trees()): trees_id = trees_element.get('id', "Trees" + str(trees_idx)) trees_label = trees_element.get('label', None) otus_id = trees_element.get('otus', None) if otus_id is None: raise Exception("Taxa block not specified for trees block '{}'".format(otus_id)) taxon_namespace = self._id_taxon_namespace_map.get(otus_id, None) if not taxon_namespace: raise Exception("Tree block '{}': Taxa block '{}' not found".format(trees_id, otus_id)) for tree_element in trees_element.findall_tree(): tree_obj = self.tree_factory() tree_parser.build_tree(tree_obj, tree_element, otus_id) yield tree_obj
40.865169
103
0.607369
true
true
f717b173935cbd0d7770fed38f1c470436bb75f4
970
py
Python
tests/testNextRule.py
andersonjwan/tltk-mtl-ext
a4f0314df6c55d532b7f9d169b6d08bff3811ef3
[ "BSD-3-Clause" ]
1
2020-12-11T21:32:46.000Z
2020-12-11T21:32:46.000Z
tests/testNextRule.py
andersonjwan/tltk-mtl-ext
a4f0314df6c55d532b7f9d169b6d08bff3811ef3
[ "BSD-3-Clause" ]
null
null
null
tests/testNextRule.py
andersonjwan/tltk-mtl-ext
a4f0314df6c55d532b7f9d169b6d08bff3811ef3
[ "BSD-3-Clause" ]
null
null
null
import tltk_mtl as MTL import tltk_mtl_ext as MTLE def testNextRule(): preds = {} preds['pred1'] = MTL.Predicate('pred1', 1, 2) preds['pred2'] = MTL.Predicate('pred2', 2, 4) preds['pred3'] = MTL.Predicate('pred3', 4, 8) assert isinstance(MTLE.parse_mtl('next pred1', preds), MTL.Next), printFail(1) printPass(1) assert isinstance(MTLE.parse_mtl('next X pred1', preds), MTL.Next), printFail(2) printPass(2) assert isinstance(MTLE.parse_mtl('next (pred1 && pred2)', preds), MTL.Next), printFail(3) printPass(3) assert isinstance(MTLE.parse_mtl('X (pred1 && X X X pred3)', preds), MTL.Next), printFail(4) printPass(4) assert isinstance(MTLE.parse_mtl('X X X X X X X X (pred1 & pred2)', preds), MTL.Next), printFail(5) printPass(5) def printPass(test_num): print("%-20s Assertion No. %02d PASSED." % ('[Next Rule Test]', test_num)) def printFail(test_num): return '%-20s Assertion No. %02d FAILED' % ('[Next Rule Test]', test_num) testNextRule()
34.642857
100
0.689691
import tltk_mtl as MTL import tltk_mtl_ext as MTLE def testNextRule(): preds = {} preds['pred1'] = MTL.Predicate('pred1', 1, 2) preds['pred2'] = MTL.Predicate('pred2', 2, 4) preds['pred3'] = MTL.Predicate('pred3', 4, 8) assert isinstance(MTLE.parse_mtl('next pred1', preds), MTL.Next), printFail(1) printPass(1) assert isinstance(MTLE.parse_mtl('next X pred1', preds), MTL.Next), printFail(2) printPass(2) assert isinstance(MTLE.parse_mtl('next (pred1 && pred2)', preds), MTL.Next), printFail(3) printPass(3) assert isinstance(MTLE.parse_mtl('X (pred1 && X X X pred3)', preds), MTL.Next), printFail(4) printPass(4) assert isinstance(MTLE.parse_mtl('X X X X X X X X (pred1 & pred2)', preds), MTL.Next), printFail(5) printPass(5) def printPass(test_num): print("%-20s Assertion No. %02d PASSED." % ('[Next Rule Test]', test_num)) def printFail(test_num): return '%-20s Assertion No. %02d FAILED' % ('[Next Rule Test]', test_num) testNextRule()
true
true
f717b362c8813b8acd724ce809248566680836c5
591
py
Python
data & result/history.py
robinzixuan/Dialog_Act_Bert_Classification
014cc8df0545e5bf85a22127e63e8490f3aa9012
[ "MIT" ]
null
null
null
data & result/history.py
robinzixuan/Dialog_Act_Bert_Classification
014cc8df0545e5bf85a22127e63e8490f3aa9012
[ "MIT" ]
null
null
null
data & result/history.py
robinzixuan/Dialog_Act_Bert_Classification
014cc8df0545e5bf85a22127e63e8490f3aa9012
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jun 30 20:49:32 2019 @author: rluo """ import keras import matplotlib.pyplot as plt from keras.models import load_model import pickle history = pickle.load(open('history.p','rb')) plt.plot(history['loss']) #plt.plot(history['val_loss']) plt.title('model loss') plt.ylabel('loss') plt.xlabel('Epoch') plt.legend(['train', 'test'], loc='upper left'); plt.plot(history['acc']) #plt.plot(history['val_acc']) plt.title('model accuracy') plt.ylabel('acc') plt.xlabel('Epoch') plt.legend(['train', 'test'], loc='upper left');
19.7
48
0.683587
import keras import matplotlib.pyplot as plt from keras.models import load_model import pickle history = pickle.load(open('history.p','rb')) plt.plot(history['loss']) plt.title('model loss') plt.ylabel('loss') plt.xlabel('Epoch') plt.legend(['train', 'test'], loc='upper left'); plt.plot(history['acc']) plt.title('model accuracy') plt.ylabel('acc') plt.xlabel('Epoch') plt.legend(['train', 'test'], loc='upper left');
true
true
f717b38081c7eaa8fa44370f116ae44f650ba3cb
689
py
Python
examples/seq2seq/paraphrasing/predict.py
liorshk/simpletransformers
226cf4d11edf5157c1beafcc44aaa78f65ccc985
[ "Apache-2.0" ]
3,151
2019-10-05T11:14:44.000Z
2022-03-31T17:02:54.000Z
examples/seq2seq/paraphrasing/predict.py
liorshk/simpletransformers
226cf4d11edf5157c1beafcc44aaa78f65ccc985
[ "Apache-2.0" ]
1,165
2019-10-05T14:48:55.000Z
2022-03-31T11:12:58.000Z
examples/seq2seq/paraphrasing/predict.py
liorshk/simpletransformers
226cf4d11edf5157c1beafcc44aaa78f65ccc985
[ "Apache-2.0" ]
739
2019-10-06T15:11:54.000Z
2022-03-28T11:07:36.000Z
import logging from simpletransformers.seq2seq import Seq2SeqModel logging.basicConfig(level=logging.INFO) transformers_logger = logging.getLogger("transformers") transformers_logger.setLevel(logging.ERROR) model = Seq2SeqModel(encoder_decoder_type="bart", encoder_decoder_name="outputs") while True: original = input("Enter text to paraphrase: ") to_predict = [original] preds = model.predict(to_predict) print("---------------------------------------------------------") print(original) print() print("Predictions >>>") for pred in preds[0]: print(pred) print("---------------------------------------------------------") print()
23.758621
81
0.593614
import logging from simpletransformers.seq2seq import Seq2SeqModel logging.basicConfig(level=logging.INFO) transformers_logger = logging.getLogger("transformers") transformers_logger.setLevel(logging.ERROR) model = Seq2SeqModel(encoder_decoder_type="bart", encoder_decoder_name="outputs") while True: original = input("Enter text to paraphrase: ") to_predict = [original] preds = model.predict(to_predict) print("---------------------------------------------------------") print(original) print() print("Predictions >>>") for pred in preds[0]: print(pred) print("---------------------------------------------------------") print()
true
true
f717b4377f6a9a74d53a66640675d4744b9f7a3a
2,171
py
Python
app.py
dennisfarmer/Ensemble-Video-Downloader
fa3cb334f9140b5fecdfcb1c2ee6020743a484a7
[ "MIT" ]
null
null
null
app.py
dennisfarmer/Ensemble-Video-Downloader
fa3cb334f9140b5fecdfcb1c2ee6020743a484a7
[ "MIT" ]
1
2021-08-02T19:08:13.000Z
2021-08-03T02:35:49.000Z
app.py
dennisfarmer/Ensemble-Video-Downloader
fa3cb334f9140b5fecdfcb1c2ee6020743a484a7
[ "MIT" ]
1
2021-08-03T04:44:13.000Z
2021-08-03T04:44:13.000Z
from PyQt5.QtWidgets import QApplication,QWidget,QTextEdit,QVBoxLayout,QPushButton from link_converter import convert_url import pyperclip import sys class LinkConverter(QWidget): def __init__(self,parent=None): super().__init__(parent) self.setWindowTitle("Ensemblevideo Link Converter - Dennis Farmer") self.resize(600,300) self.textEdit = QTextEdit() self.btnPress1 = QPushButton("Convert to Download Link") self.btnPress3 = QPushButton("Clear Field Contents") self.btnPress2 = QPushButton("Copy to Clipboard") layout = QVBoxLayout() layout.addWidget(self.textEdit) layout.addWidget(self.btnPress1) layout.addWidget(self.btnPress2) layout.addWidget(self.btnPress3) self.setLayout(layout) self.textEdit.setPlainText("https://cloud.ensemblevideo.com/hapi/v1/contents/e5ee9fb7-8a1e-48f2-9e4d-2ac8a77c2478/launch?embedAsThumbnail=false&displayTitle=True&displaySharing=False&autoplay=False&showCaptions=False&hideControls=True&audioPreviewImage=False&displayEmbedCode=False&displayAttachments=True&displayLinks=True&displayCredits=False&displayVideoDuration=False&displayNotes=True&displayCaptionSearch=True&displayMetaData=false&displayDownloadIcon=False&displayViewersReport=False&displayAxdxs=False&idn_content=e5ee9fb7-8a1e-48f2-9e4d-2ac8a77c2478&idn_init=False&idn_sig=62NO%2FKLkev7ZUVK696RTOVkjP1Q%3D") self.btnPress1.clicked.connect(self.btnPress1_Clicked) self.btnPress2.clicked.connect(self.btnPress2_Clicked) self.btnPress3.clicked.connect(self.btnPress3_Clicked) def btnPress1_Clicked(self): old_url = self.textEdit.toPlainText() new_url = convert_url(old_url) self.textEdit.setPlainText(new_url) def btnPress2_Clicked(self): url = self.textEdit.toPlainText() pyperclip.copy(url) def btnPress3_Clicked(self): self.textEdit.setPlainText("") def Start(): lc = LinkConverter() lc.show() return lc def main(): app = QApplication(sys.argv) win = Start() app.exec_() #sys.exit(app.exec_()) if __name__ == '__main__': main()
39.472727
624
0.738369
from PyQt5.QtWidgets import QApplication,QWidget,QTextEdit,QVBoxLayout,QPushButton from link_converter import convert_url import pyperclip import sys class LinkConverter(QWidget): def __init__(self,parent=None): super().__init__(parent) self.setWindowTitle("Ensemblevideo Link Converter - Dennis Farmer") self.resize(600,300) self.textEdit = QTextEdit() self.btnPress1 = QPushButton("Convert to Download Link") self.btnPress3 = QPushButton("Clear Field Contents") self.btnPress2 = QPushButton("Copy to Clipboard") layout = QVBoxLayout() layout.addWidget(self.textEdit) layout.addWidget(self.btnPress1) layout.addWidget(self.btnPress2) layout.addWidget(self.btnPress3) self.setLayout(layout) self.textEdit.setPlainText("https://cloud.ensemblevideo.com/hapi/v1/contents/e5ee9fb7-8a1e-48f2-9e4d-2ac8a77c2478/launch?embedAsThumbnail=false&displayTitle=True&displaySharing=False&autoplay=False&showCaptions=False&hideControls=True&audioPreviewImage=False&displayEmbedCode=False&displayAttachments=True&displayLinks=True&displayCredits=False&displayVideoDuration=False&displayNotes=True&displayCaptionSearch=True&displayMetaData=false&displayDownloadIcon=False&displayViewersReport=False&displayAxdxs=False&idn_content=e5ee9fb7-8a1e-48f2-9e4d-2ac8a77c2478&idn_init=False&idn_sig=62NO%2FKLkev7ZUVK696RTOVkjP1Q%3D") self.btnPress1.clicked.connect(self.btnPress1_Clicked) self.btnPress2.clicked.connect(self.btnPress2_Clicked) self.btnPress3.clicked.connect(self.btnPress3_Clicked) def btnPress1_Clicked(self): old_url = self.textEdit.toPlainText() new_url = convert_url(old_url) self.textEdit.setPlainText(new_url) def btnPress2_Clicked(self): url = self.textEdit.toPlainText() pyperclip.copy(url) def btnPress3_Clicked(self): self.textEdit.setPlainText("") def Start(): lc = LinkConverter() lc.show() return lc def main(): app = QApplication(sys.argv) win = Start() app.exec_() if __name__ == '__main__': main()
true
true
f717b45b3fbcc04aefd659d8153dad422e2f094b
3,280
py
Python
test/optimization/test_vertex_cover.py
kareem1925/qiskit-aqua
7056f9bdd9ece32c41e162faecdcd24cf483da6f
[ "Apache-2.0" ]
null
null
null
test/optimization/test_vertex_cover.py
kareem1925/qiskit-aqua
7056f9bdd9ece32c41e162faecdcd24cf483da6f
[ "Apache-2.0" ]
null
null
null
test/optimization/test_vertex_cover.py
kareem1925/qiskit-aqua
7056f9bdd9ece32c41e162faecdcd24cf483da6f
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Test Vertex Cover """ import unittest from test.optimization import QiskitOptimizationTestCase import numpy as np from qiskit import BasicAer from qiskit.aqua import aqua_globals, QuantumInstance from qiskit.optimization.applications.ising import vertex_cover from qiskit.optimization.applications.ising.common import random_graph, sample_most_likely from qiskit.aqua.algorithms import NumPyMinimumEigensolver, VQE from qiskit.aqua.components.variational_forms import RYRZ from qiskit.aqua.components.optimizers import SPSA class TestVertexCover(QiskitOptimizationTestCase): """Cplex Ising tests.""" def setUp(self): super().setUp() self.seed = 100 aqua_globals.random_seed = self.seed self.num_nodes = 3 self.w = random_graph(self.num_nodes, edge_prob=0.8, weight_range=10) self.qubit_op, self.offset = vertex_cover.get_operator(self.w) def _brute_force(self): # brute-force way def bitfield(n, length): result = np.binary_repr(n, length) return [int(digit) for digit in result] # [2:] to chop off the "0b" part nodes = self.num_nodes maximum = 2 ** nodes minimal_v = np.inf for i in range(maximum): cur = bitfield(i, nodes) cur_v = vertex_cover.check_full_edge_coverage(np.array(cur), self.w) if cur_v: nonzerocount = np.count_nonzero(cur) if nonzerocount < minimal_v: minimal_v = nonzerocount return minimal_v def test_vertex_cover(self): """ Vertex Cover test """ algo = NumPyMinimumEigensolver(self.qubit_op, aux_operators=[]) result = algo.run() x = sample_most_likely(result.eigenstate) sol = vertex_cover.get_graph_solution(x) np.testing.assert_array_equal(sol, [0, 1, 1]) oracle = self._brute_force() self.assertEqual(np.count_nonzero(sol), oracle) def test_vertex_cover_vqe(self): """ Vertex Cover VQE test """ aqua_globals.random_seed = self.seed result = VQE(self.qubit_op, RYRZ(self.qubit_op.num_qubits, depth=3), SPSA(max_trials=200), max_evals_grouped=2).run( QuantumInstance(BasicAer.get_backend('qasm_simulator'), seed_simulator=aqua_globals.random_seed, seed_transpiler=aqua_globals.random_seed)) x = sample_most_likely(result['eigvecs'][0]) sol = vertex_cover.get_graph_solution(x) oracle = self._brute_force() self.assertEqual(np.count_nonzero(sol), oracle) if __name__ == '__main__': unittest.main()
36.043956
90
0.655488
import unittest from test.optimization import QiskitOptimizationTestCase import numpy as np from qiskit import BasicAer from qiskit.aqua import aqua_globals, QuantumInstance from qiskit.optimization.applications.ising import vertex_cover from qiskit.optimization.applications.ising.common import random_graph, sample_most_likely from qiskit.aqua.algorithms import NumPyMinimumEigensolver, VQE from qiskit.aqua.components.variational_forms import RYRZ from qiskit.aqua.components.optimizers import SPSA class TestVertexCover(QiskitOptimizationTestCase): def setUp(self): super().setUp() self.seed = 100 aqua_globals.random_seed = self.seed self.num_nodes = 3 self.w = random_graph(self.num_nodes, edge_prob=0.8, weight_range=10) self.qubit_op, self.offset = vertex_cover.get_operator(self.w) def _brute_force(self): def bitfield(n, length): result = np.binary_repr(n, length) return [int(digit) for digit in result] nodes = self.num_nodes maximum = 2 ** nodes minimal_v = np.inf for i in range(maximum): cur = bitfield(i, nodes) cur_v = vertex_cover.check_full_edge_coverage(np.array(cur), self.w) if cur_v: nonzerocount = np.count_nonzero(cur) if nonzerocount < minimal_v: minimal_v = nonzerocount return minimal_v def test_vertex_cover(self): algo = NumPyMinimumEigensolver(self.qubit_op, aux_operators=[]) result = algo.run() x = sample_most_likely(result.eigenstate) sol = vertex_cover.get_graph_solution(x) np.testing.assert_array_equal(sol, [0, 1, 1]) oracle = self._brute_force() self.assertEqual(np.count_nonzero(sol), oracle) def test_vertex_cover_vqe(self): aqua_globals.random_seed = self.seed result = VQE(self.qubit_op, RYRZ(self.qubit_op.num_qubits, depth=3), SPSA(max_trials=200), max_evals_grouped=2).run( QuantumInstance(BasicAer.get_backend('qasm_simulator'), seed_simulator=aqua_globals.random_seed, seed_transpiler=aqua_globals.random_seed)) x = sample_most_likely(result['eigvecs'][0]) sol = vertex_cover.get_graph_solution(x) oracle = self._brute_force() self.assertEqual(np.count_nonzero(sol), oracle) if __name__ == '__main__': unittest.main()
true
true
f717b6f0791909056e625635779049e23c7cb669
1,651
py
Python
scripts/test.py
JIC-Image-Analysis/find-plasmodesmata-dockerised
940afd85687b8383203f65da586da58a234e2deb
[ "MIT" ]
null
null
null
scripts/test.py
JIC-Image-Analysis/find-plasmodesmata-dockerised
940afd85687b8383203f65da586da58a234e2deb
[ "MIT" ]
null
null
null
scripts/test.py
JIC-Image-Analysis/find-plasmodesmata-dockerised
940afd85687b8383203f65da586da58a234e2deb
[ "MIT" ]
null
null
null
"""Functional test.""" import os import os.path from jicbioimage.core.image import MicroscopyCollection from jicbioimage.core.io import ( AutoName, DataManager, FileBackend, _md5_hexdigest_from_file, ) from plasmodesmata_analysis import plasmodesmata_analysis def test_plasmodesmata_analysis(): output_dir = "/output/tmp" if not os.path.isdir(output_dir): os.mkdir(output_dir) try: AutoName.directory = output_dir backend_dir = "/backend" test_image = "/scripts/test_data/test.tif" file_backend = FileBackend(backend_dir) data_manager = DataManager(file_backend) data_manager.load(test_image) md5_hex = _md5_hexdigest_from_file(test_image) manifest_path = os.path.join(backend_dir, md5_hex, "manifest.json") microscopy_collection = MicroscopyCollection() microscopy_collection.parse_manifest(manifest_path) plasmodesmata_analysis(microscopy_collection, 0, 15000, 2, 50) expected_data_dir = "/scripts/test_data/expected" for fname in os.listdir(expected_data_dir): expected_fpath = os.path.join(expected_data_dir, fname) result_fpath = os.path.join(output_dir, fname) expected_md5 = _md5_hexdigest_from_file(expected_fpath) result_md5 = _md5_hexdigest_from_file(result_fpath) assert expected_md5 == result_md5 finally: for fname in os.listdir(output_dir): fpath = os.path.join(output_dir, fname) os.unlink(fpath) os.rmdir(output_dir) if __name__ == "__main__": test_plasmodesmata_analysis()
30.018182
75
0.69473
import os import os.path from jicbioimage.core.image import MicroscopyCollection from jicbioimage.core.io import ( AutoName, DataManager, FileBackend, _md5_hexdigest_from_file, ) from plasmodesmata_analysis import plasmodesmata_analysis def test_plasmodesmata_analysis(): output_dir = "/output/tmp" if not os.path.isdir(output_dir): os.mkdir(output_dir) try: AutoName.directory = output_dir backend_dir = "/backend" test_image = "/scripts/test_data/test.tif" file_backend = FileBackend(backend_dir) data_manager = DataManager(file_backend) data_manager.load(test_image) md5_hex = _md5_hexdigest_from_file(test_image) manifest_path = os.path.join(backend_dir, md5_hex, "manifest.json") microscopy_collection = MicroscopyCollection() microscopy_collection.parse_manifest(manifest_path) plasmodesmata_analysis(microscopy_collection, 0, 15000, 2, 50) expected_data_dir = "/scripts/test_data/expected" for fname in os.listdir(expected_data_dir): expected_fpath = os.path.join(expected_data_dir, fname) result_fpath = os.path.join(output_dir, fname) expected_md5 = _md5_hexdigest_from_file(expected_fpath) result_md5 = _md5_hexdigest_from_file(result_fpath) assert expected_md5 == result_md5 finally: for fname in os.listdir(output_dir): fpath = os.path.join(output_dir, fname) os.unlink(fpath) os.rmdir(output_dir) if __name__ == "__main__": test_plasmodesmata_analysis()
true
true
f717b71efc824a722853352eee8071fc691d8c22
2,118
py
Python
airflow/providers/amazon/aws/example_dags/example_s3_bucket.py
jpsalado92/airflow
6776586904ab2a15727dcfc1c8d03c7a32a78444
[ "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0", "BSD-3-Clause" ]
27
2019-02-25T14:20:36.000Z
2022-03-22T09:35:13.000Z
airflow/providers/amazon/aws/example_dags/example_s3_bucket.py
sdwivedi565/airflow
78e4d16d970dbcb599d9c7f8df2a1a4273649ae8
[ "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0", "BSD-3-Clause" ]
200
2019-01-09T15:33:06.000Z
2022-01-12T09:13:42.000Z
airflow/providers/amazon/aws/example_dags/example_s3_bucket.py
MatrixManAtYrService/airflow-challenge
cef498efe9f4818e5f8e85c179ca730e84b31f4a
[ "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0", "BSD-3-Clause" ]
14
2019-06-25T17:08:29.000Z
2022-03-29T13:25:53.000Z
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import os from datetime import datetime from airflow.decorators import task from airflow.models.dag import DAG from airflow.providers.amazon.aws.hooks.s3 import S3Hook from airflow.providers.amazon.aws.operators.s3 import S3CreateBucketOperator, S3DeleteBucketOperator BUCKET_NAME = os.environ.get('BUCKET_NAME', 'test-airflow-12345') @task(task_id="s3_bucket_dag_add_keys_to_bucket") def upload_keys(): """This is a python callback to add keys into the s3 bucket""" # add keys to bucket s3_hook = S3Hook() for i in range(0, 3): s3_hook.load_string( string_data="input", key=f"path/data{i}", bucket_name=BUCKET_NAME, ) # [START howto_operator_s3_bucket] with DAG( dag_id='s3_bucket_dag', schedule_interval=None, start_date=datetime(2021, 1, 1), catchup=False, default_args={"bucket_name": BUCKET_NAME}, max_active_runs=1, tags=['example'], ) as dag: create_bucket = S3CreateBucketOperator(task_id='s3_bucket_dag_create', region_name='us-east-1') # Using a task-decorated function to add keys add_keys_to_bucket = upload_keys() delete_bucket = S3DeleteBucketOperator(task_id='s3_bucket_dag_delete', force_delete=True) create_bucket >> add_keys_to_bucket >> delete_bucket # [END howto_operator_s3_bucket]
34.721311
100
0.742682
import os from datetime import datetime from airflow.decorators import task from airflow.models.dag import DAG from airflow.providers.amazon.aws.hooks.s3 import S3Hook from airflow.providers.amazon.aws.operators.s3 import S3CreateBucketOperator, S3DeleteBucketOperator BUCKET_NAME = os.environ.get('BUCKET_NAME', 'test-airflow-12345') @task(task_id="s3_bucket_dag_add_keys_to_bucket") def upload_keys(): s3_hook = S3Hook() for i in range(0, 3): s3_hook.load_string( string_data="input", key=f"path/data{i}", bucket_name=BUCKET_NAME, ) with DAG( dag_id='s3_bucket_dag', schedule_interval=None, start_date=datetime(2021, 1, 1), catchup=False, default_args={"bucket_name": BUCKET_NAME}, max_active_runs=1, tags=['example'], ) as dag: create_bucket = S3CreateBucketOperator(task_id='s3_bucket_dag_create', region_name='us-east-1') add_keys_to_bucket = upload_keys() delete_bucket = S3DeleteBucketOperator(task_id='s3_bucket_dag_delete', force_delete=True) create_bucket >> add_keys_to_bucket >> delete_bucket
true
true
f717b89a3172f1c4b9bc6e5d62033e37e8a5b95c
753
py
Python
modulos/utils.py
oliverfaustino/NRPG-DataManager
71064cb79be304f712aabcceebd6647121d2cb6c
[ "MIT" ]
null
null
null
modulos/utils.py
oliverfaustino/NRPG-DataManager
71064cb79be304f712aabcceebd6647121d2cb6c
[ "MIT" ]
null
null
null
modulos/utils.py
oliverfaustino/NRPG-DataManager
71064cb79be304f712aabcceebd6647121d2cb6c
[ "MIT" ]
null
null
null
import pyperclip import pandas as pd from modulos.conecao import * def copiar(objeto): # função para copiar os objetos para área de transferência global copiar # para resolver o porblema UnboundLocalError: local variable 'copiar' referenced before assignment: opcao = int(input('Deseja copiar para área de transferência? "1" para sim e qualquer tecla para não\n\nR: ')) if opcao == 1: copiar = pyperclip.copy(objeto) print('\nCopiado com sucesso!') else: pass return copiar def select(sql): # função que decta qual tipo de ação eu desejo fazer try: df = pd.read_sql_query(sql, con=engine).to_string(index=False) finally: pass return df
25.965517
131
0.654714
import pyperclip import pandas as pd from modulos.conecao import * def copiar(objeto): global copiar opcao = int(input('Deseja copiar para área de transferência? "1" para sim e qualquer tecla para não\n\nR: ')) if opcao == 1: copiar = pyperclip.copy(objeto) print('\nCopiado com sucesso!') else: pass return copiar def select(sql): try: df = pd.read_sql_query(sql, con=engine).to_string(index=False) finally: pass return df
true
true
f717b8e1b7a02ea373928b5f35b6948527803150
5,822
py
Python
tests/admin_views/test_templatetags.py
downstreamimpact/django
6686238cdc5c826ca5aab39d771798ff98e90ae8
[ "CNRI-Python-GPL-Compatible", "BSD-3-Clause" ]
7
2020-01-13T18:26:41.000Z
2021-04-20T04:22:26.000Z
tests/admin_views/test_templatetags.py
downstreamimpact/django
6686238cdc5c826ca5aab39d771798ff98e90ae8
[ "CNRI-Python-GPL-Compatible", "BSD-3-Clause" ]
null
null
null
tests/admin_views/test_templatetags.py
downstreamimpact/django
6686238cdc5c826ca5aab39d771798ff98e90ae8
[ "CNRI-Python-GPL-Compatible", "BSD-3-Clause" ]
4
2019-11-07T01:22:16.000Z
2020-09-16T22:02:16.000Z
import datetime from django.contrib.admin import ModelAdmin from django.contrib.admin.templatetags.admin_list import date_hierarchy from django.contrib.admin.templatetags.admin_modify import submit_row from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from django.test import RequestFactory, TestCase from django.urls import reverse from .admin import ArticleAdmin, site from .models import Article, Question from .tests import AdminViewBasicTestCase class AdminTemplateTagsTest(AdminViewBasicTestCase): request_factory = RequestFactory() def test_submit_row(self): """ submit_row template tag should pass whole context. """ request = self.request_factory.get(reverse('admin:auth_user_change', args=[self.superuser.pk])) request.user = self.superuser admin = UserAdmin(User, site) extra_context = {'extra': True} response = admin.change_view(request, str(self.superuser.pk), extra_context=extra_context) template_context = submit_row(response.context_data) self.assertIs(template_context['extra'], True) self.assertIs(template_context['show_save'], True) def test_override_show_save_and_add_another(self): request = self.request_factory.get( reverse('admin:auth_user_change', args=[self.superuser.pk]), ) request.user = self.superuser admin = UserAdmin(User, site) for extra_context, expected_flag in ( ({}, True), # Default. ({'show_save_and_add_another': False}, False), ): with self.subTest(show_save_and_add_another=expected_flag): response = admin.change_view( request, str(self.superuser.pk), extra_context=extra_context, ) template_context = submit_row(response.context_data) self.assertIs(template_context['show_save_and_add_another'], expected_flag) def test_override_change_form_template_tags(self): """ admin_modify template tags follow the standard search pattern admin/app_label/model/template.html. """ article = Article.objects.all()[0] request = self.request_factory.get(reverse('admin:admin_views_article_change', args=[article.pk])) request.user = self.superuser admin = ArticleAdmin(Article, site) extra_context = {'show_publish': True, 'extra': True} response = admin.change_view(request, str(article.pk), extra_context=extra_context) response.render() self.assertIs(response.context_data['show_publish'], True) self.assertIs(response.context_data['extra'], True) self.assertContains(response, 'name="_save"') self.assertContains(response, 'name="_publish"') self.assertContains(response, 'override-change_form_object_tools') self.assertContains(response, 'override-prepopulated_fields_js') def test_override_change_list_template_tags(self): """ admin_list template tags follow the standard search pattern admin/app_label/model/template.html. """ request = self.request_factory.get(reverse('admin:admin_views_article_changelist')) request.user = self.superuser admin = ArticleAdmin(Article, site) admin.date_hierarchy = 'date' admin.search_fields = ('title', 'content') response = admin.changelist_view(request) response.render() self.assertContains(response, 'override-actions') self.assertContains(response, 'override-change_list_object_tools') self.assertContains(response, 'override-change_list_results') self.assertContains(response, 'override-date_hierarchy') self.assertContains(response, 'override-pagination') self.assertContains(response, 'override-search_form') class DateHierarchyTests(TestCase): factory = RequestFactory() @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser(username='super', password='secret', email='super@example.com') def test_choice_links(self): modeladmin = ModelAdmin(Question, site) modeladmin.date_hierarchy = 'posted' posted_dates = ( datetime.date(2017, 10, 1), datetime.date(2017, 10, 1), datetime.date(2017, 12, 15), datetime.date(2017, 12, 15), datetime.date(2017, 12, 31), datetime.date(2018, 2, 1), ) Question.objects.bulk_create(Question(question='q', posted=posted) for posted in posted_dates) tests = ( ({}, [['year=2017'], ['year=2018']]), ({'year': 2016}, []), ({'year': 2017}, [['month=10', 'year=2017'], ['month=12', 'year=2017']]), ({'year': 2017, 'month': 9}, []), ({'year': 2017, 'month': 12}, [['day=15', 'month=12', 'year=2017'], ['day=31', 'month=12', 'year=2017']]), ) for query, expected_choices in tests: with self.subTest(query=query): query = {'posted__%s' % q: val for q, val in query.items()} request = self.factory.get('/', query) request.user = self.superuser changelist = modeladmin.get_changelist_instance(request) spec = date_hierarchy(changelist) choices = [choice['link'] for choice in spec['choices']] expected_choices = [ '&'.join('posted__%s' % c for c in choice) for choice in expected_choices ] expected_choices = [('?' + choice) if choice else '' for choice in expected_choices] self.assertEqual(choices, expected_choices)
44.442748
118
0.643422
import datetime from django.contrib.admin import ModelAdmin from django.contrib.admin.templatetags.admin_list import date_hierarchy from django.contrib.admin.templatetags.admin_modify import submit_row from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from django.test import RequestFactory, TestCase from django.urls import reverse from .admin import ArticleAdmin, site from .models import Article, Question from .tests import AdminViewBasicTestCase class AdminTemplateTagsTest(AdminViewBasicTestCase): request_factory = RequestFactory() def test_submit_row(self): request = self.request_factory.get(reverse('admin:auth_user_change', args=[self.superuser.pk])) request.user = self.superuser admin = UserAdmin(User, site) extra_context = {'extra': True} response = admin.change_view(request, str(self.superuser.pk), extra_context=extra_context) template_context = submit_row(response.context_data) self.assertIs(template_context['extra'], True) self.assertIs(template_context['show_save'], True) def test_override_show_save_and_add_another(self): request = self.request_factory.get( reverse('admin:auth_user_change', args=[self.superuser.pk]), ) request.user = self.superuser admin = UserAdmin(User, site) for extra_context, expected_flag in ( ({}, True), ({'show_save_and_add_another': False}, False), ): with self.subTest(show_save_and_add_another=expected_flag): response = admin.change_view( request, str(self.superuser.pk), extra_context=extra_context, ) template_context = submit_row(response.context_data) self.assertIs(template_context['show_save_and_add_another'], expected_flag) def test_override_change_form_template_tags(self): article = Article.objects.all()[0] request = self.request_factory.get(reverse('admin:admin_views_article_change', args=[article.pk])) request.user = self.superuser admin = ArticleAdmin(Article, site) extra_context = {'show_publish': True, 'extra': True} response = admin.change_view(request, str(article.pk), extra_context=extra_context) response.render() self.assertIs(response.context_data['show_publish'], True) self.assertIs(response.context_data['extra'], True) self.assertContains(response, 'name="_save"') self.assertContains(response, 'name="_publish"') self.assertContains(response, 'override-change_form_object_tools') self.assertContains(response, 'override-prepopulated_fields_js') def test_override_change_list_template_tags(self): request = self.request_factory.get(reverse('admin:admin_views_article_changelist')) request.user = self.superuser admin = ArticleAdmin(Article, site) admin.date_hierarchy = 'date' admin.search_fields = ('title', 'content') response = admin.changelist_view(request) response.render() self.assertContains(response, 'override-actions') self.assertContains(response, 'override-change_list_object_tools') self.assertContains(response, 'override-change_list_results') self.assertContains(response, 'override-date_hierarchy') self.assertContains(response, 'override-pagination') self.assertContains(response, 'override-search_form') class DateHierarchyTests(TestCase): factory = RequestFactory() @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser(username='super', password='secret', email='super@example.com') def test_choice_links(self): modeladmin = ModelAdmin(Question, site) modeladmin.date_hierarchy = 'posted' posted_dates = ( datetime.date(2017, 10, 1), datetime.date(2017, 10, 1), datetime.date(2017, 12, 15), datetime.date(2017, 12, 15), datetime.date(2017, 12, 31), datetime.date(2018, 2, 1), ) Question.objects.bulk_create(Question(question='q', posted=posted) for posted in posted_dates) tests = ( ({}, [['year=2017'], ['year=2018']]), ({'year': 2016}, []), ({'year': 2017}, [['month=10', 'year=2017'], ['month=12', 'year=2017']]), ({'year': 2017, 'month': 9}, []), ({'year': 2017, 'month': 12}, [['day=15', 'month=12', 'year=2017'], ['day=31', 'month=12', 'year=2017']]), ) for query, expected_choices in tests: with self.subTest(query=query): query = {'posted__%s' % q: val for q, val in query.items()} request = self.factory.get('/', query) request.user = self.superuser changelist = modeladmin.get_changelist_instance(request) spec = date_hierarchy(changelist) choices = [choice['link'] for choice in spec['choices']] expected_choices = [ '&'.join('posted__%s' % c for c in choice) for choice in expected_choices ] expected_choices = [('?' + choice) if choice else '' for choice in expected_choices] self.assertEqual(choices, expected_choices)
true
true
f717b91705d7d8a081fb14e5a9579959e466aa1f
28,392
py
Python
allennlp/models/semantic_parsing/atis/atis_semantic_parser.py
ljch2018/allennlp
63ba3fb28897578d4798039d1713e2b7995eb753
[ "Apache-2.0" ]
null
null
null
allennlp/models/semantic_parsing/atis/atis_semantic_parser.py
ljch2018/allennlp
63ba3fb28897578d4798039d1713e2b7995eb753
[ "Apache-2.0" ]
null
null
null
allennlp/models/semantic_parsing/atis/atis_semantic_parser.py
ljch2018/allennlp
63ba3fb28897578d4798039d1713e2b7995eb753
[ "Apache-2.0" ]
null
null
null
import logging from typing import Any, Dict, List, Tuple import difflib import sqlparse from overrides import overrides import torch from allennlp.common.util import pad_sequence_to_length from allennlp.data import Vocabulary from allennlp.data.fields.production_rule_field import ProductionRuleArray from allennlp.semparse.executors import SqlExecutor from allennlp.models.model import Model from allennlp.modules import Attention, Seq2SeqEncoder, TextFieldEmbedder, \ Embedding from allennlp.nn import util from allennlp.semparse.worlds import AtisWorld from allennlp.semparse.contexts.sql_context_utils import action_sequence_to_sql from allennlp.state_machines.states import GrammarBasedState from allennlp.state_machines.transition_functions.linking_transition_function import LinkingTransitionFunction from allennlp.state_machines import BeamSearch from allennlp.state_machines.trainers import MaximumMarginalLikelihood from allennlp.state_machines.states import GrammarStatelet, RnnStatelet from allennlp.training.metrics import Average logger = logging.getLogger(__name__) # pylint: disable=invalid-name @Model.register("atis_parser") class AtisSemanticParser(Model): """ Parameters ---------- vocab : ``Vocabulary`` utterance_embedder : ``TextFieldEmbedder`` Embedder for utterances. action_embedding_dim : ``int`` Dimension to use for action embeddings. encoder : ``Seq2SeqEncoder`` The encoder to use for the input utterance. decoder_beam_search : ``BeamSearch`` Beam search used to retrieve best sequences after training. max_decoding_steps : ``int`` When we're decoding with a beam search, what's the maximum number of steps we should take? This only applies at evaluation time, not during training. input_attention: ``Attention`` We compute an attention over the input utterance at each step of the decoder, using the decoder hidden state as the query. Passed to the transition function. add_action_bias : ``bool``, optional (default=True) If ``True``, we will learn a bias weight for each action that gets used when predicting that action, in addition to its embedding. dropout : ``float``, optional (default=0) If greater than 0, we will apply dropout with this probability after all encoders (pytorch LSTMs do not apply dropout to their last layer). rule_namespace : ``str``, optional (default=rule_labels) The vocabulary namespace to use for production rules. The default corresponds to the default used in the dataset reader, so you likely don't need to modify this. database_file: ``str``, optional (default=/atis/atis.db) The path of the SQLite database when evaluating SQL queries. SQLite is disk based, so we need the file location to connect to it. """ def __init__(self, vocab: Vocabulary, utterance_embedder: TextFieldEmbedder, action_embedding_dim: int, encoder: Seq2SeqEncoder, decoder_beam_search: BeamSearch, max_decoding_steps: int, input_attention: Attention, add_action_bias: bool = True, training_beam_size: int = None, dropout: float = 0.0, rule_namespace: str = 'rule_labels', database_file='/atis/atis.db') -> None: # Atis semantic parser init super().__init__(vocab) self._utterance_embedder = utterance_embedder self._encoder = encoder self._max_decoding_steps = max_decoding_steps self._add_action_bias = add_action_bias if dropout > 0: self._dropout = torch.nn.Dropout(p=dropout) else: self._dropout = lambda x: x self._rule_namespace = rule_namespace self._exact_match = Average() self._valid_sql_query = Average() self._action_similarity = Average() self._denotation_accuracy = Average() self._executor = SqlExecutor(database_file) self._action_padding_index = -1 # the padding value used by IndexField num_actions = vocab.get_vocab_size(self._rule_namespace) if self._add_action_bias: input_action_dim = action_embedding_dim + 1 else: input_action_dim = action_embedding_dim self._action_embedder = Embedding(num_embeddings=num_actions, embedding_dim=input_action_dim) self._output_action_embedder = Embedding(num_embeddings=num_actions, embedding_dim=action_embedding_dim) # This is what we pass as input in the first step of decoding, when we don't have a # previous action, or a previous utterance attention. self._first_action_embedding = torch.nn.Parameter(torch.FloatTensor(action_embedding_dim)) self._first_attended_utterance = torch.nn.Parameter(torch.FloatTensor(encoder.get_output_dim())) torch.nn.init.normal_(self._first_action_embedding) torch.nn.init.normal_(self._first_attended_utterance) self._num_entity_types = 2 # TODO(kevin): get this in a more principled way somehow? self._entity_type_decoder_embedding = Embedding(self._num_entity_types, action_embedding_dim) self._beam_search = decoder_beam_search self._decoder_trainer = MaximumMarginalLikelihood(training_beam_size) self._transition_function = LinkingTransitionFunction(encoder_output_dim=self._encoder.get_output_dim(), action_embedding_dim=action_embedding_dim, input_attention=input_attention, predict_start_type_separately=False, add_action_bias=self._add_action_bias, dropout=dropout) @overrides def forward(self, # type: ignore utterance: Dict[str, torch.LongTensor], world: List[AtisWorld], actions: List[List[ProductionRuleArray]], linking_scores: torch.Tensor, target_action_sequence: torch.LongTensor = None, sql_queries: List[List[str]] = None) -> Dict[str, torch.Tensor]: # pylint: disable=arguments-differ """ We set up the initial state for the decoder, and pass that state off to either a DecoderTrainer, if we're training, or a BeamSearch for inference, if we're not. Parameters ---------- utterance : Dict[str, torch.LongTensor] The output of ``TextField.as_array()`` applied on the utterance ``TextField``. This will be passed through a ``TextFieldEmbedder`` and then through an encoder. world : ``List[AtisWorld]`` We use a ``MetadataField`` to get the ``World`` for each input instance. Because of how ``MetadataField`` works, this gets passed to us as a ``List[AtisWorld]``, actions : ``List[List[ProductionRuleArray]]`` A list of all possible actions for each ``World`` in the batch, indexed into a ``ProductionRuleArray`` using a ``ProductionRuleField``. We will embed all of these and use the embeddings to determine which action to take at each timestep in the decoder. linking_scores: ``torch.Tensor`` A matrix of the linking the utterance tokens and the entities. This is a binary matrix that is deterministically generated where each entry indicates whether a token generated an entity. This tensor has shape ``(batch_size, num_entities, num_utterance_tokens)``. target_action_sequence : torch.Tensor, optional (default=None) The action sequence for the correct action sequence, where each action is an index into the list of possible actions. This tensor has shape ``(batch_size, sequence_length, 1)``. We remove the trailing dimension. sql_queries : List[List[str]], optional (default=None) A list of the SQL queries that are given during training or validation. """ initial_state = self._get_initial_state(utterance, world, actions, linking_scores) batch_size = linking_scores.shape[0] if target_action_sequence is not None: # Remove the trailing dimension (from ListField[ListField[IndexField]]). target_action_sequence = target_action_sequence.squeeze(-1) target_mask = target_action_sequence != self._action_padding_index else: target_mask = None if self.training: # target_action_sequence is of shape (batch_size, 1, sequence_length) here after we unsqueeze it for # the MML trainer. return self._decoder_trainer.decode(initial_state, self._transition_function, (target_action_sequence.unsqueeze(1), target_mask.unsqueeze(1))) else: # TODO(kevin) Move some of this functionality to a separate method for computing validation outputs. action_mapping = {} for batch_index, batch_actions in enumerate(actions): for action_index, action in enumerate(batch_actions): action_mapping[(batch_index, action_index)] = action[0] outputs: Dict[str, Any] = {'action_mapping': action_mapping} outputs['linking_scores'] = linking_scores if target_action_sequence is not None: outputs['loss'] = self._decoder_trainer.decode(initial_state, self._transition_function, (target_action_sequence.unsqueeze(1), target_mask.unsqueeze(1)))['loss'] num_steps = self._max_decoding_steps # This tells the state to start keeping track of debug info, which we'll pass along in # our output dictionary. initial_state.debug_info = [[] for _ in range(batch_size)] best_final_states = self._beam_search.search(num_steps, initial_state, self._transition_function, keep_final_unfinished_states=False) outputs['best_action_sequence'] = [] outputs['debug_info'] = [] outputs['entities'] = [] outputs['predicted_sql_query'] = [] outputs['sql_queries'] = [] outputs['utterance'] = [] outputs['tokenized_utterance'] = [] for i in range(batch_size): # Decoding may not have terminated with any completed valid SQL queries, if `num_steps` # isn't long enough (or if the model is not trained enough and gets into an # infinite action loop). if i not in best_final_states: self._exact_match(0) self._denotation_accuracy(0) self._valid_sql_query(0) self._action_similarity(0) outputs['predicted_sql_query'].append('') continue best_action_indices = best_final_states[i][0].action_history[0] action_strings = [action_mapping[(i, action_index)] for action_index in best_action_indices] predicted_sql_query = action_sequence_to_sql(action_strings) if target_action_sequence is not None: # Use a Tensor, not a Variable, to avoid a memory leak. targets = target_action_sequence[i].data sequence_in_targets = 0 sequence_in_targets = self._action_history_match(best_action_indices, targets) self._exact_match(sequence_in_targets) similarity = difflib.SequenceMatcher(None, best_action_indices, targets) self._action_similarity(similarity.ratio()) if sql_queries and sql_queries[i]: denotation_correct = self._executor.evaluate_sql_query(predicted_sql_query, sql_queries[i]) self._denotation_accuracy(denotation_correct) outputs['sql_queries'].append(sql_queries[i]) outputs['utterance'].append(world[i].utterances[-1]) outputs['tokenized_utterance'].append([token.text for token in world[i].tokenized_utterances[-1]]) outputs['entities'].append(world[i].entities) outputs['best_action_sequence'].append(action_strings) outputs['predicted_sql_query'].append(sqlparse.format(predicted_sql_query, reindent=True)) outputs['debug_info'].append(best_final_states[i][0].debug_info[0]) # type: ignore return outputs def _get_initial_state(self, utterance: Dict[str, torch.LongTensor], worlds: List[AtisWorld], actions: List[List[ProductionRuleArray]], linking_scores: torch.Tensor) -> GrammarBasedState: embedded_utterance = self._utterance_embedder(utterance) utterance_mask = util.get_text_field_mask(utterance).float() batch_size = embedded_utterance.size(0) num_entities = max([len(world.entities) for world in worlds]) # entity_types: tensor with shape (batch_size, num_entities) entity_types, _ = self._get_type_vector(worlds, num_entities, embedded_utterance) # (batch_size, num_utterance_tokens, embedding_dim) encoder_input = embedded_utterance # (batch_size, utterance_length, encoder_output_dim) encoder_outputs = self._dropout(self._encoder(encoder_input, utterance_mask)) # This will be our initial hidden state and memory cell for the decoder LSTM. final_encoder_output = util.get_final_encoder_states(encoder_outputs, utterance_mask, self._encoder.is_bidirectional()) memory_cell = encoder_outputs.new_zeros(batch_size, self._encoder.get_output_dim()) initial_score = embedded_utterance.data.new_zeros(batch_size) # To make grouping states together in the decoder easier, we convert the batch dimension in # all of our tensors into an outer list. For instance, the encoder outputs have shape # `(batch_size, utterance_length, encoder_output_dim)`. We need to convert this into a list # of `batch_size` tensors, each of shape `(utterance_length, encoder_output_dim)`. Then we # won't have to do any index selects, or anything, we'll just do some `torch.cat()`s. initial_score_list = [initial_score[i] for i in range(batch_size)] encoder_output_list = [encoder_outputs[i] for i in range(batch_size)] utterance_mask_list = [utterance_mask[i] for i in range(batch_size)] initial_rnn_state = [] for i in range(batch_size): initial_rnn_state.append(RnnStatelet(final_encoder_output[i], memory_cell[i], self._first_action_embedding, self._first_attended_utterance, encoder_output_list, utterance_mask_list)) initial_grammar_state = [self._create_grammar_state(worlds[i], actions[i], linking_scores[i], entity_types[i]) for i in range(batch_size)] initial_state = GrammarBasedState(batch_indices=list(range(batch_size)), action_history=[[] for _ in range(batch_size)], score=initial_score_list, rnn_state=initial_rnn_state, grammar_state=initial_grammar_state, possible_actions=actions, debug_info=None) return initial_state @staticmethod def _get_type_vector(worlds: List[AtisWorld], num_entities: int, tensor: torch.Tensor = None) -> Tuple[torch.LongTensor, Dict[int, int]]: """ Produces the encoding for each entity's type. In addition, a map from a flattened entity index to type is returned to combine entity type operations into one method. Parameters ---------- worlds : ``List[AtisWorld]`` num_entities : ``int`` tensor : ``torch.Tensor`` Used for copying the constructed list onto the right device. Returns ------- A ``torch.LongTensor`` with shape ``(batch_size, num_entities, num_types)``. entity_types : ``Dict[int, int]`` This is a mapping from ((batch_index * num_entities) + entity_index) to entity type id. """ entity_types = {} batch_types = [] for batch_index, world in enumerate(worlds): types = [] entities = [('number', entity) if 'number' or 'time_range' in entity else ('string', entity) for entity in world.entities] for entity_index, entity in enumerate(entities): # We need numbers to be first, then strings, since our entities are going to be # sorted. We do a split by type and then a merge later, and it relies on this sorting. if entity[0] == 'number': entity_type = 1 else: entity_type = 0 types.append(entity_type) # For easier lookups later, we're actually using a _flattened_ version # of (batch_index, entity_index) for the key, because this is how the # linking scores are stored. flattened_entity_index = batch_index * num_entities + entity_index entity_types[flattened_entity_index] = entity_type padded = pad_sequence_to_length(types, num_entities, lambda: 0) batch_types.append(padded) return tensor.new_tensor(batch_types, dtype=torch.long), entity_types @staticmethod def _action_history_match(predicted: List[int], targets: torch.LongTensor) -> int: # TODO(mattg): this could probably be moved into a FullSequenceMatch metric, or something. # Check if target is big enough to cover prediction (including start/end symbols) if len(predicted) > targets.size(0): return 0 predicted_tensor = targets.new_tensor(predicted) targets_trimmed = targets[:len(predicted)] # Return 1 if the predicted sequence is anywhere in the list of targets. return predicted_tensor.equal(targets_trimmed) @staticmethod def is_nonterminal(token: str): if token[0] == '"' and token[-1] == '"': return False return True @overrides def get_metrics(self, reset: bool = False) -> Dict[str, float]: """ We track four metrics here: 1. exact_match, which is the percentage of the time that our best output action sequence matches the SQL query exactly. 2. denotation_acc, which is the percentage of examples where we get the correct denotation. This is the typical "accuracy" metric, and it is what you should usually report in an experimental result. You need to be careful, though, that you're computing this on the full data, and not just the subset that can be parsed. (make sure you pass "keep_if_unparseable=True" to the dataset reader, which we do for validation data, but not training data). 3. valid_sql_query, which is the percentage of time that decoding actually produces a valid SQL query. We might not produce a valid SQL query if the decoder gets into a repetitive loop, or we're trying to produce a super long SQL query and run out of time steps, or something. 4. action_similarity, which is how similar the action sequence predicted is to the actual action sequence. This is basically a soft measure of exact_match. """ return { 'exact_match': self._exact_match.get_metric(reset), 'denotation_acc': self._denotation_accuracy.get_metric(reset), 'valid_sql_query': self._valid_sql_query.get_metric(reset), 'action_similarity': self._action_similarity.get_metric(reset) } def _create_grammar_state(self, world: AtisWorld, possible_actions: List[ProductionRuleArray], linking_scores: torch.Tensor, entity_types: torch.Tensor) -> GrammarStatelet: """ This method creates the GrammarStatelet object that's used for decoding. Part of creating that is creating the `valid_actions` dictionary, which contains embedded representations of all of the valid actions. So, we create that here as well. The inputs to this method are for a `single instance in the batch`; none of the tensors we create here are batched. We grab the global action ids from the input ``ProductionRuleArrays``, and we use those to embed the valid actions for every non-terminal type. We use the input ``linking_scores`` for non-global actions. Parameters ---------- world : ``AtisWorld`` From the input to ``forward`` for a single batch instance. possible_actions : ``List[ProductionRuleArray]`` From the input to ``forward`` for a single batch instance. linking_scores : ``torch.Tensor`` Assumed to have shape ``(num_entities, num_utterance_tokens)`` (i.e., there is no batch dimension). entity_types : ``torch.Tensor`` Assumed to have shape ``(num_entities,)`` (i.e., there is no batch dimension). """ action_map = {} for action_index, action in enumerate(possible_actions): action_string = action[0] action_map[action_string] = action_index valid_actions = world.valid_actions entity_map = {} entities = world.entities for entity_index, entity in enumerate(entities): entity_map[entity] = entity_index translated_valid_actions: Dict[str, Dict[str, Tuple[torch.Tensor, torch.Tensor, List[int]]]] = {} for key, action_strings in valid_actions.items(): translated_valid_actions[key] = {} # `key` here is a non-terminal from the grammar, and `action_strings` are all the valid # productions of that non-terminal. We'll first split those productions by global vs. # linked action. action_indices = [action_map[action_string] for action_string in action_strings] production_rule_arrays = [(possible_actions[index], index) for index in action_indices] global_actions = [] linked_actions = [] for production_rule_array, action_index in production_rule_arrays: if production_rule_array[1]: global_actions.append((production_rule_array[2], action_index)) else: linked_actions.append((production_rule_array[0], action_index)) if global_actions: global_action_tensors, global_action_ids = zip(*global_actions) global_action_tensor = entity_types.new_tensor(torch.cat(global_action_tensors, dim=0), dtype=torch.long) global_input_embeddings = self._action_embedder(global_action_tensor) global_output_embeddings = self._output_action_embedder(global_action_tensor) translated_valid_actions[key]['global'] = (global_input_embeddings, global_output_embeddings, list(global_action_ids)) if linked_actions: linked_rules, linked_action_ids = zip(*linked_actions) entities = linked_rules entity_ids = [entity_map[entity] for entity in entities] entity_linking_scores = linking_scores[entity_ids] entity_type_tensor = entity_types[entity_ids] entity_type_embeddings = self._entity_type_decoder_embedding(entity_type_tensor) entity_type_embeddings = entity_types.new_tensor(entity_type_embeddings, dtype=torch.float) translated_valid_actions[key]['linked'] = (entity_linking_scores, entity_type_embeddings, list(linked_action_ids)) return GrammarStatelet(['statement'], {}, translated_valid_actions, {}, self.is_nonterminal, reverse_productions=False) @overrides def decode(self, output_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]: """ This method overrides ``Model.decode``, which gets called after ``Model.forward``, at test time, to finalize predictions. This is (confusingly) a separate notion from the "decoder" in "encoder/decoder", where that decoder logic lives in ``TransitionFunction``. This method trims the output predictions to the first end symbol, replaces indices with corresponding tokens, and adds a field called ``predicted_actions`` to the ``output_dict``. """ action_mapping = output_dict['action_mapping'] best_actions = output_dict["best_action_sequence"] debug_infos = output_dict['debug_info'] batch_action_info = [] for batch_index, (predicted_actions, debug_info) in enumerate(zip(best_actions, debug_infos)): instance_action_info = [] for predicted_action, action_debug_info in zip(predicted_actions, debug_info): action_info = {} action_info['predicted_action'] = predicted_action considered_actions = action_debug_info['considered_actions'] probabilities = action_debug_info['probabilities'] actions = [] for action, probability in zip(considered_actions, probabilities): if action != -1: actions.append((action_mapping[(batch_index, action)], probability)) actions.sort() considered_actions, probabilities = zip(*actions) action_info['considered_actions'] = considered_actions action_info['action_probabilities'] = probabilities action_info['utterance_attention'] = action_debug_info.get('question_attention', []) instance_action_info.append(action_info) batch_action_info.append(instance_action_info) output_dict["predicted_actions"] = batch_action_info return output_dict
54.705202
112
0.61151
import logging from typing import Any, Dict, List, Tuple import difflib import sqlparse from overrides import overrides import torch from allennlp.common.util import pad_sequence_to_length from allennlp.data import Vocabulary from allennlp.data.fields.production_rule_field import ProductionRuleArray from allennlp.semparse.executors import SqlExecutor from allennlp.models.model import Model from allennlp.modules import Attention, Seq2SeqEncoder, TextFieldEmbedder, \ Embedding from allennlp.nn import util from allennlp.semparse.worlds import AtisWorld from allennlp.semparse.contexts.sql_context_utils import action_sequence_to_sql from allennlp.state_machines.states import GrammarBasedState from allennlp.state_machines.transition_functions.linking_transition_function import LinkingTransitionFunction from allennlp.state_machines import BeamSearch from allennlp.state_machines.trainers import MaximumMarginalLikelihood from allennlp.state_machines.states import GrammarStatelet, RnnStatelet from allennlp.training.metrics import Average logger = logging.getLogger(__name__) @Model.register("atis_parser") class AtisSemanticParser(Model): def __init__(self, vocab: Vocabulary, utterance_embedder: TextFieldEmbedder, action_embedding_dim: int, encoder: Seq2SeqEncoder, decoder_beam_search: BeamSearch, max_decoding_steps: int, input_attention: Attention, add_action_bias: bool = True, training_beam_size: int = None, dropout: float = 0.0, rule_namespace: str = 'rule_labels', database_file='/atis/atis.db') -> None: super().__init__(vocab) self._utterance_embedder = utterance_embedder self._encoder = encoder self._max_decoding_steps = max_decoding_steps self._add_action_bias = add_action_bias if dropout > 0: self._dropout = torch.nn.Dropout(p=dropout) else: self._dropout = lambda x: x self._rule_namespace = rule_namespace self._exact_match = Average() self._valid_sql_query = Average() self._action_similarity = Average() self._denotation_accuracy = Average() self._executor = SqlExecutor(database_file) self._action_padding_index = -1 num_actions = vocab.get_vocab_size(self._rule_namespace) if self._add_action_bias: input_action_dim = action_embedding_dim + 1 else: input_action_dim = action_embedding_dim self._action_embedder = Embedding(num_embeddings=num_actions, embedding_dim=input_action_dim) self._output_action_embedder = Embedding(num_embeddings=num_actions, embedding_dim=action_embedding_dim) # previous action, or a previous utterance attention. self._first_action_embedding = torch.nn.Parameter(torch.FloatTensor(action_embedding_dim)) self._first_attended_utterance = torch.nn.Parameter(torch.FloatTensor(encoder.get_output_dim())) torch.nn.init.normal_(self._first_action_embedding) torch.nn.init.normal_(self._first_attended_utterance) self._num_entity_types = 2 # TODO(kevin): get this in a more principled way somehow? self._entity_type_decoder_embedding = Embedding(self._num_entity_types, action_embedding_dim) self._beam_search = decoder_beam_search self._decoder_trainer = MaximumMarginalLikelihood(training_beam_size) self._transition_function = LinkingTransitionFunction(encoder_output_dim=self._encoder.get_output_dim(), action_embedding_dim=action_embedding_dim, input_attention=input_attention, predict_start_type_separately=False, add_action_bias=self._add_action_bias, dropout=dropout) @overrides def forward(self, # type: ignore utterance: Dict[str, torch.LongTensor], world: List[AtisWorld], actions: List[List[ProductionRuleArray]], linking_scores: torch.Tensor, target_action_sequence: torch.LongTensor = None, sql_queries: List[List[str]] = None) -> Dict[str, torch.Tensor]: # pylint: disable=arguments-differ initial_state = self._get_initial_state(utterance, world, actions, linking_scores) batch_size = linking_scores.shape[0] if target_action_sequence is not None: # Remove the trailing dimension (from ListField[ListField[IndexField]]). target_action_sequence = target_action_sequence.squeeze(-1) target_mask = target_action_sequence != self._action_padding_index else: target_mask = None if self.training: # target_action_sequence is of shape (batch_size, 1, sequence_length) here after we unsqueeze it for # the MML trainer. return self._decoder_trainer.decode(initial_state, self._transition_function, (target_action_sequence.unsqueeze(1), target_mask.unsqueeze(1))) else: # TODO(kevin) Move some of this functionality to a separate method for computing validation outputs. action_mapping = {} for batch_index, batch_actions in enumerate(actions): for action_index, action in enumerate(batch_actions): action_mapping[(batch_index, action_index)] = action[0] outputs: Dict[str, Any] = {'action_mapping': action_mapping} outputs['linking_scores'] = linking_scores if target_action_sequence is not None: outputs['loss'] = self._decoder_trainer.decode(initial_state, self._transition_function, (target_action_sequence.unsqueeze(1), target_mask.unsqueeze(1)))['loss'] num_steps = self._max_decoding_steps # This tells the state to start keeping track of debug info, which we'll pass along in initial_state.debug_info = [[] for _ in range(batch_size)] best_final_states = self._beam_search.search(num_steps, initial_state, self._transition_function, keep_final_unfinished_states=False) outputs['best_action_sequence'] = [] outputs['debug_info'] = [] outputs['entities'] = [] outputs['predicted_sql_query'] = [] outputs['sql_queries'] = [] outputs['utterance'] = [] outputs['tokenized_utterance'] = [] for i in range(batch_size): # infinite action loop). if i not in best_final_states: self._exact_match(0) self._denotation_accuracy(0) self._valid_sql_query(0) self._action_similarity(0) outputs['predicted_sql_query'].append('') continue best_action_indices = best_final_states[i][0].action_history[0] action_strings = [action_mapping[(i, action_index)] for action_index in best_action_indices] predicted_sql_query = action_sequence_to_sql(action_strings) if target_action_sequence is not None: # Use a Tensor, not a Variable, to avoid a memory leak. targets = target_action_sequence[i].data sequence_in_targets = 0 sequence_in_targets = self._action_history_match(best_action_indices, targets) self._exact_match(sequence_in_targets) similarity = difflib.SequenceMatcher(None, best_action_indices, targets) self._action_similarity(similarity.ratio()) if sql_queries and sql_queries[i]: denotation_correct = self._executor.evaluate_sql_query(predicted_sql_query, sql_queries[i]) self._denotation_accuracy(denotation_correct) outputs['sql_queries'].append(sql_queries[i]) outputs['utterance'].append(world[i].utterances[-1]) outputs['tokenized_utterance'].append([token.text for token in world[i].tokenized_utterances[-1]]) outputs['entities'].append(world[i].entities) outputs['best_action_sequence'].append(action_strings) outputs['predicted_sql_query'].append(sqlparse.format(predicted_sql_query, reindent=True)) outputs['debug_info'].append(best_final_states[i][0].debug_info[0]) # type: ignore return outputs def _get_initial_state(self, utterance: Dict[str, torch.LongTensor], worlds: List[AtisWorld], actions: List[List[ProductionRuleArray]], linking_scores: torch.Tensor) -> GrammarBasedState: embedded_utterance = self._utterance_embedder(utterance) utterance_mask = util.get_text_field_mask(utterance).float() batch_size = embedded_utterance.size(0) num_entities = max([len(world.entities) for world in worlds]) # entity_types: tensor with shape (batch_size, num_entities) entity_types, _ = self._get_type_vector(worlds, num_entities, embedded_utterance) # (batch_size, num_utterance_tokens, embedding_dim) encoder_input = embedded_utterance # (batch_size, utterance_length, encoder_output_dim) encoder_outputs = self._dropout(self._encoder(encoder_input, utterance_mask)) # This will be our initial hidden state and memory cell for the decoder LSTM. final_encoder_output = util.get_final_encoder_states(encoder_outputs, utterance_mask, self._encoder.is_bidirectional()) memory_cell = encoder_outputs.new_zeros(batch_size, self._encoder.get_output_dim()) initial_score = embedded_utterance.data.new_zeros(batch_size) # To make grouping states together in the decoder easier, we convert the batch dimension in # all of our tensors into an outer list. For instance, the encoder outputs have shape # `(batch_size, utterance_length, encoder_output_dim)`. We need to convert this into a list # of `batch_size` tensors, each of shape `(utterance_length, encoder_output_dim)`. Then we # won't have to do any index selects, or anything, we'll just do some `torch.cat()`s. initial_score_list = [initial_score[i] for i in range(batch_size)] encoder_output_list = [encoder_outputs[i] for i in range(batch_size)] utterance_mask_list = [utterance_mask[i] for i in range(batch_size)] initial_rnn_state = [] for i in range(batch_size): initial_rnn_state.append(RnnStatelet(final_encoder_output[i], memory_cell[i], self._first_action_embedding, self._first_attended_utterance, encoder_output_list, utterance_mask_list)) initial_grammar_state = [self._create_grammar_state(worlds[i], actions[i], linking_scores[i], entity_types[i]) for i in range(batch_size)] initial_state = GrammarBasedState(batch_indices=list(range(batch_size)), action_history=[[] for _ in range(batch_size)], score=initial_score_list, rnn_state=initial_rnn_state, grammar_state=initial_grammar_state, possible_actions=actions, debug_info=None) return initial_state @staticmethod def _get_type_vector(worlds: List[AtisWorld], num_entities: int, tensor: torch.Tensor = None) -> Tuple[torch.LongTensor, Dict[int, int]]: entity_types = {} batch_types = [] for batch_index, world in enumerate(worlds): types = [] entities = [('number', entity) if 'number' or 'time_range' in entity else ('string', entity) for entity in world.entities] for entity_index, entity in enumerate(entities): # We need numbers to be first, then strings, since our entities are going to be # sorted. We do a split by type and then a merge later, and it relies on this sorting. if entity[0] == 'number': entity_type = 1 else: entity_type = 0 types.append(entity_type) # For easier lookups later, we're actually using a _flattened_ version flattened_entity_index = batch_index * num_entities + entity_index entity_types[flattened_entity_index] = entity_type padded = pad_sequence_to_length(types, num_entities, lambda: 0) batch_types.append(padded) return tensor.new_tensor(batch_types, dtype=torch.long), entity_types @staticmethod def _action_history_match(predicted: List[int], targets: torch.LongTensor) -> int: if len(predicted) > targets.size(0): return 0 predicted_tensor = targets.new_tensor(predicted) targets_trimmed = targets[:len(predicted)] return predicted_tensor.equal(targets_trimmed) @staticmethod def is_nonterminal(token: str): if token[0] == '"' and token[-1] == '"': return False return True @overrides def get_metrics(self, reset: bool = False) -> Dict[str, float]: return { 'exact_match': self._exact_match.get_metric(reset), 'denotation_acc': self._denotation_accuracy.get_metric(reset), 'valid_sql_query': self._valid_sql_query.get_metric(reset), 'action_similarity': self._action_similarity.get_metric(reset) } def _create_grammar_state(self, world: AtisWorld, possible_actions: List[ProductionRuleArray], linking_scores: torch.Tensor, entity_types: torch.Tensor) -> GrammarStatelet: action_map = {} for action_index, action in enumerate(possible_actions): action_string = action[0] action_map[action_string] = action_index valid_actions = world.valid_actions entity_map = {} entities = world.entities for entity_index, entity in enumerate(entities): entity_map[entity] = entity_index translated_valid_actions: Dict[str, Dict[str, Tuple[torch.Tensor, torch.Tensor, List[int]]]] = {} for key, action_strings in valid_actions.items(): translated_valid_actions[key] = {} # linked action. action_indices = [action_map[action_string] for action_string in action_strings] production_rule_arrays = [(possible_actions[index], index) for index in action_indices] global_actions = [] linked_actions = [] for production_rule_array, action_index in production_rule_arrays: if production_rule_array[1]: global_actions.append((production_rule_array[2], action_index)) else: linked_actions.append((production_rule_array[0], action_index)) if global_actions: global_action_tensors, global_action_ids = zip(*global_actions) global_action_tensor = entity_types.new_tensor(torch.cat(global_action_tensors, dim=0), dtype=torch.long) global_input_embeddings = self._action_embedder(global_action_tensor) global_output_embeddings = self._output_action_embedder(global_action_tensor) translated_valid_actions[key]['global'] = (global_input_embeddings, global_output_embeddings, list(global_action_ids)) if linked_actions: linked_rules, linked_action_ids = zip(*linked_actions) entities = linked_rules entity_ids = [entity_map[entity] for entity in entities] entity_linking_scores = linking_scores[entity_ids] entity_type_tensor = entity_types[entity_ids] entity_type_embeddings = self._entity_type_decoder_embedding(entity_type_tensor) entity_type_embeddings = entity_types.new_tensor(entity_type_embeddings, dtype=torch.float) translated_valid_actions[key]['linked'] = (entity_linking_scores, entity_type_embeddings, list(linked_action_ids)) return GrammarStatelet(['statement'], {}, translated_valid_actions, {}, self.is_nonterminal, reverse_productions=False) @overrides def decode(self, output_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]: action_mapping = output_dict['action_mapping'] best_actions = output_dict["best_action_sequence"] debug_infos = output_dict['debug_info'] batch_action_info = [] for batch_index, (predicted_actions, debug_info) in enumerate(zip(best_actions, debug_infos)): instance_action_info = [] for predicted_action, action_debug_info in zip(predicted_actions, debug_info): action_info = {} action_info['predicted_action'] = predicted_action considered_actions = action_debug_info['considered_actions'] probabilities = action_debug_info['probabilities'] actions = [] for action, probability in zip(considered_actions, probabilities): if action != -1: actions.append((action_mapping[(batch_index, action)], probability)) actions.sort() considered_actions, probabilities = zip(*actions) action_info['considered_actions'] = considered_actions action_info['action_probabilities'] = probabilities action_info['utterance_attention'] = action_debug_info.get('question_attention', []) instance_action_info.append(action_info) batch_action_info.append(instance_action_info) output_dict["predicted_actions"] = batch_action_info return output_dict
true
true
f717ba6db19fac8fe6c6bc3c5388211b577e2db4
871
py
Python
tests/unit/fake_data_root/kubernetes/var/lib/juju/agents/unit-containerd-2/charm/hooks/relations/untrusted-container-runtime/requires.py
KellenRenshaw/hotsos
e3fc51ab7f8af606a5846a3486a7fda23d761583
[ "Apache-2.0" ]
6
2021-10-01T19:46:14.000Z
2022-03-31T17:05:08.000Z
tests/unit/fake_data_root/kubernetes/var/lib/juju/agents/unit-containerd-2/charm/hooks/relations/untrusted-container-runtime/requires.py
KellenRenshaw/hotsos
e3fc51ab7f8af606a5846a3486a7fda23d761583
[ "Apache-2.0" ]
111
2021-10-01T18:18:17.000Z
2022-03-29T12:23:20.000Z
tests/unit/fake_data_root/kubernetes/var/lib/juju/agents/unit-containerd-2/charm/hooks/relations/untrusted-container-runtime/requires.py
KellenRenshaw/hotsos
e3fc51ab7f8af606a5846a3486a7fda23d761583
[ "Apache-2.0" ]
10
2021-09-29T14:47:54.000Z
2022-03-18T14:52:16.000Z
from charms.reactive import ( Endpoint, set_flag, clear_flag ) from charms.reactive import ( when, when_not ) class ContainerRuntimeRequires(Endpoint): @when('endpoint.{endpoint_name}.changed') def changed(self): set_flag(self.expand_name('endpoint.{endpoint_name}.available')) @when_not('endpoint.{endpoint_name}.joined') def broken(self): clear_flag(self.expand_name('endpoint.{endpoint_name}.available')) def set_config(self, name, binary_path): """ Set the configuration to be published. :param name: String name of runtime :param binary_path: String runtime executable :return: None """ for relation in self.relations: relation.to_publish.update({ 'name': name, 'binary_path': binary_path })
24.885714
74
0.626866
from charms.reactive import ( Endpoint, set_flag, clear_flag ) from charms.reactive import ( when, when_not ) class ContainerRuntimeRequires(Endpoint): @when('endpoint.{endpoint_name}.changed') def changed(self): set_flag(self.expand_name('endpoint.{endpoint_name}.available')) @when_not('endpoint.{endpoint_name}.joined') def broken(self): clear_flag(self.expand_name('endpoint.{endpoint_name}.available')) def set_config(self, name, binary_path): for relation in self.relations: relation.to_publish.update({ 'name': name, 'binary_path': binary_path })
true
true
f717ba7e0a6e1a58c6c5756909c027da10c010bb
878
py
Python
read_exif.py
kiyoon/camera-tools
2e269141597dd27ec7d41e49285e01ef566cb54c
[ "MIT" ]
1
2021-11-14T23:30:47.000Z
2021-11-14T23:30:47.000Z
read_exif.py
kiyoon/camera-tools
2e269141597dd27ec7d41e49285e01ef566cb54c
[ "MIT" ]
null
null
null
read_exif.py
kiyoon/camera-tools
2e269141597dd27ec7d41e49285e01ef566cb54c
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 import argparse class Formatter(argparse.ArgumentDefaultsHelpFormatter, argparse.RawDescriptionHelpFormatter): pass parser = argparse.ArgumentParser( description='''Read EXIF data Author: Kiyoon Kim (yoonkr33@gmail.com)''', formatter_class=Formatter) parser.add_argument('input_files', type=str, nargs='+', help='files to read metadata') args = parser.parse_args() import glob import os import exiftool import pprint if __name__ == "__main__": for origpath in args.input_files: for path in glob.glob(origpath): # glob: Windows wildcard support root, fname_ext = os.path.split(path) fname, fext = os.path.splitext(fname_ext) with exiftool.ExifTool() as et: metadata = et.get_metadata(path) print(path) pprint.pprint(metadata)
24.388889
94
0.671982
import argparse class Formatter(argparse.ArgumentDefaultsHelpFormatter, argparse.RawDescriptionHelpFormatter): pass parser = argparse.ArgumentParser( description='''Read EXIF data Author: Kiyoon Kim (yoonkr33@gmail.com)''', formatter_class=Formatter) parser.add_argument('input_files', type=str, nargs='+', help='files to read metadata') args = parser.parse_args() import glob import os import exiftool import pprint if __name__ == "__main__": for origpath in args.input_files: for path in glob.glob(origpath): root, fname_ext = os.path.split(path) fname, fext = os.path.splitext(fname_ext) with exiftool.ExifTool() as et: metadata = et.get_metadata(path) print(path) pprint.pprint(metadata)
true
true
f717bcdd89a1615aae5c49e9f6e2cbe27aa71630
458
py
Python
ProjectShop/ProductApp/urls.py
kolyasalubov/ProjectShop
41a62d27276542bf65aab51663220ffe88858024
[ "MIT" ]
3
2021-08-30T09:15:52.000Z
2022-03-24T14:40:11.000Z
ProjectShop/ProductApp/urls.py
kolyasalubov/ProjectShop
41a62d27276542bf65aab51663220ffe88858024
[ "MIT" ]
150
2021-08-30T12:37:17.000Z
2021-11-17T07:09:19.000Z
ProjectShop/ProductApp/urls.py
kolyasalubov/ProjectShop
41a62d27276542bf65aab51663220ffe88858024
[ "MIT" ]
null
null
null
from django.urls import path from ProductApp.views import ( HomePageView, CategoriesView, ProductDetailView, CategoryDetailView, ) urlpatterns = [ path("categories/<slug:slug>/", CategoryDetailView.as_view(), name="category-detail"), path("categories/", CategoriesView.as_view(), name="categories"), path("<slug:slug>/", ProductDetailView.as_view(), name="product-detail"), path("", HomePageView.as_view(), name="home"), ]
26.941176
90
0.696507
from django.urls import path from ProductApp.views import ( HomePageView, CategoriesView, ProductDetailView, CategoryDetailView, ) urlpatterns = [ path("categories/<slug:slug>/", CategoryDetailView.as_view(), name="category-detail"), path("categories/", CategoriesView.as_view(), name="categories"), path("<slug:slug>/", ProductDetailView.as_view(), name="product-detail"), path("", HomePageView.as_view(), name="home"), ]
true
true
f717bdb31e80489aaefa7fbd595c263379b27f37
15,376
py
Python
src/hub/dataload/sources/chembl/chembl_upload.py
ravila4/mychem.info
9b63b5f0957b5e7b252ca8122734a363905036b3
[ "Apache-2.0" ]
null
null
null
src/hub/dataload/sources/chembl/chembl_upload.py
ravila4/mychem.info
9b63b5f0957b5e7b252ca8122734a363905036b3
[ "Apache-2.0" ]
null
null
null
src/hub/dataload/sources/chembl/chembl_upload.py
ravila4/mychem.info
9b63b5f0957b5e7b252ca8122734a363905036b3
[ "Apache-2.0" ]
null
null
null
""" Chembl uploader """ # pylint: disable=E0401, E0611 import os import glob import pymongo import biothings.hub.dataload.storage as storage from biothings.hub.dataload.uploader import ParallelizedSourceUploader from hub.dataload.uploader import BaseDrugUploader from hub.datatransform.keylookup import MyChemKeyLookup from .chembl_parser import load_data SRC_META = { "url": 'https://www.ebi.ac.uk/chembl/', "license_url" : "https://www.ebi.ac.uk/about/terms-of-use", "license_url_short" : "http://bit.ly/2KAUCAm" } class ChemblUploader(BaseDrugUploader, ParallelizedSourceUploader): """ ChemblUploader - upload the Chembl data source """ name = "chembl" storage_class = storage.RootKeyMergerStorage __metadata__ = {"src_meta" : SRC_META} MOLECULE_PATTERN = "molecule.*.json" keylookup = MyChemKeyLookup( [("inchikey", "chembl.inchi_key"), ("inchi", "chembl.inchi"), ("chembl", "chembl.molecule_chembl_id"), ("chebi", "chembl.chebi_par_id"), ("drugcentral", "chembl.xrefs.drugcentral.id"), ("drugname", "chembl.pref_name")], # TODO: handle duplicate keys from pubchem # - we use RootKeyMergerStorage, but the num. duplicates # - is too high (>10000) # ("pubchem", "chembl.xrefs.pubchem.sid"), copy_from_doc=True) def jobs(self): """ this will generate arguments for self.load.data() method, allowing parallelization """ json_files = glob.glob(os.path.join(self.data_folder, self.__class__.MOLECULE_PATTERN)) return [(f,) for f in json_files] def load_data(self, data_folder): """load data from an input file""" self.logger.info("Load data from '%s'" % data_folder) return self.keylookup(load_data, debug=True)(data_folder) def post_update_data(self, *args, **kwargs): """create indexes following an update""" # pylint: disable=W0613 """ for idxname in ["chembl.chebi_par_id", "chembl.inchi", "chembl.molecule_chembl_id"]: self.logger.info("Indexing '%s'" % idxname) # background=true or it'll lock the whole database... self.collection.create_index(idxname, background=True) """ for idxname in ["chembl.chebi_par_id", "chembl.molecule_chembl_id"]: self.logger.info("Indexing '%s'" % idxname) # background=true or it'll lock the whole database... self.collection.create_index(idxname, background=True) @classmethod def get_mapping(cls): """return mapping data""" mapping = { "chembl": { "properties": { "biotherapeutic": { "properties": { "helm_notation": { "normalizer": "keyword_lowercase_normalizer", "type": "keyword", }, "description": { "type": "text" }, "biocomponents": { "properties": { "organism": { "type": "text" }, "tax_id": { "type": "integer" }, "sequence": { "type": "text" }, "component_id": { "type": "integer" }, "description": { "type": "text" }, "component_type": { "normalizer": "keyword_lowercase_normalizer", "type": "keyword", } } }, "molecule_chembl_id": { "normalizer": "keyword_lowercase_normalizer", "type": "keyword", 'copy_to': ['all'], } } }, "therapeutic_flag": { "type": "boolean" }, "usan_stem": { "type": "text" }, "molecule_chembl_id": { "normalizer": "keyword_lowercase_normalizer", "type": "keyword", }, "molecule_properties": { "properties": { "heavy_atoms": { "type": "integer" }, "acd_most_bpka": { "type": "float" }, "mw_freebase": { "type": "float" }, "num_ro5_violations": { "type": "integer" }, "molecular_species": { "normalizer": "keyword_lowercase_normalizer", "type": "keyword", }, "qed_weighted": { "type": "float" }, "ro3_pass": { "type": "boolean" }, "full_mwt": { "type": "float" }, "num_lipinski_ro5_violations": { "type": "integer" }, "rtb": { "type": "integer" }, "psa": { "type": "float" }, "alogp": { "type": "float" }, "hbd": { "type": "integer" }, "acd_most_apka": { "type": "float" }, "hbd_lipinski": { "type": "integer" }, "acd_logp": { "type": "float" }, "full_molformula": { "normalizer": "keyword_lowercase_normalizer", "type": "keyword", }, "aromatic_rings": { "type": "integer" }, "hba_lipinski": { "type": "integer" }, "mw_monoisotopic": { "type": "float" }, "hba": { "type": "integer" }, "acd_logd": { "type": "float" } } }, "helm_notation": { "normalizer": "keyword_lowercase_normalizer", "type": "keyword", }, "max_phase": { "type": "integer" }, "inorganic_flag": { "type": "integer" }, "usan_stem_definition": { "type": "text" }, "dosed_ingredient": { "type": "boolean" }, "chebi_par_id": { "normalizer": "keyword_lowercase_normalizer", "type": "keyword", }, "withdrawn_reason": { "type": "text" }, "molecule_hierarchy": { "properties": { "parent_chembl_id": { "normalizer": "keyword_lowercase_normalizer", "type": "keyword", }, "molecule_chembl_id": { "normalizer": "keyword_lowercase_normalizer", "type": "keyword", } } }, "prodrug": { "type": "integer" }, "withdrawn_flag": { "type": "boolean" }, "usan_year": { "type": "integer" }, "parenteral": { "type": "boolean" }, "black_box_warning": { "type": "integer" }, "polymer_flag": { "type": "boolean" }, "molecule_synonyms": { "properties": { "molecule_synonym": { "type": "text" }, "synonyms": { "type": "text" }, "syn_type": { "normalizer": "keyword_lowercase_normalizer", "type": "keyword", } } }, "atc_classifications": { "normalizer": "keyword_lowercase_normalizer", "type": "keyword", }, "molecule_type": { "type": "text" }, "first_in_class": { "type": "integer" }, "inchi": { "normalizer": "keyword_lowercase_normalizer", "type": "keyword", }, "structure_type": { "normalizer": "keyword_lowercase_normalizer", "type": "keyword", }, "withdrawn_class": { "type": "text" }, "inchi_key": { "normalizer": "keyword_lowercase_normalizer", "type": "keyword", }, "topical": { "type": "boolean" }, "oral": { "type": "boolean" }, "xrefs": { "properties": { "drugcentral": { "properties": { "id": { "type": "integer" }, "name": { "type": "text" } } }, "tg-gates": { "properties": { "id": { "type": "integer" }, "name": { "type": "text" } } }, "wikipedia": { "properties": { "url_stub": { "normalizer": "keyword_lowercase_normalizer", "type": "keyword", } } }, "dailymed": { "properties": { "name": { "type": "text" } } }, "pubchem": { "properties": { "sid": { "type": "integer" } } } } }, "chirality": { "type": "integer" }, "usan_substem": { "type": "text" }, "indication_class": { "type": "text" }, "withdrawn_country": { "type": "text" }, "withdrawn_year": { "type": "integer" }, "availability_type": { "type": "integer" }, "smiles": { "normalizer": "keyword_lowercase_normalizer", "type": "keyword", }, "natural_product": { "type": "integer" }, "pref_name": { "type": "text", "copy_to": ["all"] }, "first_approval": { "type": "integer" } } } } return mapping
40.569921
95
0.280437
import os import glob import pymongo import biothings.hub.dataload.storage as storage from biothings.hub.dataload.uploader import ParallelizedSourceUploader from hub.dataload.uploader import BaseDrugUploader from hub.datatransform.keylookup import MyChemKeyLookup from .chembl_parser import load_data SRC_META = { "url": 'https://www.ebi.ac.uk/chembl/', "license_url" : "https://www.ebi.ac.uk/about/terms-of-use", "license_url_short" : "http://bit.ly/2KAUCAm" } class ChemblUploader(BaseDrugUploader, ParallelizedSourceUploader): name = "chembl" storage_class = storage.RootKeyMergerStorage __metadata__ = {"src_meta" : SRC_META} MOLECULE_PATTERN = "molecule.*.json" keylookup = MyChemKeyLookup( [("inchikey", "chembl.inchi_key"), ("inchi", "chembl.inchi"), ("chembl", "chembl.molecule_chembl_id"), ("chebi", "chembl.chebi_par_id"), ("drugcentral", "chembl.xrefs.drugcentral.id"), ("drugname", "chembl.pref_name")], copy_from_doc=True) def jobs(self): json_files = glob.glob(os.path.join(self.data_folder, self.__class__.MOLECULE_PATTERN)) return [(f,) for f in json_files] def load_data(self, data_folder): self.logger.info("Load data from '%s'" % data_folder) return self.keylookup(load_data, debug=True)(data_folder) def post_update_data(self, *args, **kwargs): for idxname in ["chembl.chebi_par_id", "chembl.molecule_chembl_id"]: self.logger.info("Indexing '%s'" % idxname) self.collection.create_index(idxname, background=True) @classmethod def get_mapping(cls): mapping = { "chembl": { "properties": { "biotherapeutic": { "properties": { "helm_notation": { "normalizer": "keyword_lowercase_normalizer", "type": "keyword", }, "description": { "type": "text" }, "biocomponents": { "properties": { "organism": { "type": "text" }, "tax_id": { "type": "integer" }, "sequence": { "type": "text" }, "component_id": { "type": "integer" }, "description": { "type": "text" }, "component_type": { "normalizer": "keyword_lowercase_normalizer", "type": "keyword", } } }, "molecule_chembl_id": { "normalizer": "keyword_lowercase_normalizer", "type": "keyword", 'copy_to': ['all'], } } }, "therapeutic_flag": { "type": "boolean" }, "usan_stem": { "type": "text" }, "molecule_chembl_id": { "normalizer": "keyword_lowercase_normalizer", "type": "keyword", }, "molecule_properties": { "properties": { "heavy_atoms": { "type": "integer" }, "acd_most_bpka": { "type": "float" }, "mw_freebase": { "type": "float" }, "num_ro5_violations": { "type": "integer" }, "molecular_species": { "normalizer": "keyword_lowercase_normalizer", "type": "keyword", }, "qed_weighted": { "type": "float" }, "ro3_pass": { "type": "boolean" }, "full_mwt": { "type": "float" }, "num_lipinski_ro5_violations": { "type": "integer" }, "rtb": { "type": "integer" }, "psa": { "type": "float" }, "alogp": { "type": "float" }, "hbd": { "type": "integer" }, "acd_most_apka": { "type": "float" }, "hbd_lipinski": { "type": "integer" }, "acd_logp": { "type": "float" }, "full_molformula": { "normalizer": "keyword_lowercase_normalizer", "type": "keyword", }, "aromatic_rings": { "type": "integer" }, "hba_lipinski": { "type": "integer" }, "mw_monoisotopic": { "type": "float" }, "hba": { "type": "integer" }, "acd_logd": { "type": "float" } } }, "helm_notation": { "normalizer": "keyword_lowercase_normalizer", "type": "keyword", }, "max_phase": { "type": "integer" }, "inorganic_flag": { "type": "integer" }, "usan_stem_definition": { "type": "text" }, "dosed_ingredient": { "type": "boolean" }, "chebi_par_id": { "normalizer": "keyword_lowercase_normalizer", "type": "keyword", }, "withdrawn_reason": { "type": "text" }, "molecule_hierarchy": { "properties": { "parent_chembl_id": { "normalizer": "keyword_lowercase_normalizer", "type": "keyword", }, "molecule_chembl_id": { "normalizer": "keyword_lowercase_normalizer", "type": "keyword", } } }, "prodrug": { "type": "integer" }, "withdrawn_flag": { "type": "boolean" }, "usan_year": { "type": "integer" }, "parenteral": { "type": "boolean" }, "black_box_warning": { "type": "integer" }, "polymer_flag": { "type": "boolean" }, "molecule_synonyms": { "properties": { "molecule_synonym": { "type": "text" }, "synonyms": { "type": "text" }, "syn_type": { "normalizer": "keyword_lowercase_normalizer", "type": "keyword", } } }, "atc_classifications": { "normalizer": "keyword_lowercase_normalizer", "type": "keyword", }, "molecule_type": { "type": "text" }, "first_in_class": { "type": "integer" }, "inchi": { "normalizer": "keyword_lowercase_normalizer", "type": "keyword", }, "structure_type": { "normalizer": "keyword_lowercase_normalizer", "type": "keyword", }, "withdrawn_class": { "type": "text" }, "inchi_key": { "normalizer": "keyword_lowercase_normalizer", "type": "keyword", }, "topical": { "type": "boolean" }, "oral": { "type": "boolean" }, "xrefs": { "properties": { "drugcentral": { "properties": { "id": { "type": "integer" }, "name": { "type": "text" } } }, "tg-gates": { "properties": { "id": { "type": "integer" }, "name": { "type": "text" } } }, "wikipedia": { "properties": { "url_stub": { "normalizer": "keyword_lowercase_normalizer", "type": "keyword", } } }, "dailymed": { "properties": { "name": { "type": "text" } } }, "pubchem": { "properties": { "sid": { "type": "integer" } } } } }, "chirality": { "type": "integer" }, "usan_substem": { "type": "text" }, "indication_class": { "type": "text" }, "withdrawn_country": { "type": "text" }, "withdrawn_year": { "type": "integer" }, "availability_type": { "type": "integer" }, "smiles": { "normalizer": "keyword_lowercase_normalizer", "type": "keyword", }, "natural_product": { "type": "integer" }, "pref_name": { "type": "text", "copy_to": ["all"] }, "first_approval": { "type": "integer" } } } } return mapping
true
true
f717bdc2664f609c84cf83efbdea10b954fadfe4
2,307
py
Python
tools/test_cate_attr_predictor.py
engahmed1190/mmfashion
34ba2d8a9f2daadb4a04d24287664cebde4b14f9
[ "Apache-2.0" ]
6
2021-02-04T06:25:28.000Z
2021-07-16T05:49:13.000Z
tools/test_cate_attr_predictor.py
engahmed1190/mmfashion
34ba2d8a9f2daadb4a04d24287664cebde4b14f9
[ "Apache-2.0" ]
null
null
null
tools/test_cate_attr_predictor.py
engahmed1190/mmfashion
34ba2d8a9f2daadb4a04d24287664cebde4b14f9
[ "Apache-2.0" ]
2
2021-07-16T19:27:20.000Z
2021-12-15T09:52:54.000Z
from __future__ import division import argparse from mmcv import Config from mmcv.runner import load_checkpoint from mmfashion.apis import get_root_logger, init_dist, test_cate_attr_predictor from mmfashion.datasets.utils import get_dataset from mmfashion.models import build_predictor def parse_args(): parser = argparse.ArgumentParser( description='Test a Fashion Attribute Predictor') parser.add_argument( '--config', help='test config file path', default='configs/category_attribute_predict/roi_predictor_vgg.py') parser.add_argument('--work_dir', help='the dir to save logs and models') parser.add_argument( '--checkpoint', help='checkpoint file', default='checkpoint/CateAttrPredict/vgg/roi/epoch_40.pth') parser.add_argument( '--validate', action='store_true', help='whether to evaluate the checkpoint during training', default=True) parser.add_argument( '--launcher', choices=['none', 'pytorch', 'mpi', 'slurm'], default='none', help='job launcher') args = parser.parse_args() return args def main(): args = parse_args() cfg = Config.fromfile(args.config) if args.work_dir is not None: cfg.work_dir = args.work_dir if args.checkpoint is not None: cfg.load_from = args.checkpoint # init distributed env first if args.launcher == 'none': distributed = False else: distributed = True init_dist(args.launcher, **cfg.dist_params) # init logger logger = get_root_logger(cfg.log_level) logger.info('Distributed test: {}'.format(distributed)) # data loader dataset = get_dataset(cfg.data.test) print('dataset loaded') # build model and load checkpoint model = build_predictor(cfg.model) print('model built') load_checkpoint(model, cfg.load_from, map_location='cpu') print('load checkpoint from: {}'.format(cfg.load_from)) # test test_cate_attr_predictor(model, dataset, cfg, distributed=distributed, validate=args.validate, logger=logger) if __name__ == '__main__': main()
29.576923
79
0.638058
from __future__ import division import argparse from mmcv import Config from mmcv.runner import load_checkpoint from mmfashion.apis import get_root_logger, init_dist, test_cate_attr_predictor from mmfashion.datasets.utils import get_dataset from mmfashion.models import build_predictor def parse_args(): parser = argparse.ArgumentParser( description='Test a Fashion Attribute Predictor') parser.add_argument( '--config', help='test config file path', default='configs/category_attribute_predict/roi_predictor_vgg.py') parser.add_argument('--work_dir', help='the dir to save logs and models') parser.add_argument( '--checkpoint', help='checkpoint file', default='checkpoint/CateAttrPredict/vgg/roi/epoch_40.pth') parser.add_argument( '--validate', action='store_true', help='whether to evaluate the checkpoint during training', default=True) parser.add_argument( '--launcher', choices=['none', 'pytorch', 'mpi', 'slurm'], default='none', help='job launcher') args = parser.parse_args() return args def main(): args = parse_args() cfg = Config.fromfile(args.config) if args.work_dir is not None: cfg.work_dir = args.work_dir if args.checkpoint is not None: cfg.load_from = args.checkpoint if args.launcher == 'none': distributed = False else: distributed = True init_dist(args.launcher, **cfg.dist_params) logger = get_root_logger(cfg.log_level) logger.info('Distributed test: {}'.format(distributed)) dataset = get_dataset(cfg.data.test) print('dataset loaded') model = build_predictor(cfg.model) print('model built') load_checkpoint(model, cfg.load_from, map_location='cpu') print('load checkpoint from: {}'.format(cfg.load_from)) test_cate_attr_predictor(model, dataset, cfg, distributed=distributed, validate=args.validate, logger=logger) if __name__ == '__main__': main()
true
true
f717bedbafbc1c240de6e34e3435337fe00e3c60
4,260
py
Python
app/interfaces/Rubric.py
u8sand/FAIRshake
8f6f3dde42de29b88e9a43bdd43f848382e3bad7
[ "Apache-2.0" ]
null
null
null
app/interfaces/Rubric.py
u8sand/FAIRshake
8f6f3dde42de29b88e9a43bdd43f848382e3bad7
[ "Apache-2.0" ]
8
2018-06-05T17:01:43.000Z
2018-06-22T01:19:39.000Z
app/interfaces/Rubric.py
u8sand/FAIRshake
8f6f3dde42de29b88e9a43bdd43f848382e3bad7
[ "Apache-2.0" ]
1
2018-06-06T17:22:28.000Z
2018-06-06T17:22:28.000Z
from ..ioc import interface, model from ..types import HTTPResponse, UUID, Timestamp, Optional, List from ..util.generate_spec import generate_spec @model class CriterionModel: ''' type: object required: - user - name properties: id: type: string description: Criterion ID example: d290f1ee-6c54-4b01-90e6-d701748f0851 name: type: string description: Criterion being evaluated example: Coolness kind: type: string description: Value type of the criterion example: number ''' id: UUID name: str kind: str @model class RubricModel: ''' type: object description: An rubric for evaluating a digital object required: - user - name properties: id: type: string format: uuid description: ID of rubric example: d290f1ee-6c54-4b01-90e6-d701748f0851 user: type: string format: uuid description: ID of user who made the rubric example: d290f1ee-6c54-4b01-90e6-d701748f0851 name: type: string description: Name of the rubric example: Best Rubric criteria: type: array items: $ref: "#/definitions/Criterion" description: type: string description: Description of the rubric example: My favorite rubric tags: type: array items: type: string example: tool timestamp: type: string description: When the rubric was made format: dateTime example: '2018-05-20T15:59:59-08:00' ''' id: UUID user: UUID name: str criteria: List[CriterionModel] description: Optional[str] = None tags: Optional[List[str]] = None timestamp: Optional[Timestamp] = None @interface class RubricAPI: ''' swagger: '2.0' info: title: FAIRshakeRubric version: 1.0.0 description: A generic FAIRshake Rubric REST API for storing questions to be answered. contact: email: daniel.clarke@mssm.edu license: name: Apache 2.0 url: http://www.apache.org/licenses/LICENSE-2.0.html schemes: - https securityDefinitions: ApiKeyAuth: type: apiKey in: header name: X-API-Key paths: /: get: {RubricAPI__get} post: {RubricAPI__post} definitions: Criterion: {CriterionModel} Rubric: {RubricModel} ''' @staticmethod def get( id: Optional[UUID] = None, user: Optional[UUID] = None, object: Optional[UUID] = None, timestamp: Optional[Timestamp] = None, skip: Optional[int] = None, limit: Optional[int] = None, ) -> HTTPResponse[List[RubricModel]]: ''' summary: Query rubrics consumes: - application/json parameters: - name: id in: query description: Unique rubric identifier type: string format: uuid - name: user in: query description: Unique user identifier - name: object in: query description: Unique digital object identifier type: string format: uuid - name: timestamp in: query description: Updated at least since timestamp type: string format: dateTime - name: skip in: query description: Start index for limited results type: number - name: limit in: query description: Limit number of results type: number produces: - application/json responses: 200: description: Rubrics as json schema: type: array items: $ref: "#/definitions/Rubric" 404: description: Rubrics not found ''' raise NotImplemented @staticmethod def post( body: RubricModel ) -> HTTPResponse[None]: ''' summary: Submit rubric consumes: - application/json security: - ApiKeyAuth: [] parameters: - name: body in: body schema: $ref: "#/definitions/Rubric" produces: - application/json responses: 201: description: Rubric successfully made 400: description: Parameters invalid 500: description: Permission denied, not authenticated ''' raise NotImplemented RubricSpec = generate_spec(RubricAPI, [RubricModel, CriterionModel])
22.303665
90
0.621831
from ..ioc import interface, model from ..types import HTTPResponse, UUID, Timestamp, Optional, List from ..util.generate_spec import generate_spec @model class CriterionModel: id: UUID name: str kind: str @model class RubricModel: id: UUID user: UUID name: str criteria: List[CriterionModel] description: Optional[str] = None tags: Optional[List[str]] = None timestamp: Optional[Timestamp] = None @interface class RubricAPI: @staticmethod def get( id: Optional[UUID] = None, user: Optional[UUID] = None, object: Optional[UUID] = None, timestamp: Optional[Timestamp] = None, skip: Optional[int] = None, limit: Optional[int] = None, ) -> HTTPResponse[List[RubricModel]]: raise NotImplemented @staticmethod def post( body: RubricModel ) -> HTTPResponse[None]: raise NotImplemented RubricSpec = generate_spec(RubricAPI, [RubricModel, CriterionModel])
true
true
f717c0006f023d6f8d6d6a2811a17dfa5060ba8c
72,241
py
Python
mne/bem.py
jdammers/mne-python
1dc1502215a53385cda15c6c336fcc4341dc4d3b
[ "BSD-3-Clause" ]
null
null
null
mne/bem.py
jdammers/mne-python
1dc1502215a53385cda15c6c336fcc4341dc4d3b
[ "BSD-3-Clause" ]
null
null
null
mne/bem.py
jdammers/mne-python
1dc1502215a53385cda15c6c336fcc4341dc4d3b
[ "BSD-3-Clause" ]
1
2021-04-12T12:45:31.000Z
2021-04-12T12:45:31.000Z
# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Matti Hamalainen <msh@nmr.mgh.harvard.edu> # Eric Larson <larson.eric.d@gmail.com> # Lorenzo De Santis <lorenzo.de-santis@u-psud.fr> # # License: BSD (3-clause) from functools import partial import glob import os import os.path as op import shutil from copy import deepcopy import numpy as np from scipy import linalg from .transforms import _ensure_trans, apply_trans from .io import Info from .io.constants import FIFF from .io.write import (start_file, start_block, write_float, write_int, write_float_matrix, write_int_matrix, end_block, end_file) from .io.tag import find_tag from .io.tree import dir_tree_find from .io.open import fiff_open from .surface import (read_surface, write_surface, complete_surface_info, _compute_nearest, _get_ico_surface, read_tri, _fast_cross_nd_sum, _get_solids) from .utils import verbose, logger, run_subprocess, get_subjects_dir, warn, _pl from .fixes import einsum from .externals.six import string_types # ############################################################################ # Compute BEM solution # The following approach is based on: # # de Munck JC: "A linear discretization of the volume conductor boundary # integral equation using analytically integrated elements", # IEEE Trans Biomed Eng. 1992 39(9) : 986 - 990 # class ConductorModel(dict): """BEM or sphere model.""" def __repr__(self): # noqa: D105 if self['is_sphere']: center = ', '.join('%0.1f' % (x * 1000.) for x in self['r0']) rad = self.radius if rad is None: # no radius / MEG only extra = 'Sphere (no layers): r0=[%s] mm' % center else: extra = ('Sphere (%s layer%s): r0=[%s] R=%1.f mm' % (len(self['layers']) - 1, _pl(self['layers']), center, rad * 1000.)) else: extra = ('BEM (%s layer%s)' % (len(self['surfs']), _pl(self['surfs']))) return '<ConductorModel | %s>' % extra def copy(self): """Return copy of ConductorModel instance.""" return deepcopy(self) @property def radius(self): """Sphere radius if an EEG sphere model.""" if not self['is_sphere']: raise RuntimeError('radius undefined for BEM') return None if len(self['layers']) == 0 else self['layers'][-1]['rad'] def _calc_beta(rk, rk_norm, rk1, rk1_norm): """Compute coefficients for calculating the magic vector omega.""" rkk1 = rk1[0] - rk[0] size = np.linalg.norm(rkk1) rkk1 /= size num = rk_norm + np.dot(rk, rkk1) den = rk1_norm + np.dot(rk1, rkk1) res = np.log(num / den) / size return res def _lin_pot_coeff(fros, tri_rr, tri_nn, tri_area): """Compute the linear potential matrix element computations.""" omega = np.zeros((len(fros), 3)) # we replicate a little bit of the _get_solids code here for speed # (we need some of the intermediate values later) v1 = tri_rr[np.newaxis, 0, :] - fros v2 = tri_rr[np.newaxis, 1, :] - fros v3 = tri_rr[np.newaxis, 2, :] - fros triples = _fast_cross_nd_sum(v1, v2, v3) l1 = np.linalg.norm(v1, axis=1) l2 = np.linalg.norm(v2, axis=1) l3 = np.linalg.norm(v3, axis=1) ss = l1 * l2 * l3 ss += einsum('ij,ij,i->i', v1, v2, l3) ss += einsum('ij,ij,i->i', v1, v3, l2) ss += einsum('ij,ij,i->i', v2, v3, l1) solids = np.arctan2(triples, ss) # We *could* subselect the good points from v1, v2, v3, triples, solids, # l1, l2, and l3, but there are *very* few bad points. So instead we do # some unnecessary calculations, and then omit them from the final # solution. These three lines ensure we don't get invalid values in # _calc_beta. bad_mask = np.abs(solids) < np.pi / 1e6 l1[bad_mask] = 1. l2[bad_mask] = 1. l3[bad_mask] = 1. # Calculate the magic vector vec_omega beta = [_calc_beta(v1, l1, v2, l2)[:, np.newaxis], _calc_beta(v2, l2, v3, l3)[:, np.newaxis], _calc_beta(v3, l3, v1, l1)[:, np.newaxis]] vec_omega = (beta[2] - beta[0]) * v1 vec_omega += (beta[0] - beta[1]) * v2 vec_omega += (beta[1] - beta[2]) * v3 area2 = 2.0 * tri_area n2 = 1.0 / (area2 * area2) # leave omega = 0 otherwise # Put it all together... yys = [v1, v2, v3] idx = [0, 1, 2, 0, 2] for k in range(3): diff = yys[idx[k - 1]] - yys[idx[k + 1]] zdots = _fast_cross_nd_sum(yys[idx[k + 1]], yys[idx[k - 1]], tri_nn) omega[:, k] = -n2 * (area2 * zdots * 2. * solids - triples * (diff * vec_omega).sum(axis=-1)) # omit the bad points from the solution omega[bad_mask] = 0. return omega def _correct_auto_elements(surf, mat): """Improve auto-element approximation.""" pi2 = 2.0 * np.pi tris_flat = surf['tris'].ravel() misses = pi2 - mat.sum(axis=1) for j, miss in enumerate(misses): # How much is missing? n_memb = len(surf['neighbor_tri'][j]) # The node itself receives one half mat[j, j] = miss / 2.0 # The rest is divided evenly among the member nodes... miss /= (4.0 * n_memb) members = np.where(j == tris_flat)[0] mods = members % 3 offsets = np.array([[1, 2], [-1, 1], [-1, -2]]) tri_1 = members + offsets[mods, 0] tri_2 = members + offsets[mods, 1] for t1, t2 in zip(tri_1, tri_2): mat[j, tris_flat[t1]] += miss mat[j, tris_flat[t2]] += miss return def _fwd_bem_lin_pot_coeff(surfs): """Calculate the coefficients for linear collocation approach.""" # taken from fwd_bem_linear_collocation.c nps = [surf['np'] for surf in surfs] np_tot = sum(nps) coeff = np.zeros((np_tot, np_tot)) offsets = np.cumsum(np.concatenate(([0], nps))) for si_1, surf1 in enumerate(surfs): rr_ord = np.arange(nps[si_1]) for si_2, surf2 in enumerate(surfs): logger.info(" %s (%d) -> %s (%d) ..." % (_bem_explain_surface(surf1['id']), nps[si_1], _bem_explain_surface(surf2['id']), nps[si_2])) tri_rr = surf2['rr'][surf2['tris']] tri_nn = surf2['tri_nn'] tri_area = surf2['tri_area'] submat = coeff[offsets[si_1]:offsets[si_1 + 1], offsets[si_2]:offsets[si_2 + 1]] # view for k in range(surf2['ntri']): tri = surf2['tris'][k] if si_1 == si_2: skip_idx = ((rr_ord == tri[0]) | (rr_ord == tri[1]) | (rr_ord == tri[2])) else: skip_idx = list() # No contribution from a triangle that # this vertex belongs to # if sidx1 == sidx2 and (tri == j).any(): # continue # Otherwise do the hard job coeffs = _lin_pot_coeff(surf1['rr'], tri_rr[k], tri_nn[k], tri_area[k]) coeffs[skip_idx] = 0. submat[:, tri] -= coeffs if si_1 == si_2: _correct_auto_elements(surf1, submat) return coeff def _fwd_bem_multi_solution(solids, gamma, nps): """Do multi surface solution. * Invert I - solids/(2*M_PI) * Take deflation into account * The matrix is destroyed after inversion * This is the general multilayer case """ pi2 = 1.0 / (2 * np.pi) n_tot = np.sum(nps) assert solids.shape == (n_tot, n_tot) nsurf = len(nps) defl = 1.0 / n_tot # Modify the matrix offsets = np.cumsum(np.concatenate(([0], nps))) for si_1 in range(nsurf): for si_2 in range(nsurf): mult = pi2 if gamma is None else pi2 * gamma[si_1, si_2] slice_j = slice(offsets[si_1], offsets[si_1 + 1]) slice_k = slice(offsets[si_2], offsets[si_2 + 1]) solids[slice_j, slice_k] = defl - solids[slice_j, slice_k] * mult solids += np.eye(n_tot) return linalg.inv(solids, overwrite_a=True) def _fwd_bem_homog_solution(solids, nps): """Make a homogeneous solution.""" return _fwd_bem_multi_solution(solids, None, nps) def _fwd_bem_ip_modify_solution(solution, ip_solution, ip_mult, n_tri): """Modify the solution according to the IP approach.""" n_last = n_tri[-1] mult = (1.0 + ip_mult) / ip_mult logger.info(' Combining...') offsets = np.cumsum(np.concatenate(([0], n_tri))) for si in range(len(n_tri)): # Pick the correct submatrix (right column) and multiply sub = solution[offsets[si]:offsets[si + 1], np.sum(n_tri[:-1]):] # Multiply sub -= 2 * np.dot(sub, ip_solution) # The lower right corner is a special case sub[-n_last:, -n_last:] += mult * ip_solution # Final scaling logger.info(' Scaling...') solution *= ip_mult return def _fwd_bem_linear_collocation_solution(m): """Compute the linear collocation potential solution.""" # first, add surface geometries for surf in m['surfs']: complete_surface_info(surf, copy=False, verbose=False) logger.info('Computing the linear collocation solution...') logger.info(' Matrix coefficients...') coeff = _fwd_bem_lin_pot_coeff(m['surfs']) m['nsol'] = len(coeff) logger.info(" Inverting the coefficient matrix...") nps = [surf['np'] for surf in m['surfs']] m['solution'] = _fwd_bem_multi_solution(coeff, m['gamma'], nps) if len(m['surfs']) == 3: ip_mult = m['sigma'][1] / m['sigma'][2] if ip_mult <= FIFF.FWD_BEM_IP_APPROACH_LIMIT: logger.info('IP approach required...') logger.info(' Matrix coefficients (homog)...') coeff = _fwd_bem_lin_pot_coeff([m['surfs'][-1]]) logger.info(' Inverting the coefficient matrix (homog)...') ip_solution = _fwd_bem_homog_solution(coeff, [m['surfs'][-1]['np']]) logger.info(' Modify the original solution to incorporate ' 'IP approach...') _fwd_bem_ip_modify_solution(m['solution'], ip_solution, ip_mult, nps) m['bem_method'] = FIFF.FWD_BEM_LINEAR_COLL logger.info("Solution ready.") @verbose def make_bem_solution(surfs, verbose=None): """Create a BEM solution using the linear collocation approach. Parameters ---------- surfs : list of dict The BEM surfaces to use (`from make_bem_model`) verbose : bool, str, int, or None If not None, override default verbose level (see :func:`mne.verbose` and :ref:`Logging documentation <tut_logging>` for more). Returns ------- bem : instance of ConductorModel The BEM solution. Notes ----- .. versionadded:: 0.10.0 See Also -------- make_bem_model read_bem_surfaces write_bem_surfaces read_bem_solution write_bem_solution """ logger.info('Approximation method : Linear collocation\n') if isinstance(surfs, string_types): # Load the surfaces logger.info('Loading surfaces...') surfs = read_bem_surfaces(surfs) bem = ConductorModel(is_sphere=False, surfs=surfs) _add_gamma_multipliers(bem) if len(bem['surfs']) == 3: logger.info('Three-layer model surfaces loaded.') elif len(bem['surfs']) == 1: logger.info('Homogeneous model surface loaded.') else: raise RuntimeError('Only 1- or 3-layer BEM computations supported') _check_bem_size(bem['surfs']) _fwd_bem_linear_collocation_solution(bem) logger.info('BEM geometry computations complete.') return bem # ############################################################################ # Make BEM model def _ico_downsample(surf, dest_grade): """Downsample the surface if isomorphic to a subdivided icosahedron.""" n_tri = len(surf['tris']) found = -1 bad_msg = ("A surface with %d triangles cannot be isomorphic with a " "subdivided icosahedron." % n_tri) if n_tri % 20 != 0: raise RuntimeError(bad_msg) n_tri = n_tri // 20 found = int(round(np.log(n_tri) / np.log(4))) if n_tri != 4 ** found: raise RuntimeError(bad_msg) del n_tri if dest_grade > found: raise RuntimeError('For this surface, decimation grade should be %d ' 'or less, not %s.' % (found, dest_grade)) source = _get_ico_surface(found) dest = _get_ico_surface(dest_grade, patch_stats=True) del dest['tri_cent'] del dest['tri_nn'] del dest['neighbor_tri'] del dest['tri_area'] if not np.array_equal(source['tris'], surf['tris']): raise RuntimeError('The source surface has a matching number of ' 'triangles but ordering is wrong') logger.info('Going from %dth to %dth subdivision of an icosahedron ' '(n_tri: %d -> %d)' % (found, dest_grade, len(surf['tris']), len(dest['tris']))) # Find the mapping dest['rr'] = surf['rr'][_get_ico_map(source, dest)] return dest def _get_ico_map(fro, to): """Get a mapping between ico surfaces.""" nearest, dists = _compute_nearest(fro['rr'], to['rr'], return_dists=True) n_bads = (dists > 5e-3).sum() if n_bads > 0: raise RuntimeError('No matching vertex for %d destination vertices' % (n_bads)) return nearest def _order_surfaces(surfs): """Reorder the surfaces.""" if len(surfs) != 3: return surfs # we have three surfaces surf_order = [FIFF.FIFFV_BEM_SURF_ID_HEAD, FIFF.FIFFV_BEM_SURF_ID_SKULL, FIFF.FIFFV_BEM_SURF_ID_BRAIN] ids = np.array([surf['id'] for surf in surfs]) if set(ids) != set(surf_order): raise RuntimeError('bad surface ids: %s' % ids) order = [np.where(ids == id_)[0][0] for id_ in surf_order] surfs = [surfs[idx] for idx in order] return surfs def _assert_complete_surface(surf, incomplete='raise'): """Check the sum of solid angles as seen from inside.""" # from surface_checks.c tot_angle = 0. # Center of mass.... cm = surf['rr'].mean(axis=0) logger.info('%s CM is %6.2f %6.2f %6.2f mm' % (_surf_name[surf['id']], 1000 * cm[0], 1000 * cm[1], 1000 * cm[2])) tot_angle = _get_solids(surf['rr'][surf['tris']], cm[np.newaxis, :])[0] prop = tot_angle / (2 * np.pi) if np.abs(prop - 1.0) > 1e-5: msg = ('Surface %s is not complete (sum of solid angles ' 'yielded %g, should be 1.)' % (_surf_name[surf['id']], prop)) if incomplete == 'raise': raise RuntimeError(msg) else: warn(msg) _surf_name = { FIFF.FIFFV_BEM_SURF_ID_HEAD: 'outer skin ', FIFF.FIFFV_BEM_SURF_ID_SKULL: 'outer skull', FIFF.FIFFV_BEM_SURF_ID_BRAIN: 'inner skull', FIFF.FIFFV_BEM_SURF_ID_UNKNOWN: 'unknown ', } def _assert_inside(fro, to): """Check one set of points is inside a surface.""" # this is "is_inside" in surface_checks.c tot_angle = _get_solids(to['rr'][to['tris']], fro['rr']) if (np.abs(tot_angle / (2 * np.pi) - 1.0) > 1e-5).any(): raise RuntimeError('Surface %s is not completely inside surface %s' % (_surf_name[fro['id']], _surf_name[to['id']])) def _check_surfaces(surfs, incomplete='raise'): """Check that the surfaces are complete and non-intersecting.""" for surf in surfs: _assert_complete_surface(surf, incomplete=incomplete) # Then check the topology for surf_1, surf_2 in zip(surfs[:-1], surfs[1:]): logger.info('Checking that %s surface is inside %s surface...' % (_surf_name[surf_2['id']], _surf_name[surf_1['id']])) _assert_inside(surf_2, surf_1) def _check_surface_size(surf): """Check that the coordinate limits are reasonable.""" sizes = surf['rr'].max(axis=0) - surf['rr'].min(axis=0) if (sizes < 0.05).any(): raise RuntimeError('Dimensions of the surface %s seem too small ' '(%9.5f mm). Maybe the the unit of measure is ' 'meters instead of mm' % (_surf_name[surf['id']], 1000 * sizes.min())) def _check_thicknesses(surfs): """Compute how close we are.""" for surf_1, surf_2 in zip(surfs[:-1], surfs[1:]): min_dist = _compute_nearest(surf_1['rr'], surf_2['rr'], return_dists=True)[0] min_dist = min_dist.min() logger.info('Checking distance between %s and %s surfaces...' % (_surf_name[surf_1['id']], _surf_name[surf_2['id']])) logger.info('Minimum distance between the %s and %s surfaces is ' 'approximately %6.1f mm' % (_surf_name[surf_1['id']], _surf_name[surf_2['id']], 1000 * min_dist)) def _surfaces_to_bem(surfs, ids, sigmas, ico=None, rescale=True, incomplete='raise'): """Convert surfaces to a BEM.""" # equivalent of mne_surf2bem # surfs can be strings (filenames) or surface dicts if len(surfs) not in (1, 3) or not (len(surfs) == len(ids) == len(sigmas)): raise ValueError('surfs, ids, and sigmas must all have the same ' 'number of elements (1 or 3)') surf = list(surfs) for si, surf in enumerate(surfs): if isinstance(surf, string_types): surfs[si] = read_surface(surf, return_dict=True)[-1] # Downsampling if the surface is isomorphic with a subdivided icosahedron if ico is not None: for si, surf in enumerate(surfs): surfs[si] = _ico_downsample(surf, ico) for surf, id_ in zip(surfs, ids): surf['id'] = id_ surf['coord_frame'] = surf.get('coord_frame', FIFF.FIFFV_COORD_MRI) surf.update(np=len(surf['rr']), ntri=len(surf['tris'])) if rescale: surf['rr'] /= 1000. # convert to meters # Shifting surfaces is not implemented here... # Order the surfaces for the benefit of the topology checks for surf, sigma in zip(surfs, sigmas): surf['sigma'] = sigma surfs = _order_surfaces(surfs) # Check topology as best we can _check_surfaces(surfs, incomplete=incomplete) for surf in surfs: _check_surface_size(surf) _check_thicknesses(surfs) logger.info('Surfaces passed the basic topology checks.') return surfs @verbose def make_bem_model(subject, ico=4, conductivity=(0.3, 0.006, 0.3), subjects_dir=None, verbose=None): """Create a BEM model for a subject. .. note:: To get a single layer bem corresponding to the --homog flag in the command line tool set the ``conductivity`` parameter to a list/tuple with a single value (e.g. [0.3]). Parameters ---------- subject : str The subject. ico : int | None The surface ico downsampling to use, e.g. 5=20484, 4=5120, 3=1280. If None, no subsampling is applied. conductivity : array of int, shape (3,) or (1,) The conductivities to use for each shell. Should be a single element for a one-layer model, or three elements for a three-layer model. Defaults to ``[0.3, 0.006, 0.3]``. The MNE-C default for a single-layer model would be ``[0.3]``. subjects_dir : string, or None Path to SUBJECTS_DIR if it is not set in the environment. verbose : bool, str, int, or None If not None, override default verbose level (see :func:`mne.verbose` and :ref:`Logging documentation <tut_logging>` for more). Returns ------- surfaces : list of dict The BEM surfaces. Use `make_bem_solution` to turn these into a `ConductorModel` suitable for forward calculation. Notes ----- .. versionadded:: 0.10.0 See Also -------- make_bem_solution make_sphere_model read_bem_surfaces write_bem_surfaces """ conductivity = np.array(conductivity, float) if conductivity.ndim != 1 or conductivity.size not in (1, 3): raise ValueError('conductivity must be 1D array-like with 1 or 3 ' 'elements') subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) subject_dir = op.join(subjects_dir, subject) bem_dir = op.join(subject_dir, 'bem') inner_skull = op.join(bem_dir, 'inner_skull.surf') outer_skull = op.join(bem_dir, 'outer_skull.surf') outer_skin = op.join(bem_dir, 'outer_skin.surf') surfaces = [inner_skull, outer_skull, outer_skin] ids = [FIFF.FIFFV_BEM_SURF_ID_BRAIN, FIFF.FIFFV_BEM_SURF_ID_SKULL, FIFF.FIFFV_BEM_SURF_ID_HEAD] logger.info('Creating the BEM geometry...') if len(conductivity) == 1: surfaces = surfaces[:1] ids = ids[:1] surfaces = _surfaces_to_bem(surfaces, ids, conductivity, ico) _check_bem_size(surfaces) logger.info('Complete.\n') return surfaces # ############################################################################ # Compute EEG sphere model def _fwd_eeg_get_multi_sphere_model_coeffs(m, n_terms): """Get the model depended weighting factor for n.""" nlayer = len(m['layers']) if nlayer in (0, 1): return 1. # Initialize the arrays c1 = np.zeros(nlayer - 1) c2 = np.zeros(nlayer - 1) cr = np.zeros(nlayer - 1) cr_mult = np.zeros(nlayer - 1) for k in range(nlayer - 1): c1[k] = m['layers'][k]['sigma'] / m['layers'][k + 1]['sigma'] c2[k] = c1[k] - 1.0 cr_mult[k] = m['layers'][k]['rel_rad'] cr[k] = cr_mult[k] cr_mult[k] *= cr_mult[k] coeffs = np.zeros(n_terms - 1) for n in range(1, n_terms): # Increment the radius coefficients for k in range(nlayer - 1): cr[k] *= cr_mult[k] # Multiply the matrices M = np.eye(2) n1 = n + 1.0 for k in range(nlayer - 2, -1, -1): M = np.dot([[n + n1 * c1[k], n1 * c2[k] / cr[k]], [n * c2[k] * cr[k], n1 + n * c1[k]]], M) num = n * (2.0 * n + 1.0) ** (nlayer - 1) coeffs[n - 1] = num / (n * M[1, 1] + n1 * M[1, 0]) return coeffs def _compose_linear_fitting_data(mu, u): """Get the linear fitting data.""" # y is the data to be fitted (nterms-1 x 1) # M is the model matrix (nterms-1 x nfit-1) for k in range(u['nterms'] - 1): k1 = k + 1 mu1n = np.power(mu[0], k1) u['y'][k] = u['w'][k] * (u['fn'][k1] - mu1n * u['fn'][0]) for p in range(u['nfit'] - 1): u['M'][k][p] = u['w'][k] * (np.power(mu[p + 1], k1) - mu1n) def _compute_linear_parameters(mu, u): """Compute the best-fitting linear parameters.""" _compose_linear_fitting_data(mu, u) uu, sing, vv = linalg.svd(u['M'], full_matrices=False) # Compute the residuals u['resi'] = u['y'].copy() vec = np.empty(u['nfit'] - 1) for p in range(u['nfit'] - 1): vec[p] = np.dot(uu[:, p], u['y']) for k in range(u['nterms'] - 1): u['resi'][k] -= uu[k, p] * vec[p] vec[p] = vec[p] / sing[p] lambda_ = np.zeros(u['nfit']) for p in range(u['nfit'] - 1): sum_ = 0. for q in range(u['nfit'] - 1): sum_ += vv[q, p] * vec[q] lambda_[p + 1] = sum_ lambda_[0] = u['fn'][0] - np.sum(lambda_[1:]) rv = np.dot(u['resi'], u['resi']) / np.dot(u['y'], u['y']) return rv, lambda_ def _one_step(mu, u): """Evaluate the residual sum of squares fit for one set of mu values.""" if np.abs(mu).max() > 1.0: return 1.0 # Compose the data for the linear fitting, compute SVD, then residuals _compose_linear_fitting_data(mu, u) u['uu'], u['sing'], u['vv'] = linalg.svd(u['M']) u['resi'][:] = u['y'][:] for p in range(u['nfit'] - 1): dot = np.dot(u['uu'][p], u['y']) for k in range(u['nterms'] - 1): u['resi'][k] = u['resi'][k] - u['uu'][p, k] * dot # Return their sum of squares return np.dot(u['resi'], u['resi']) def _fwd_eeg_fit_berg_scherg(m, nterms, nfit): """Fit the Berg-Scherg equivalent spherical model dipole parameters.""" from scipy.optimize import fmin_cobyla assert nfit >= 2 u = dict(y=np.zeros(nterms - 1), resi=np.zeros(nterms - 1), nfit=nfit, nterms=nterms, M=np.zeros((nterms - 1, nfit - 1))) # (1) Calculate the coefficients of the true expansion u['fn'] = _fwd_eeg_get_multi_sphere_model_coeffs(m, nterms + 1) # (2) Calculate the weighting f = (min([layer['rad'] for layer in m['layers']]) / max([layer['rad'] for layer in m['layers']])) # correct weighting k = np.arange(1, nterms + 1) u['w'] = np.sqrt((2.0 * k + 1) * (3.0 * k + 1.0) / k) * np.power(f, (k - 1.0)) u['w'][-1] = 0 # Do the nonlinear minimization, constraining mu to the interval [-1, +1] mu_0 = np.random.RandomState(0).rand(nfit) * f fun = partial(_one_step, u=u) max_ = 1. - 2e-4 # adjust for fmin_cobyla "catol" that not all scipy have cons = [(lambda x: max_ - np.abs(x[ii])) for ii in range(nfit)] mu = fmin_cobyla(fun, mu_0, cons, rhobeg=0.5, rhoend=5e-3, disp=0) # (6) Do the final step: calculation of the linear parameters rv, lambda_ = _compute_linear_parameters(mu, u) order = np.argsort(mu)[::-1] mu, lambda_ = mu[order], lambda_[order] # sort: largest mu first m['mu'] = mu # This division takes into account the actual conductivities m['lambda'] = lambda_ / m['layers'][-1]['sigma'] m['nfit'] = nfit return rv @verbose def make_sphere_model(r0=(0., 0., 0.04), head_radius=0.09, info=None, relative_radii=(0.90, 0.92, 0.97, 1.0), sigmas=(0.33, 1.0, 0.004, 0.33), verbose=None): """Create a spherical model for forward solution calculation. Parameters ---------- r0 : array-like | str Head center to use (in head coordinates). If 'auto', the head center will be calculated from the digitization points in info. head_radius : float | str | None If float, compute spherical shells for EEG using the given radius. If 'auto', estimate an approriate radius from the dig points in Info, If None, exclude shells (single layer sphere model). info : instance of Info | None Measurement info. Only needed if ``r0`` or ``head_radius`` are ``'auto'``. relative_radii : array-like Relative radii for the spherical shells. sigmas : array-like Sigma values for the spherical shells. verbose : bool, str, int, or None If not None, override default verbose level (see :func:`mne.verbose` and :ref:`Logging documentation <tut_logging>` for more). Returns ------- sphere : instance of ConductorModel The resulting spherical conductor model. Notes ----- .. versionadded:: 0.9.0 See Also -------- make_bem_model make_bem_solution """ for name in ('r0', 'head_radius'): param = locals()[name] if isinstance(param, string_types): if param != 'auto': raise ValueError('%s, if str, must be "auto" not "%s"' % (name, param)) relative_radii = np.array(relative_radii, float).ravel() sigmas = np.array(sigmas, float).ravel() if len(relative_radii) != len(sigmas): raise ValueError('relative_radii length (%s) must match that of ' 'sigmas (%s)' % (len(relative_radii), len(sigmas))) if len(sigmas) <= 1 and head_radius is not None: raise ValueError('at least 2 sigmas must be supplied if ' 'head_radius is not None, got %s' % (len(sigmas),)) if (isinstance(r0, string_types) and r0 == 'auto') or \ (isinstance(head_radius, string_types) and head_radius == 'auto'): if info is None: raise ValueError('Info must not be None for auto mode') head_radius_fit, r0_fit = fit_sphere_to_headshape(info, units='m')[:2] if isinstance(r0, string_types): r0 = r0_fit if isinstance(head_radius, string_types): head_radius = head_radius_fit sphere = ConductorModel(is_sphere=True, r0=np.array(r0), coord_frame=FIFF.FIFFV_COORD_HEAD) sphere['layers'] = list() if head_radius is not None: # Eventually these could be configurable... relative_radii = np.array(relative_radii, float) sigmas = np.array(sigmas, float) order = np.argsort(relative_radii) relative_radii = relative_radii[order] sigmas = sigmas[order] for rel_rad, sig in zip(relative_radii, sigmas): # sort layers by (relative) radius, and scale radii layer = dict(rad=rel_rad, sigma=sig) layer['rel_rad'] = layer['rad'] = rel_rad sphere['layers'].append(layer) # scale the radii R = sphere['layers'][-1]['rad'] rR = sphere['layers'][-1]['rel_rad'] for layer in sphere['layers']: layer['rad'] /= R layer['rel_rad'] /= rR # # Setup the EEG sphere model calculations # # Scale the relative radii for k in range(len(relative_radii)): sphere['layers'][k]['rad'] = (head_radius * sphere['layers'][k]['rel_rad']) rv = _fwd_eeg_fit_berg_scherg(sphere, 200, 3) logger.info('\nEquiv. model fitting -> RV = %g %%' % (100 * rv)) for k in range(3): logger.info('mu%d = %g lambda%d = %g' % (k + 1, sphere['mu'][k], k + 1, sphere['layers'][-1]['sigma'] * sphere['lambda'][k])) logger.info('Set up EEG sphere model with scalp radius %7.1f mm\n' % (1000 * head_radius,)) return sphere # ############################################################################# # Sphere fitting _dig_kind_dict = { 'cardinal': FIFF.FIFFV_POINT_CARDINAL, 'hpi': FIFF.FIFFV_POINT_HPI, 'eeg': FIFF.FIFFV_POINT_EEG, 'extra': FIFF.FIFFV_POINT_EXTRA, } _dig_kind_rev = dict((val, key) for key, val in _dig_kind_dict.items()) _dig_kind_ints = tuple(_dig_kind_dict.values()) @verbose def fit_sphere_to_headshape(info, dig_kinds='auto', units='m', verbose=None): """Fit a sphere to the headshape points to determine head center. Parameters ---------- info : instance of Info Measurement info. dig_kinds : list of str | str Kind of digitization points to use in the fitting. These can be any combination of ('cardinal', 'hpi', 'eeg', 'extra'). Can also be 'auto' (default), which will use only the 'extra' points if enough (more than 10) are available, and if not, uses 'extra' and 'eeg' points. units : str Can be "m" (default) or "mm". .. versionadded:: 0.12 verbose : bool, str, int, or None If not None, override default verbose level (see :func:`mne.verbose` and :ref:`Logging documentation <tut_logging>` for more). Returns ------- radius : float Sphere radius. origin_head: ndarray, shape (3,) Head center in head coordinates. origin_device: ndarray, shape (3,) Head center in device coordinates. Notes ----- This function excludes any points that are low and frontal (``z < 0 and y > 0``) to improve the fit. """ if not isinstance(units, string_types) or units not in ('m', 'mm'): raise ValueError('units must be a "m" or "mm"') radius, origin_head, origin_device = _fit_sphere_to_headshape( info, dig_kinds) if units == 'mm': radius *= 1e3 origin_head *= 1e3 origin_device *= 1e3 return radius, origin_head, origin_device @verbose def get_fitting_dig(info, dig_kinds='auto', verbose=None): """Get digitization points suitable for sphere fitting. Parameters ---------- info : instance of Info The measurement info. dig_kinds : list of str | str Kind of digitization points to use in the fitting. These can be any combination of ('cardinal', 'hpi', 'eeg', 'extra'). Can also be 'auto' (default), which will use only the 'extra' points if enough (more than 10) are available, and if not, uses 'extra' and 'eeg' points. verbose : bool, str or None If not None, override default verbose level Returns ------- dig : array, shape (n_pts, 3) The digitization points (in head coordinates) to use for fitting. Notes ----- This will exclude digitization locations that have ``z < 0 and y > 0``, i.e. points on the nose and below the nose on the face. .. versionadded:: 0.14 """ if not isinstance(info, Info): raise TypeError('info must be an instance of Info not %s' % type(info)) if info['dig'] is None: raise RuntimeError('Cannot fit headshape without digitization ' ', info["dig"] is None') if isinstance(dig_kinds, string_types): if dig_kinds == 'auto': # try "extra" first try: return get_fitting_dig(info, 'extra') except ValueError: pass return get_fitting_dig(info, ('extra', 'eeg')) else: dig_kinds = (dig_kinds,) # convert string args to ints (first make dig_kinds mutable in case tuple) dig_kinds = list(dig_kinds) for di, d in enumerate(dig_kinds): dig_kinds[di] = _dig_kind_dict.get(d, d) if dig_kinds[di] not in _dig_kind_ints: raise ValueError('dig_kinds[#%d] (%s) must be one of %s' % (di, d, sorted(list(_dig_kind_dict.keys())))) # get head digization points of the specified kind(s) hsp = [p['r'] for p in info['dig'] if p['kind'] in dig_kinds] if any(p['coord_frame'] != FIFF.FIFFV_COORD_HEAD for p in info['dig']): raise RuntimeError('Digitization points not in head coordinates, ' 'contact mne-python developers') # exclude some frontal points (nose etc.) hsp = np.array([p for p in hsp if not (p[2] < -1e-6 and p[1] > 1e-6)]) if len(hsp) <= 10: kinds_str = ', '.join(['"%s"' % _dig_kind_rev[d] for d in sorted(dig_kinds)]) msg = ('Only %s head digitization points of the specified kind%s (%s,)' % (len(hsp), _pl(dig_kinds), kinds_str)) if len(hsp) < 4: raise ValueError(msg + ', at least 4 required') else: warn(msg + ', fitting may be inaccurate') return hsp @verbose def _fit_sphere_to_headshape(info, dig_kinds, verbose=None): """Fit a sphere to the given head shape.""" hsp = get_fitting_dig(info, dig_kinds) radius, origin_head = _fit_sphere(np.array(hsp), disp=False) # compute origin in device coordinates head_to_dev = _ensure_trans(info['dev_head_t'], 'head', 'meg') origin_device = apply_trans(head_to_dev, origin_head) logger.info('Fitted sphere radius:'.ljust(30) + '%0.1f mm' % (radius * 1e3,)) # 99th percentile on Wikipedia for Giabella to back of head is 21.7cm, # i.e. 108mm "radius", so let's go with 110mm # en.wikipedia.org/wiki/Human_head#/media/File:HeadAnthropometry.JPG if radius > 0.110: warn('Estimated head size (%0.1f mm) exceeded 99th ' 'percentile for adult head size' % (1e3 * radius,)) # > 2 cm away from head center in X or Y is strange if np.linalg.norm(origin_head[:2]) > 0.02: warn('(X, Y) fit (%0.1f, %0.1f) more than 20 mm from ' 'head frame origin' % tuple(1e3 * origin_head[:2])) logger.info('Origin head coordinates:'.ljust(30) + '%0.1f %0.1f %0.1f mm' % tuple(1e3 * origin_head)) logger.info('Origin device coordinates:'.ljust(30) + '%0.1f %0.1f %0.1f mm' % tuple(1e3 * origin_device)) return radius, origin_head, origin_device def _fit_sphere(points, disp='auto'): """Fit a sphere to an arbitrary set of points.""" from scipy.optimize import fmin_cobyla if isinstance(disp, string_types) and disp == 'auto': disp = True if logger.level <= 20 else False # initial guess for center and radius radii = (np.max(points, axis=1) - np.min(points, axis=1)) / 2. radius_init = radii.mean() center_init = np.median(points, axis=0) # optimization x0 = np.concatenate([center_init, [radius_init]]) def cost_fun(center_rad): d = np.linalg.norm(points - center_rad[:3], axis=1) - center_rad[3] d *= d return d.sum() def constraint(center_rad): return center_rad[3] # radius must be >= 0 x_opt = fmin_cobyla(cost_fun, x0, constraint, rhobeg=radius_init, rhoend=radius_init * 1e-6, disp=disp) origin = x_opt[:3] radius = x_opt[3] return radius, origin def _check_origin(origin, info, coord_frame='head', disp=False): """Check or auto-determine the origin.""" if isinstance(origin, string_types): if origin != 'auto': raise ValueError('origin must be a numerical array, or "auto", ' 'not %s' % (origin,)) if coord_frame == 'head': R, origin = fit_sphere_to_headshape(info, verbose=False, units='m')[:2] logger.info(' Automatic origin fit: head of radius %0.1f mm' % (R * 1000.,)) del R else: origin = (0., 0., 0.) origin = np.array(origin, float) if origin.shape != (3,): raise ValueError('origin must be a 3-element array') if disp: origin_str = ', '.join(['%0.1f' % (o * 1000) for o in origin]) msg = (' Using origin %s mm in the %s frame' % (origin_str, coord_frame)) if coord_frame == 'meg' and info['dev_head_t'] is not None: o_dev = apply_trans(info['dev_head_t'], origin) origin_str = ', '.join('%0.1f' % (o * 1000,) for o in o_dev) msg += ' (%s mm in the head frame)' % (origin_str,) logger.info(msg) return origin # ############################################################################ # Create BEM surfaces @verbose def make_watershed_bem(subject, subjects_dir=None, overwrite=False, volume='T1', atlas=False, gcaatlas=False, preflood=None, show=False, verbose=None): """Create BEM surfaces using the FreeSurfer watershed algorithm. Parameters ---------- subject : str Subject name (required) subjects_dir : str Directory containing subjects data. If None use the Freesurfer SUBJECTS_DIR environment variable. overwrite : bool Write over existing files volume : str Defaults to T1 atlas : bool Specify the --atlas option for mri_watershed gcaatlas : bool Use the subcortical atlas preflood : int Change the preflood height show : bool Show surfaces to visually inspect all three BEM surfaces (recommended). .. versionadded:: 0.12 verbose : bool, str or None If not None, override default verbose level Notes ----- .. versionadded:: 0.10 """ from .viz.misc import plot_bem env, mri_dir = _prepare_env(subject, subjects_dir, requires_freesurfer=True)[:2] subjects_dir = env['SUBJECTS_DIR'] subject_dir = op.join(subjects_dir, subject) mri_dir = op.join(subject_dir, 'mri') T1_dir = op.join(mri_dir, volume) T1_mgz = op.join(mri_dir, volume + '.mgz') bem_dir = op.join(subject_dir, 'bem') ws_dir = op.join(subject_dir, 'bem', 'watershed') if not op.isdir(bem_dir): os.makedirs(bem_dir) if not op.isdir(T1_dir) and not op.isfile(T1_mgz): raise RuntimeError('Could not find the MRI data') if op.isdir(ws_dir): if not overwrite: raise RuntimeError('%s already exists. Use the --overwrite option' ' to recreate it.' % ws_dir) else: shutil.rmtree(ws_dir) # put together the command cmd = ['mri_watershed'] if preflood: cmd += ["-h", "%s" % int(preflood)] if gcaatlas: cmd += ['-atlas', '-T1', '-brain_atlas', env['FREESURFER_HOME'] + '/average/RB_all_withskull_2007-08-08.gca', subject_dir + '/mri/transforms/talairach_with_skull.lta'] elif atlas: cmd += ['-atlas'] if op.exists(T1_mgz): cmd += ['-useSRAS', '-surf', op.join(ws_dir, subject), T1_mgz, op.join(ws_dir, 'ws')] else: cmd += ['-useSRAS', '-surf', op.join(ws_dir, subject), T1_dir, op.join(ws_dir, 'ws')] # report and run logger.info('\nRunning mri_watershed for BEM segmentation with the ' 'following parameters:\n\n' 'SUBJECTS_DIR = %s\n' 'SUBJECT = %s\n' 'Results dir = %s\n' % (subjects_dir, subject, ws_dir)) os.makedirs(op.join(ws_dir, 'ws')) run_subprocess(cmd, env=env) if op.isfile(T1_mgz): new_info = _extract_volume_info(T1_mgz) if new_info is None: warn('nibabel is required to replace the volume info. Volume info' 'not updated in the written surface.') new_info = dict() surfs = ['brain', 'inner_skull', 'outer_skull', 'outer_skin'] for s in surfs: surf_ws_out = op.join(ws_dir, '%s_%s_surface' % (subject, s)) rr, tris, volume_info = read_surface(surf_ws_out, read_metadata=True) volume_info.update(new_info) # replace volume info, 'head' stays write_surface(s, rr, tris, volume_info=volume_info) # Create symbolic links surf_out = op.join(bem_dir, '%s.surf' % s) if not overwrite and op.exists(surf_out): skip_symlink = True else: if op.exists(surf_out): os.remove(surf_out) _symlink(surf_ws_out, surf_out) skip_symlink = False if skip_symlink: logger.info("Unable to create all symbolic links to .surf files " "in bem folder. Use --overwrite option to recreate " "them.") dest = op.join(bem_dir, 'watershed') else: logger.info("Symbolic links to .surf files created in bem folder") dest = bem_dir logger.info("\nThank you for waiting.\nThe BEM triangulations for this " "subject are now available at:\n%s." % dest) # Write a head file for coregistration fname_head = op.join(bem_dir, subject + '-head.fif') if op.isfile(fname_head): os.remove(fname_head) surf = _surfaces_to_bem([op.join(ws_dir, subject + '_outer_skin_surface')], [FIFF.FIFFV_BEM_SURF_ID_HEAD], sigmas=[1]) write_bem_surfaces(fname_head, surf) # Show computed BEM surfaces if show: plot_bem(subject=subject, subjects_dir=subjects_dir, orientation='coronal', slices=None, show=True) logger.info('Created %s\n\nComplete.' % (fname_head,)) def _extract_volume_info(mgz, raise_error=True): """Extract volume info from a mgz file.""" try: import nibabel as nib except ImportError: return # warning raised elsewhere header = nib.load(mgz).header vol_info = dict() version = header['version'] if version == 1: version = '%s # volume info valid' % version else: raise ValueError('Volume info invalid.') vol_info['valid'] = version vol_info['filename'] = mgz vol_info['volume'] = header['dims'][:3] vol_info['voxelsize'] = header['delta'] vol_info['xras'], vol_info['yras'], vol_info['zras'] = header['Mdc'].T vol_info['cras'] = header['Pxyz_c'] return vol_info # ############################################################################ # Read @verbose def read_bem_surfaces(fname, patch_stats=False, s_id=None, verbose=None): """Read the BEM surfaces from a FIF file. Parameters ---------- fname : string The name of the file containing the surfaces. patch_stats : bool, optional (default False) Calculate and add cortical patch statistics to the surfaces. s_id : int | None If int, only read and return the surface with the given s_id. An error will be raised if it doesn't exist. If None, all surfaces are read and returned. verbose : bool, str, int, or None If not None, override default verbose level (see :func:`mne.verbose` and :ref:`Logging documentation <tut_logging>` for more). Returns ------- surf: list | dict A list of dictionaries that each contain a surface. If s_id is not None, only the requested surface will be returned. See Also -------- write_bem_surfaces, write_bem_solution, make_bem_model """ # Default coordinate frame coord_frame = FIFF.FIFFV_COORD_MRI # Open the file, create directory f, tree, _ = fiff_open(fname) with f as fid: # Find BEM bem = dir_tree_find(tree, FIFF.FIFFB_BEM) if bem is None or len(bem) == 0: raise ValueError('BEM data not found') bem = bem[0] # Locate all surfaces bemsurf = dir_tree_find(bem, FIFF.FIFFB_BEM_SURF) if bemsurf is None: raise ValueError('BEM surface data not found') logger.info(' %d BEM surfaces found' % len(bemsurf)) # Coordinate frame possibly at the top level tag = find_tag(fid, bem, FIFF.FIFF_BEM_COORD_FRAME) if tag is not None: coord_frame = tag.data # Read all surfaces if s_id is not None: surf = [_read_bem_surface(fid, bsurf, coord_frame, s_id) for bsurf in bemsurf] surf = [s for s in surf if s is not None] if not len(surf) == 1: raise ValueError('surface with id %d not found' % s_id) else: surf = list() for bsurf in bemsurf: logger.info(' Reading a surface...') this = _read_bem_surface(fid, bsurf, coord_frame) surf.append(this) logger.info('[done]') logger.info(' %d BEM surfaces read' % len(surf)) for this in surf: if patch_stats or this['nn'] is None: complete_surface_info(this, copy=False) return surf[0] if s_id is not None else surf def _read_bem_surface(fid, this, def_coord_frame, s_id=None): """Read one bem surface.""" # fid should be open as a context manager here res = dict() # Read all the interesting stuff tag = find_tag(fid, this, FIFF.FIFF_BEM_SURF_ID) if tag is None: res['id'] = FIFF.FIFFV_BEM_SURF_ID_UNKNOWN else: res['id'] = int(tag.data) if s_id is not None and res['id'] != s_id: return None tag = find_tag(fid, this, FIFF.FIFF_BEM_SIGMA) res['sigma'] = 1.0 if tag is None else float(tag.data) tag = find_tag(fid, this, FIFF.FIFF_BEM_SURF_NNODE) if tag is None: raise ValueError('Number of vertices not found') res['np'] = int(tag.data) tag = find_tag(fid, this, FIFF.FIFF_BEM_SURF_NTRI) if tag is None: raise ValueError('Number of triangles not found') res['ntri'] = int(tag.data) tag = find_tag(fid, this, FIFF.FIFF_MNE_COORD_FRAME) if tag is None: tag = find_tag(fid, this, FIFF.FIFF_BEM_COORD_FRAME) if tag is None: res['coord_frame'] = def_coord_frame else: res['coord_frame'] = tag.data else: res['coord_frame'] = tag.data # Vertices, normals, and triangles tag = find_tag(fid, this, FIFF.FIFF_BEM_SURF_NODES) if tag is None: raise ValueError('Vertex data not found') res['rr'] = tag.data.astype(np.float) # XXX : double because of mayavi bug if res['rr'].shape[0] != res['np']: raise ValueError('Vertex information is incorrect') tag = find_tag(fid, this, FIFF.FIFF_MNE_SOURCE_SPACE_NORMALS) if tag is None: tag = find_tag(fid, this, FIFF.FIFF_BEM_SURF_NORMALS) if tag is None: res['nn'] = None else: res['nn'] = tag.data.copy() if res['nn'].shape[0] != res['np']: raise ValueError('Vertex normal information is incorrect') tag = find_tag(fid, this, FIFF.FIFF_BEM_SURF_TRIANGLES) if tag is None: raise ValueError('Triangulation not found') res['tris'] = tag.data - 1 # index start at 0 in Python if res['tris'].shape[0] != res['ntri']: raise ValueError('Triangulation information is incorrect') return res @verbose def read_bem_solution(fname, verbose=None): """Read the BEM solution from a file. Parameters ---------- fname : string The file containing the BEM solution. verbose : bool, str, int, or None If not None, override default verbose level (see :func:`mne.verbose` and :ref:`Logging documentation <tut_logging>` for more). Returns ------- bem : instance of ConductorModel The BEM solution. See Also -------- write_bem_solution, read_bem_surfaces, write_bem_surfaces, make_bem_solution """ # mirrors fwd_bem_load_surfaces from fwd_bem_model.c logger.info('Loading surfaces...') bem_surfs = read_bem_surfaces(fname, patch_stats=True, verbose=False) if len(bem_surfs) == 3: logger.info('Three-layer model surfaces loaded.') needed = np.array([FIFF.FIFFV_BEM_SURF_ID_HEAD, FIFF.FIFFV_BEM_SURF_ID_SKULL, FIFF.FIFFV_BEM_SURF_ID_BRAIN]) if not all(x['id'] in needed for x in bem_surfs): raise RuntimeError('Could not find necessary BEM surfaces') # reorder surfaces as necessary (shouldn't need to?) reorder = [None] * 3 for x in bem_surfs: reorder[np.where(x['id'] == needed)[0][0]] = x bem_surfs = reorder elif len(bem_surfs) == 1: if not bem_surfs[0]['id'] == FIFF.FIFFV_BEM_SURF_ID_BRAIN: raise RuntimeError('BEM Surfaces not found') logger.info('Homogeneous model surface loaded.') # convert from surfaces to solution bem = ConductorModel(is_sphere=False, surfs=bem_surfs) logger.info('\nLoading the solution matrix...\n') f, tree, _ = fiff_open(fname) with f as fid: # Find the BEM data nodes = dir_tree_find(tree, FIFF.FIFFB_BEM) if len(nodes) == 0: raise RuntimeError('No BEM data in %s' % fname) bem_node = nodes[0] # Approximation method tag = find_tag(f, bem_node, FIFF.FIFF_BEM_APPROX) if tag is None: raise RuntimeError('No BEM solution found in %s' % fname) method = tag.data[0] if method not in (FIFF.FIFFV_BEM_APPROX_CONST, FIFF.FIFFV_BEM_APPROX_LINEAR): raise RuntimeError('Cannot handle BEM approximation method : %d' % method) tag = find_tag(fid, bem_node, FIFF.FIFF_BEM_POT_SOLUTION) dims = tag.data.shape if len(dims) != 2: raise RuntimeError('Expected a two-dimensional solution matrix ' 'instead of a %d dimensional one' % dims[0]) dim = 0 for surf in bem['surfs']: if method == FIFF.FIFFV_BEM_APPROX_LINEAR: dim += surf['np'] else: # method == FIFF.FIFFV_BEM_APPROX_CONST dim += surf['ntri'] if dims[0] != dim or dims[1] != dim: raise RuntimeError('Expected a %d x %d solution matrix instead of ' 'a %d x %d one' % (dim, dim, dims[1], dims[0])) sol = tag.data nsol = dims[0] bem['solution'] = sol bem['nsol'] = nsol bem['bem_method'] = method # Gamma factors and multipliers _add_gamma_multipliers(bem) kind = { FIFF.FIFFV_BEM_APPROX_CONST: 'constant collocation', FIFF.FIFFV_BEM_APPROX_LINEAR: 'linear_collocation', }[bem['bem_method']] logger.info('Loaded %s BEM solution from %s', kind, fname) return bem def _add_gamma_multipliers(bem): """Add gamma and multipliers in-place.""" bem['sigma'] = np.array([surf['sigma'] for surf in bem['surfs']]) # Dirty trick for the zero conductivity outside sigma = np.r_[0.0, bem['sigma']] bem['source_mult'] = 2.0 / (sigma[1:] + sigma[:-1]) bem['field_mult'] = sigma[1:] - sigma[:-1] # make sure subsequent "zip"s work correctly assert len(bem['surfs']) == len(bem['field_mult']) bem['gamma'] = ((sigma[1:] - sigma[:-1])[np.newaxis, :] / (sigma[1:] + sigma[:-1])[:, np.newaxis]) _surf_dict = {'inner_skull': FIFF.FIFFV_BEM_SURF_ID_BRAIN, 'outer_skull': FIFF.FIFFV_BEM_SURF_ID_SKULL, 'head': FIFF.FIFFV_BEM_SURF_ID_HEAD} def _bem_find_surface(bem, id_): """Find surface from already-loaded BEM.""" if isinstance(id_, string_types): name = id_ id_ = _surf_dict[id_] else: name = _bem_explain_surface(id_) idx = np.where(np.array([s['id'] for s in bem['surfs']]) == id_)[0] if len(idx) != 1: raise RuntimeError('BEM model does not have the %s triangulation' % name.replace('_', ' ')) return bem['surfs'][idx[0]] def _bem_explain_surface(id_): """Return a string corresponding to the given surface ID.""" _rev_dict = dict((val, key) for key, val in _surf_dict.items()) return _rev_dict[id_] # ############################################################################ # Write def write_bem_surfaces(fname, surfs): """Write BEM surfaces to a fiff file. Parameters ---------- fname : str Filename to write. surfs : dict | list of dict The surfaces, or a single surface. """ if isinstance(surfs, dict): surfs = [surfs] with start_file(fname) as fid: start_block(fid, FIFF.FIFFB_BEM) write_int(fid, FIFF.FIFF_BEM_COORD_FRAME, surfs[0]['coord_frame']) _write_bem_surfaces_block(fid, surfs) end_block(fid, FIFF.FIFFB_BEM) end_file(fid) def _write_bem_surfaces_block(fid, surfs): """Write bem surfaces to open file handle.""" for surf in surfs: start_block(fid, FIFF.FIFFB_BEM_SURF) write_float(fid, FIFF.FIFF_BEM_SIGMA, surf['sigma']) write_int(fid, FIFF.FIFF_BEM_SURF_ID, surf['id']) write_int(fid, FIFF.FIFF_MNE_COORD_FRAME, surf['coord_frame']) write_int(fid, FIFF.FIFF_BEM_SURF_NNODE, surf['np']) write_int(fid, FIFF.FIFF_BEM_SURF_NTRI, surf['ntri']) write_float_matrix(fid, FIFF.FIFF_BEM_SURF_NODES, surf['rr']) # index start at 0 in Python write_int_matrix(fid, FIFF.FIFF_BEM_SURF_TRIANGLES, surf['tris'] + 1) if 'nn' in surf and surf['nn'] is not None and len(surf['nn']) > 0: write_float_matrix(fid, FIFF.FIFF_BEM_SURF_NORMALS, surf['nn']) end_block(fid, FIFF.FIFFB_BEM_SURF) def write_bem_solution(fname, bem): """Write a BEM model with solution. Parameters ---------- fname : str The filename to use. bem : instance of ConductorModel The BEM model with solution to save. See Also -------- read_bem_solution """ _check_bem_size(bem['surfs']) with start_file(fname) as fid: start_block(fid, FIFF.FIFFB_BEM) # Coordinate frame (mainly for backward compatibility) write_int(fid, FIFF.FIFF_BEM_COORD_FRAME, bem['surfs'][0]['coord_frame']) # Surfaces _write_bem_surfaces_block(fid, bem['surfs']) # The potential solution if 'solution' in bem: if bem['bem_method'] != FIFF.FWD_BEM_LINEAR_COLL: raise RuntimeError('Only linear collocation supported') write_int(fid, FIFF.FIFF_BEM_APPROX, FIFF.FIFFV_BEM_APPROX_LINEAR) write_float_matrix(fid, FIFF.FIFF_BEM_POT_SOLUTION, bem['solution']) end_block(fid, FIFF.FIFFB_BEM) end_file(fid) # ############################################################################# # Create 3-Layers BEM model from Flash MRI images def _prepare_env(subject, subjects_dir, requires_freesurfer): """Prepare an env object for subprocess calls.""" env = os.environ.copy() if requires_freesurfer and not os.environ.get('FREESURFER_HOME'): raise RuntimeError('I cannot find freesurfer. The FREESURFER_HOME ' 'environment variable is not set.') if not isinstance(subject, string_types): raise TypeError('The subject argument must be set') subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) if not op.isdir(subjects_dir): raise RuntimeError('Could not find the MRI data directory "%s"' % subjects_dir) subject_dir = op.join(subjects_dir, subject) if not op.isdir(subject_dir): raise RuntimeError('Could not find the subject data directory "%s"' % (subject_dir,)) env['SUBJECT'] = subject env['SUBJECTS_DIR'] = subjects_dir mri_dir = op.join(subject_dir, 'mri') bem_dir = op.join(subject_dir, 'bem') return env, mri_dir, bem_dir @verbose def convert_flash_mris(subject, flash30=True, convert=True, unwarp=False, subjects_dir=None, verbose=None): """Convert DICOM files for use with make_flash_bem. Parameters ---------- subject : str Subject name. flash30 : bool Use 30-degree flip angle data. convert : bool Assume that the Flash MRI images have already been converted to mgz files. unwarp : bool Run grad_unwarp with -unwarp option on each of the converted data sets. It requires FreeSurfer's MATLAB toolbox to be properly installed. subjects_dir : string, or None Path to SUBJECTS_DIR if it is not set in the environment. verbose : bool, str, int, or None If not None, override default verbose level (see :func:`mne.verbose` and :ref:`Logging documentation <tut_logging>` for more). Notes ----- Before running this script do the following: (unless convert=False is specified) 1. Copy all of your FLASH images in a single directory <source> and create a directory <dest> to hold the output of mne_organize_dicom 2. cd to <dest> and run $ mne_organize_dicom <source> to create an appropriate directory structure 3. Create symbolic links to make flash05 and flash30 point to the appropriate series: $ ln -s <FLASH 5 series dir> flash05 $ ln -s <FLASH 30 series dir> flash30 Some partition formats (e.g. FAT32) do not support symbolic links. In this case, copy the file to the appropriate series: $ cp <FLASH 5 series dir> flash05 $ cp <FLASH 30 series dir> flash30 4. cd to the directory where flash05 and flash30 links are 5. Set SUBJECTS_DIR and SUBJECT environment variables appropriately 6. Run this script This function assumes that the Freesurfer segmentation of the subject has been completed. In particular, the T1.mgz and brain.mgz MRI volumes should be, as usual, in the subject's mri directory. """ env, mri_dir = _prepare_env(subject, subjects_dir, requires_freesurfer=True)[:2] curdir = os.getcwd() # Step 1a : Data conversion to mgz format if not op.exists(op.join(mri_dir, 'flash', 'parameter_maps')): os.makedirs(op.join(mri_dir, 'flash', 'parameter_maps')) echos_done = 0 if convert: logger.info("\n---- Converting Flash images ----") echos = ['001', '002', '003', '004', '005', '006', '007', '008'] if flash30: flashes = ['05'] else: flashes = ['05', '30'] # missing = False for flash in flashes: for echo in echos: if not op.isdir(op.join('flash' + flash, echo)): missing = True if missing: echos = ['002', '003', '004', '005', '006', '007', '008', '009'] for flash in flashes: for echo in echos: if not op.isdir(op.join('flash' + flash, echo)): raise RuntimeError("Directory %s is missing." % op.join('flash' + flash, echo)) # for flash in flashes: for echo in echos: if not op.isdir(op.join('flash' + flash, echo)): raise RuntimeError("Directory %s is missing." % op.join('flash' + flash, echo)) sample_file = glob.glob(op.join('flash' + flash, echo, '*'))[0] dest_file = op.join(mri_dir, 'flash', 'mef' + flash + '_' + echo + '.mgz') # do not redo if already present if op.isfile(dest_file): logger.info("The file %s is already there") else: cmd = ['mri_convert', sample_file, dest_file] run_subprocess(cmd, env=env) echos_done += 1 # Step 1b : Run grad_unwarp on converted files os.chdir(op.join(mri_dir, "flash")) files = glob.glob("mef*.mgz") if unwarp: logger.info("\n---- Unwarp mgz data sets ----") for infile in files: outfile = infile.replace(".mgz", "u.mgz") cmd = ['grad_unwarp', '-i', infile, '-o', outfile, '-unwarp', 'true'] run_subprocess(cmd, env=env) # Clear parameter maps if some of the data were reconverted if echos_done > 0 and op.exists("parameter_maps"): shutil.rmtree("parameter_maps") logger.info("\nParameter maps directory cleared") if not op.exists("parameter_maps"): os.makedirs("parameter_maps") # Step 2 : Create the parameter maps if flash30: logger.info("\n---- Creating the parameter maps ----") if unwarp: files = glob.glob("mef05*u.mgz") if len(os.listdir('parameter_maps')) == 0: cmd = ['mri_ms_fitparms'] + files + ['parameter_maps'] run_subprocess(cmd, env=env) else: logger.info("Parameter maps were already computed") # Step 3 : Synthesize the flash 5 images logger.info("\n---- Synthesizing flash 5 images ----") os.chdir('parameter_maps') if not op.exists('flash5.mgz'): cmd = ['mri_synthesize', '20 5 5', 'T1.mgz', 'PD.mgz', 'flash5.mgz'] run_subprocess(cmd, env=env) os.remove('flash5_reg.mgz') else: logger.info("Synthesized flash 5 volume is already there") else: logger.info("\n---- Averaging flash5 echoes ----") os.chdir('parameter_maps') if unwarp: files = glob.glob("mef05*u.mgz") else: files = glob.glob("mef05*.mgz") cmd = ['mri_average', '-noconform', files, 'flash5.mgz'] run_subprocess(cmd, env=env) if op.exists('flash5_reg.mgz'): os.remove('flash5_reg.mgz') # Go back to initial directory os.chdir(curdir) @verbose def make_flash_bem(subject, overwrite=False, show=True, subjects_dir=None, flash_path=None, verbose=None): """Create 3-Layer BEM model from prepared flash MRI images. Parameters ---------- subject : str Subject name. overwrite : bool Write over existing .surf files in bem folder. show : bool Show surfaces to visually inspect all three BEM surfaces (recommended). subjects_dir : string, or None Path to SUBJECTS_DIR if it is not set in the environment. flash_path : str | None Path to the flash images. If None (default), mri/flash/parameter_maps within the subject reconstruction is used. .. versionadded:: 0.13.0 verbose : bool, str, int, or None If not None, override default verbose level (see :func:`mne.verbose` and :ref:`Logging documentation <tut_logging>` for more). Notes ----- This program assumes that FreeSurfer is installed and sourced properly. This function extracts the BEM surfaces (outer skull, inner skull, and outer skin) from multiecho FLASH MRI data with spin angles of 5 and 30 degrees, in mgz format. See Also -------- convert_flash_mris """ from .viz.misc import plot_bem is_test = os.environ.get('MNE_SKIP_FS_FLASH_CALL', False) env, mri_dir, bem_dir = _prepare_env(subject, subjects_dir, requires_freesurfer=True) if flash_path is None: flash_path = op.join(mri_dir, 'flash', 'parameter_maps') else: flash_path = op.abspath(flash_path) curdir = os.getcwd() subjects_dir = env['SUBJECTS_DIR'] logger.info('\nProcessing the flash MRI data to produce BEM meshes with ' 'the following parameters:\n' 'SUBJECTS_DIR = %s\n' 'SUBJECT = %s\n' 'Result dir = %s\n' % (subjects_dir, subject, op.join(bem_dir, 'flash'))) # Step 4 : Register with MPRAGE logger.info("\n---- Registering flash 5 with MPRAGE ----") flash5 = op.join(flash_path, 'flash5.mgz') flash5_reg = op.join(flash_path, 'flash5_reg.mgz') if not op.exists(flash5_reg): if op.exists(op.join(mri_dir, 'T1.mgz')): ref_volume = op.join(mri_dir, 'T1.mgz') else: ref_volume = op.join(mri_dir, 'T1') cmd = ['fsl_rigid_register', '-r', ref_volume, '-i', flash5, '-o', flash5_reg] run_subprocess(cmd, env=env) else: logger.info("Registered flash 5 image is already there") # Step 5a : Convert flash5 into COR logger.info("\n---- Converting flash5 volume into COR format ----") shutil.rmtree(op.join(mri_dir, 'flash5'), ignore_errors=True) os.makedirs(op.join(mri_dir, 'flash5')) if not is_test: # CIs don't have freesurfer, skipped when testing. cmd = ['mri_convert', flash5_reg, op.join(mri_dir, 'flash5')] run_subprocess(cmd, env=env) # Step 5b and c : Convert the mgz volumes into COR os.chdir(mri_dir) convert_T1 = False if not op.isdir('T1') or len(glob.glob(op.join('T1', 'COR*'))) == 0: convert_T1 = True convert_brain = False if not op.isdir('brain') or len(glob.glob(op.join('brain', 'COR*'))) == 0: convert_brain = True logger.info("\n---- Converting T1 volume into COR format ----") if convert_T1: if not op.isfile('T1.mgz'): raise RuntimeError("Both T1 mgz and T1 COR volumes missing.") os.makedirs('T1') cmd = ['mri_convert', 'T1.mgz', 'T1'] run_subprocess(cmd, env=env) else: logger.info("T1 volume is already in COR format") logger.info("\n---- Converting brain volume into COR format ----") if convert_brain: if not op.isfile('brain.mgz'): raise RuntimeError("Both brain mgz and brain COR volumes missing.") os.makedirs('brain') cmd = ['mri_convert', 'brain.mgz', 'brain'] run_subprocess(cmd, env=env) else: logger.info("Brain volume is already in COR format") # Finally ready to go if not is_test: # CIs don't have freesurfer, skipped when testing. logger.info("\n---- Creating the BEM surfaces ----") cmd = ['mri_make_bem_surfaces', subject] run_subprocess(cmd, env=env) logger.info("\n---- Converting the tri files into surf files ----") os.chdir(bem_dir) if not op.exists('flash'): os.makedirs('flash') os.chdir('flash') surfs = ['inner_skull', 'outer_skull', 'outer_skin'] for surf in surfs: shutil.move(op.join(bem_dir, surf + '.tri'), surf + '.tri') nodes, tris = read_tri(surf + '.tri', swap=True) vol_info = _extract_volume_info(flash5_reg) if vol_info is None: warn('nibabel is required to update the volume info. Volume info ' 'omitted from the written surface.') else: vol_info['head'] = np.array([20]) write_surface(surf + '.surf', nodes, tris, volume_info=vol_info) # Cleanup section logger.info("\n---- Cleaning up ----") os.chdir(bem_dir) os.remove('inner_skull_tmp.tri') os.chdir(mri_dir) if convert_T1: shutil.rmtree('T1') logger.info("Deleted the T1 COR volume") if convert_brain: shutil.rmtree('brain') logger.info("Deleted the brain COR volume") shutil.rmtree('flash5') logger.info("Deleted the flash5 COR volume") # Create symbolic links to the .surf files in the bem folder logger.info("\n---- Creating symbolic links ----") os.chdir(bem_dir) for surf in surfs: surf = surf + '.surf' if not overwrite and op.exists(surf): skip_symlink = True else: if op.exists(surf): os.remove(surf) _symlink(op.join('flash', surf), op.join(surf)) skip_symlink = False if skip_symlink: logger.info("Unable to create all symbolic links to .surf files " "in bem folder. Use --overwrite option to recreate them.") dest = op.join(bem_dir, 'flash') else: logger.info("Symbolic links to .surf files created in bem folder") dest = bem_dir logger.info("\nThank you for waiting.\nThe BEM triangulations for this " "subject are now available at:\n%s.\nWe hope the BEM meshes " "created will facilitate your MEG and EEG data analyses." % dest) # Show computed BEM surfaces if show: plot_bem(subject=subject, subjects_dir=subjects_dir, orientation='coronal', slices=None, show=True) # Go back to initial directory os.chdir(curdir) def _check_bem_size(surfs): """Check bem surface sizes.""" if len(surfs) > 1 and surfs[0]['np'] > 10000: warn('The bem surfaces have %s data points. 5120 (ico grade=4) ' 'should be enough. Dense 3-layer bems may not save properly.' % surfs[0]['np']) def _symlink(src, dest): """Create a symlink.""" try: os.symlink(src, dest) except OSError: warn('Could not create symbolic link %s. Check that your partition ' 'handles symbolic links. The file will be copied instead.' % dest) shutil.copy(src, dest)
37.822513
79
0.584087
from functools import partial import glob import os import os.path as op import shutil from copy import deepcopy import numpy as np from scipy import linalg from .transforms import _ensure_trans, apply_trans from .io import Info from .io.constants import FIFF from .io.write import (start_file, start_block, write_float, write_int, write_float_matrix, write_int_matrix, end_block, end_file) from .io.tag import find_tag from .io.tree import dir_tree_find from .io.open import fiff_open from .surface import (read_surface, write_surface, complete_surface_info, _compute_nearest, _get_ico_surface, read_tri, _fast_cross_nd_sum, _get_solids) from .utils import verbose, logger, run_subprocess, get_subjects_dir, warn, _pl from .fixes import einsum from .externals.six import string_types rf['tris'].ravel() misses = pi2 - mat.sum(axis=1) for j, miss in enumerate(misses): # How much is missing? n_memb = len(surf['neighbor_tri'][j]) # The node itself receives one half mat[j, j] = miss / 2.0 # The rest is divided evenly among the member nodes... miss /= (4.0 * n_memb) members = np.where(j == tris_flat)[0] mods = members % 3 offsets = np.array([[1, 2], [-1, 1], [-1, -2]]) tri_1 = members + offsets[mods, 0] tri_2 = members + offsets[mods, 1] for t1, t2 in zip(tri_1, tri_2): mat[j, tris_flat[t1]] += miss mat[j, tris_flat[t2]] += miss return def _fwd_bem_lin_pot_coeff(surfs): # taken from fwd_bem_linear_collocation.c nps = [surf['np'] for surf in surfs] np_tot = sum(nps) coeff = np.zeros((np_tot, np_tot)) offsets = np.cumsum(np.concatenate(([0], nps))) for si_1, surf1 in enumerate(surfs): rr_ord = np.arange(nps[si_1]) for si_2, surf2 in enumerate(surfs): logger.info(" %s (%d) -> %s (%d) ..." % (_bem_explain_surface(surf1['id']), nps[si_1], _bem_explain_surface(surf2['id']), nps[si_2])) tri_rr = surf2['rr'][surf2['tris']] tri_nn = surf2['tri_nn'] tri_area = surf2['tri_area'] submat = coeff[offsets[si_1]:offsets[si_1 + 1], offsets[si_2]:offsets[si_2 + 1]] # view for k in range(surf2['ntri']): tri = surf2['tris'][k] if si_1 == si_2: skip_idx = ((rr_ord == tri[0]) | (rr_ord == tri[1]) | (rr_ord == tri[2])) else: skip_idx = list() # No contribution from a triangle that # this vertex belongs to # if sidx1 == sidx2 and (tri == j).any(): # continue # Otherwise do the hard job coeffs = _lin_pot_coeff(surf1['rr'], tri_rr[k], tri_nn[k], tri_area[k]) coeffs[skip_idx] = 0. submat[:, tri] -= coeffs if si_1 == si_2: _correct_auto_elements(surf1, submat) return coeff def _fwd_bem_multi_solution(solids, gamma, nps): pi2 = 1.0 / (2 * np.pi) n_tot = np.sum(nps) assert solids.shape == (n_tot, n_tot) nsurf = len(nps) defl = 1.0 / n_tot # Modify the matrix offsets = np.cumsum(np.concatenate(([0], nps))) for si_1 in range(nsurf): for si_2 in range(nsurf): mult = pi2 if gamma is None else pi2 * gamma[si_1, si_2] slice_j = slice(offsets[si_1], offsets[si_1 + 1]) slice_k = slice(offsets[si_2], offsets[si_2 + 1]) solids[slice_j, slice_k] = defl - solids[slice_j, slice_k] * mult solids += np.eye(n_tot) return linalg.inv(solids, overwrite_a=True) def _fwd_bem_homog_solution(solids, nps): return _fwd_bem_multi_solution(solids, None, nps) def _fwd_bem_ip_modify_solution(solution, ip_solution, ip_mult, n_tri): n_last = n_tri[-1] mult = (1.0 + ip_mult) / ip_mult logger.info(' Combining...') offsets = np.cumsum(np.concatenate(([0], n_tri))) for si in range(len(n_tri)): # Pick the correct submatrix (right column) and multiply sub = solution[offsets[si]:offsets[si + 1], np.sum(n_tri[:-1]):] # Multiply sub -= 2 * np.dot(sub, ip_solution) # The lower right corner is a special case sub[-n_last:, -n_last:] += mult * ip_solution # Final scaling logger.info(' Scaling...') solution *= ip_mult return def _fwd_bem_linear_collocation_solution(m): # first, add surface geometries for surf in m['surfs']: complete_surface_info(surf, copy=False, verbose=False) logger.info('Computing the linear collocation solution...') logger.info(' Matrix coefficients...') coeff = _fwd_bem_lin_pot_coeff(m['surfs']) m['nsol'] = len(coeff) logger.info(" Inverting the coefficient matrix...") nps = [surf['np'] for surf in m['surfs']] m['solution'] = _fwd_bem_multi_solution(coeff, m['gamma'], nps) if len(m['surfs']) == 3: ip_mult = m['sigma'][1] / m['sigma'][2] if ip_mult <= FIFF.FWD_BEM_IP_APPROACH_LIMIT: logger.info('IP approach required...') logger.info(' Matrix coefficients (homog)...') coeff = _fwd_bem_lin_pot_coeff([m['surfs'][-1]]) logger.info(' Inverting the coefficient matrix (homog)...') ip_solution = _fwd_bem_homog_solution(coeff, [m['surfs'][-1]['np']]) logger.info(' Modify the original solution to incorporate ' 'IP approach...') _fwd_bem_ip_modify_solution(m['solution'], ip_solution, ip_mult, nps) m['bem_method'] = FIFF.FWD_BEM_LINEAR_COLL logger.info("Solution ready.") @verbose def make_bem_solution(surfs, verbose=None): logger.info('Approximation method : Linear collocation\n') if isinstance(surfs, string_types): # Load the surfaces logger.info('Loading surfaces...') surfs = read_bem_surfaces(surfs) bem = ConductorModel(is_sphere=False, surfs=surfs) _add_gamma_multipliers(bem) if len(bem['surfs']) == 3: logger.info('Three-layer model surfaces loaded.') elif len(bem['surfs']) == 1: logger.info('Homogeneous model surface loaded.') else: raise RuntimeError('Only 1- or 3-layer BEM computations supported') _check_bem_size(bem['surfs']) _fwd_bem_linear_collocation_solution(bem) logger.info('BEM geometry computations complete.') return bem # ############################################################################ # Make BEM model def _ico_downsample(surf, dest_grade): n_tri = len(surf['tris']) found = -1 bad_msg = ("A surface with %d triangles cannot be isomorphic with a " "subdivided icosahedron." % n_tri) if n_tri % 20 != 0: raise RuntimeError(bad_msg) n_tri = n_tri // 20 found = int(round(np.log(n_tri) / np.log(4))) if n_tri != 4 ** found: raise RuntimeError(bad_msg) del n_tri if dest_grade > found: raise RuntimeError('For this surface, decimation grade should be %d ' 'or less, not %s.' % (found, dest_grade)) source = _get_ico_surface(found) dest = _get_ico_surface(dest_grade, patch_stats=True) del dest['tri_cent'] del dest['tri_nn'] del dest['neighbor_tri'] del dest['tri_area'] if not np.array_equal(source['tris'], surf['tris']): raise RuntimeError('The source surface has a matching number of ' 'triangles but ordering is wrong') logger.info('Going from %dth to %dth subdivision of an icosahedron ' '(n_tri: %d -> %d)' % (found, dest_grade, len(surf['tris']), len(dest['tris']))) # Find the mapping dest['rr'] = surf['rr'][_get_ico_map(source, dest)] return dest def _get_ico_map(fro, to): nearest, dists = _compute_nearest(fro['rr'], to['rr'], return_dists=True) n_bads = (dists > 5e-3).sum() if n_bads > 0: raise RuntimeError('No matching vertex for %d destination vertices' % (n_bads)) return nearest def _order_surfaces(surfs): if len(surfs) != 3: return surfs # we have three surfaces surf_order = [FIFF.FIFFV_BEM_SURF_ID_HEAD, FIFF.FIFFV_BEM_SURF_ID_SKULL, FIFF.FIFFV_BEM_SURF_ID_BRAIN] ids = np.array([surf['id'] for surf in surfs]) if set(ids) != set(surf_order): raise RuntimeError('bad surface ids: %s' % ids) order = [np.where(ids == id_)[0][0] for id_ in surf_order] surfs = [surfs[idx] for idx in order] return surfs def _assert_complete_surface(surf, incomplete='raise'): # from surface_checks.c tot_angle = 0. # Center of mass.... cm = surf['rr'].mean(axis=0) logger.info('%s CM is %6.2f %6.2f %6.2f mm' % (_surf_name[surf['id']], 1000 * cm[0], 1000 * cm[1], 1000 * cm[2])) tot_angle = _get_solids(surf['rr'][surf['tris']], cm[np.newaxis, :])[0] prop = tot_angle / (2 * np.pi) if np.abs(prop - 1.0) > 1e-5: msg = ('Surface %s is not complete (sum of solid angles ' 'yielded %g, should be 1.)' % (_surf_name[surf['id']], prop)) if incomplete == 'raise': raise RuntimeError(msg) else: warn(msg) _surf_name = { FIFF.FIFFV_BEM_SURF_ID_HEAD: 'outer skin ', FIFF.FIFFV_BEM_SURF_ID_SKULL: 'outer skull', FIFF.FIFFV_BEM_SURF_ID_BRAIN: 'inner skull', FIFF.FIFFV_BEM_SURF_ID_UNKNOWN: 'unknown ', } def _assert_inside(fro, to): # this is "is_inside" in surface_checks.c tot_angle = _get_solids(to['rr'][to['tris']], fro['rr']) if (np.abs(tot_angle / (2 * np.pi) - 1.0) > 1e-5).any(): raise RuntimeError('Surface %s is not completely inside surface %s' % (_surf_name[fro['id']], _surf_name[to['id']])) def _check_surfaces(surfs, incomplete='raise'): for surf in surfs: _assert_complete_surface(surf, incomplete=incomplete) # Then check the topology for surf_1, surf_2 in zip(surfs[:-1], surfs[1:]): logger.info('Checking that %s surface is inside %s surface...' % (_surf_name[surf_2['id']], _surf_name[surf_1['id']])) _assert_inside(surf_2, surf_1) def _check_surface_size(surf): sizes = surf['rr'].max(axis=0) - surf['rr'].min(axis=0) if (sizes < 0.05).any(): raise RuntimeError('Dimensions of the surface %s seem too small ' '(%9.5f mm). Maybe the the unit of measure is ' 'meters instead of mm' % (_surf_name[surf['id']], 1000 * sizes.min())) def _check_thicknesses(surfs): for surf_1, surf_2 in zip(surfs[:-1], surfs[1:]): min_dist = _compute_nearest(surf_1['rr'], surf_2['rr'], return_dists=True)[0] min_dist = min_dist.min() logger.info('Checking distance between %s and %s surfaces...' % (_surf_name[surf_1['id']], _surf_name[surf_2['id']])) logger.info('Minimum distance between the %s and %s surfaces is ' 'approximately %6.1f mm' % (_surf_name[surf_1['id']], _surf_name[surf_2['id']], 1000 * min_dist)) def _surfaces_to_bem(surfs, ids, sigmas, ico=None, rescale=True, incomplete='raise'): # equivalent of mne_surf2bem # surfs can be strings (filenames) or surface dicts if len(surfs) not in (1, 3) or not (len(surfs) == len(ids) == len(sigmas)): raise ValueError('surfs, ids, and sigmas must all have the same ' 'number of elements (1 or 3)') surf = list(surfs) for si, surf in enumerate(surfs): if isinstance(surf, string_types): surfs[si] = read_surface(surf, return_dict=True)[-1] # Downsampling if the surface is isomorphic with a subdivided icosahedron if ico is not None: for si, surf in enumerate(surfs): surfs[si] = _ico_downsample(surf, ico) for surf, id_ in zip(surfs, ids): surf['id'] = id_ surf['coord_frame'] = surf.get('coord_frame', FIFF.FIFFV_COORD_MRI) surf.update(np=len(surf['rr']), ntri=len(surf['tris'])) if rescale: surf['rr'] /= 1000. # convert to meters # Shifting surfaces is not implemented here... # Order the surfaces for the benefit of the topology checks for surf, sigma in zip(surfs, sigmas): surf['sigma'] = sigma surfs = _order_surfaces(surfs) # Check topology as best we can _check_surfaces(surfs, incomplete=incomplete) for surf in surfs: _check_surface_size(surf) _check_thicknesses(surfs) logger.info('Surfaces passed the basic topology checks.') return surfs @verbose def make_bem_model(subject, ico=4, conductivity=(0.3, 0.006, 0.3), subjects_dir=None, verbose=None): conductivity = np.array(conductivity, float) if conductivity.ndim != 1 or conductivity.size not in (1, 3): raise ValueError('conductivity must be 1D array-like with 1 or 3 ' 'elements') subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) subject_dir = op.join(subjects_dir, subject) bem_dir = op.join(subject_dir, 'bem') inner_skull = op.join(bem_dir, 'inner_skull.surf') outer_skull = op.join(bem_dir, 'outer_skull.surf') outer_skin = op.join(bem_dir, 'outer_skin.surf') surfaces = [inner_skull, outer_skull, outer_skin] ids = [FIFF.FIFFV_BEM_SURF_ID_BRAIN, FIFF.FIFFV_BEM_SURF_ID_SKULL, FIFF.FIFFV_BEM_SURF_ID_HEAD] logger.info('Creating the BEM geometry...') if len(conductivity) == 1: surfaces = surfaces[:1] ids = ids[:1] surfaces = _surfaces_to_bem(surfaces, ids, conductivity, ico) _check_bem_size(surfaces) logger.info('Complete.\n') return surfaces # ############################################################################ # Compute EEG sphere model def _fwd_eeg_get_multi_sphere_model_coeffs(m, n_terms): nlayer = len(m['layers']) if nlayer in (0, 1): return 1. # Initialize the arrays c1 = np.zeros(nlayer - 1) c2 = np.zeros(nlayer - 1) cr = np.zeros(nlayer - 1) cr_mult = np.zeros(nlayer - 1) for k in range(nlayer - 1): c1[k] = m['layers'][k]['sigma'] / m['layers'][k + 1]['sigma'] c2[k] = c1[k] - 1.0 cr_mult[k] = m['layers'][k]['rel_rad'] cr[k] = cr_mult[k] cr_mult[k] *= cr_mult[k] coeffs = np.zeros(n_terms - 1) for n in range(1, n_terms): # Increment the radius coefficients for k in range(nlayer - 1): cr[k] *= cr_mult[k] # Multiply the matrices M = np.eye(2) n1 = n + 1.0 for k in range(nlayer - 2, -1, -1): M = np.dot([[n + n1 * c1[k], n1 * c2[k] / cr[k]], [n * c2[k] * cr[k], n1 + n * c1[k]]], M) num = n * (2.0 * n + 1.0) ** (nlayer - 1) coeffs[n - 1] = num / (n * M[1, 1] + n1 * M[1, 0]) return coeffs def _compose_linear_fitting_data(mu, u): # y is the data to be fitted (nterms-1 x 1) # M is the model matrix (nterms-1 x nfit-1) for k in range(u['nterms'] - 1): k1 = k + 1 mu1n = np.power(mu[0], k1) u['y'][k] = u['w'][k] * (u['fn'][k1] - mu1n * u['fn'][0]) for p in range(u['nfit'] - 1): u['M'][k][p] = u['w'][k] * (np.power(mu[p + 1], k1) - mu1n) def _compute_linear_parameters(mu, u): _compose_linear_fitting_data(mu, u) uu, sing, vv = linalg.svd(u['M'], full_matrices=False) # Compute the residuals u['resi'] = u['y'].copy() vec = np.empty(u['nfit'] - 1) for p in range(u['nfit'] - 1): vec[p] = np.dot(uu[:, p], u['y']) for k in range(u['nterms'] - 1): u['resi'][k] -= uu[k, p] * vec[p] vec[p] = vec[p] / sing[p] lambda_ = np.zeros(u['nfit']) for p in range(u['nfit'] - 1): sum_ = 0. for q in range(u['nfit'] - 1): sum_ += vv[q, p] * vec[q] lambda_[p + 1] = sum_ lambda_[0] = u['fn'][0] - np.sum(lambda_[1:]) rv = np.dot(u['resi'], u['resi']) / np.dot(u['y'], u['y']) return rv, lambda_ def _one_step(mu, u): if np.abs(mu).max() > 1.0: return 1.0 # Compose the data for the linear fitting, compute SVD, then residuals _compose_linear_fitting_data(mu, u) u['uu'], u['sing'], u['vv'] = linalg.svd(u['M']) u['resi'][:] = u['y'][:] for p in range(u['nfit'] - 1): dot = np.dot(u['uu'][p], u['y']) for k in range(u['nterms'] - 1): u['resi'][k] = u['resi'][k] - u['uu'][p, k] * dot # Return their sum of squares return np.dot(u['resi'], u['resi']) def _fwd_eeg_fit_berg_scherg(m, nterms, nfit): from scipy.optimize import fmin_cobyla assert nfit >= 2 u = dict(y=np.zeros(nterms - 1), resi=np.zeros(nterms - 1), nfit=nfit, nterms=nterms, M=np.zeros((nterms - 1, nfit - 1))) # (1) Calculate the coefficients of the true expansion u['fn'] = _fwd_eeg_get_multi_sphere_model_coeffs(m, nterms + 1) # (2) Calculate the weighting f = (min([layer['rad'] for layer in m['layers']]) / max([layer['rad'] for layer in m['layers']])) # correct weighting k = np.arange(1, nterms + 1) u['w'] = np.sqrt((2.0 * k + 1) * (3.0 * k + 1.0) / k) * np.power(f, (k - 1.0)) u['w'][-1] = 0 # Do the nonlinear minimization, constraining mu to the interval [-1, +1] mu_0 = np.random.RandomState(0).rand(nfit) * f fun = partial(_one_step, u=u) max_ = 1. - 2e-4 # adjust for fmin_cobyla "catol" that not all scipy have cons = [(lambda x: max_ - np.abs(x[ii])) for ii in range(nfit)] mu = fmin_cobyla(fun, mu_0, cons, rhobeg=0.5, rhoend=5e-3, disp=0) # (6) Do the final step: calculation of the linear parameters rv, lambda_ = _compute_linear_parameters(mu, u) order = np.argsort(mu)[::-1] mu, lambda_ = mu[order], lambda_[order] # sort: largest mu first m['mu'] = mu # This division takes into account the actual conductivities m['lambda'] = lambda_ / m['layers'][-1]['sigma'] m['nfit'] = nfit return rv @verbose def make_sphere_model(r0=(0., 0., 0.04), head_radius=0.09, info=None, relative_radii=(0.90, 0.92, 0.97, 1.0), sigmas=(0.33, 1.0, 0.004, 0.33), verbose=None): for name in ('r0', 'head_radius'): param = locals()[name] if isinstance(param, string_types): if param != 'auto': raise ValueError('%s, if str, must be "auto" not "%s"' % (name, param)) relative_radii = np.array(relative_radii, float).ravel() sigmas = np.array(sigmas, float).ravel() if len(relative_radii) != len(sigmas): raise ValueError('relative_radii length (%s) must match that of ' 'sigmas (%s)' % (len(relative_radii), len(sigmas))) if len(sigmas) <= 1 and head_radius is not None: raise ValueError('at least 2 sigmas must be supplied if ' 'head_radius is not None, got %s' % (len(sigmas),)) if (isinstance(r0, string_types) and r0 == 'auto') or \ (isinstance(head_radius, string_types) and head_radius == 'auto'): if info is None: raise ValueError('Info must not be None for auto mode') head_radius_fit, r0_fit = fit_sphere_to_headshape(info, units='m')[:2] if isinstance(r0, string_types): r0 = r0_fit if isinstance(head_radius, string_types): head_radius = head_radius_fit sphere = ConductorModel(is_sphere=True, r0=np.array(r0), coord_frame=FIFF.FIFFV_COORD_HEAD) sphere['layers'] = list() if head_radius is not None: # Eventually these could be configurable... relative_radii = np.array(relative_radii, float) sigmas = np.array(sigmas, float) order = np.argsort(relative_radii) relative_radii = relative_radii[order] sigmas = sigmas[order] for rel_rad, sig in zip(relative_radii, sigmas): # sort layers by (relative) radius, and scale radii layer = dict(rad=rel_rad, sigma=sig) layer['rel_rad'] = layer['rad'] = rel_rad sphere['layers'].append(layer) # scale the radii R = sphere['layers'][-1]['rad'] rR = sphere['layers'][-1]['rel_rad'] for layer in sphere['layers']: layer['rad'] /= R layer['rel_rad'] /= rR # # Setup the EEG sphere model calculations # # Scale the relative radii for k in range(len(relative_radii)): sphere['layers'][k]['rad'] = (head_radius * sphere['layers'][k]['rel_rad']) rv = _fwd_eeg_fit_berg_scherg(sphere, 200, 3) logger.info('\nEquiv. model fitting -> RV = %g %%' % (100 * rv)) for k in range(3): logger.info('mu%d = %g lambda%d = %g' % (k + 1, sphere['mu'][k], k + 1, sphere['layers'][-1]['sigma'] * sphere['lambda'][k])) logger.info('Set up EEG sphere model with scalp radius %7.1f mm\n' % (1000 * head_radius,)) return sphere # ############################################################################# # Sphere fitting _dig_kind_dict = { 'cardinal': FIFF.FIFFV_POINT_CARDINAL, 'hpi': FIFF.FIFFV_POINT_HPI, 'eeg': FIFF.FIFFV_POINT_EEG, 'extra': FIFF.FIFFV_POINT_EXTRA, } _dig_kind_rev = dict((val, key) for key, val in _dig_kind_dict.items()) _dig_kind_ints = tuple(_dig_kind_dict.values()) @verbose def fit_sphere_to_headshape(info, dig_kinds='auto', units='m', verbose=None): if not isinstance(units, string_types) or units not in ('m', 'mm'): raise ValueError('units must be a "m" or "mm"') radius, origin_head, origin_device = _fit_sphere_to_headshape( info, dig_kinds) if units == 'mm': radius *= 1e3 origin_head *= 1e3 origin_device *= 1e3 return radius, origin_head, origin_device @verbose def get_fitting_dig(info, dig_kinds='auto', verbose=None): if not isinstance(info, Info): raise TypeError('info must be an instance of Info not %s' % type(info)) if info['dig'] is None: raise RuntimeError('Cannot fit headshape without digitization ' ', info["dig"] is None') if isinstance(dig_kinds, string_types): if dig_kinds == 'auto': # try "extra" first try: return get_fitting_dig(info, 'extra') except ValueError: pass return get_fitting_dig(info, ('extra', 'eeg')) else: dig_kinds = (dig_kinds,) # convert string args to ints (first make dig_kinds mutable in case tuple) dig_kinds = list(dig_kinds) for di, d in enumerate(dig_kinds): dig_kinds[di] = _dig_kind_dict.get(d, d) if dig_kinds[di] not in _dig_kind_ints: raise ValueError('dig_kinds[ % (di, d, sorted(list(_dig_kind_dict.keys())))) # get head digization points of the specified kind(s) hsp = [p['r'] for p in info['dig'] if p['kind'] in dig_kinds] if any(p['coord_frame'] != FIFF.FIFFV_COORD_HEAD for p in info['dig']): raise RuntimeError('Digitization points not in head coordinates, ' 'contact mne-python developers') # exclude some frontal points (nose etc.) hsp = np.array([p for p in hsp if not (p[2] < -1e-6 and p[1] > 1e-6)]) if len(hsp) <= 10: kinds_str = ', '.join(['"%s"' % _dig_kind_rev[d] for d in sorted(dig_kinds)]) msg = ('Only %s head digitization points of the specified kind%s (%s,)' % (len(hsp), _pl(dig_kinds), kinds_str)) if len(hsp) < 4: raise ValueError(msg + ', at least 4 required') else: warn(msg + ', fitting may be inaccurate') return hsp @verbose def _fit_sphere_to_headshape(info, dig_kinds, verbose=None): hsp = get_fitting_dig(info, dig_kinds) radius, origin_head = _fit_sphere(np.array(hsp), disp=False) # compute origin in device coordinates head_to_dev = _ensure_trans(info['dev_head_t'], 'head', 'meg') origin_device = apply_trans(head_to_dev, origin_head) logger.info('Fitted sphere radius:'.ljust(30) + '%0.1f mm' % (radius * 1e3,)) # 99th percentile on Wikipedia for Giabella to back of head is 21.7cm, # i.e. 108mm "radius", so let's go with 110mm rn('Estimated head size (%0.1f mm) exceeded 99th ' 'percentile for adult head size' % (1e3 * radius,)) if np.linalg.norm(origin_head[:2]) > 0.02: warn('(X, Y) fit (%0.1f, %0.1f) more than 20 mm from ' 'head frame origin' % tuple(1e3 * origin_head[:2])) logger.info('Origin head coordinates:'.ljust(30) + '%0.1f %0.1f %0.1f mm' % tuple(1e3 * origin_head)) logger.info('Origin device coordinates:'.ljust(30) + '%0.1f %0.1f %0.1f mm' % tuple(1e3 * origin_device)) return radius, origin_head, origin_device def _fit_sphere(points, disp='auto'): from scipy.optimize import fmin_cobyla if isinstance(disp, string_types) and disp == 'auto': disp = True if logger.level <= 20 else False radii = (np.max(points, axis=1) - np.min(points, axis=1)) / 2. radius_init = radii.mean() center_init = np.median(points, axis=0) x0 = np.concatenate([center_init, [radius_init]]) def cost_fun(center_rad): d = np.linalg.norm(points - center_rad[:3], axis=1) - center_rad[3] d *= d return d.sum() def constraint(center_rad): return center_rad[3] x_opt = fmin_cobyla(cost_fun, x0, constraint, rhobeg=radius_init, rhoend=radius_init * 1e-6, disp=disp) origin = x_opt[:3] radius = x_opt[3] return radius, origin def _check_origin(origin, info, coord_frame='head', disp=False): if isinstance(origin, string_types): if origin != 'auto': raise ValueError('origin must be a numerical array, or "auto", ' 'not %s' % (origin,)) if coord_frame == 'head': R, origin = fit_sphere_to_headshape(info, verbose=False, units='m')[:2] logger.info(' Automatic origin fit: head of radius %0.1f mm' % (R * 1000.,)) del R else: origin = (0., 0., 0.) origin = np.array(origin, float) if origin.shape != (3,): raise ValueError('origin must be a 3-element array') if disp: origin_str = ', '.join(['%0.1f' % (o * 1000) for o in origin]) msg = (' Using origin %s mm in the %s frame' % (origin_str, coord_frame)) if coord_frame == 'meg' and info['dev_head_t'] is not None: o_dev = apply_trans(info['dev_head_t'], origin) origin_str = ', '.join('%0.1f' % (o * 1000,) for o in o_dev) msg += ' (%s mm in the head frame)' % (origin_str,) logger.info(msg) return origin out): os.remove(surf_out) _symlink(surf_ws_out, surf_out) skip_symlink = False if skip_symlink: logger.info("Unable to create all symbolic links to .surf files " "in bem folder. Use --overwrite option to recreate " "them.") dest = op.join(bem_dir, 'watershed') else: logger.info("Symbolic links to .surf files created in bem folder") dest = bem_dir logger.info("\nThank you for waiting.\nThe BEM triangulations for this " "subject are now available at:\n%s." % dest) fname_head = op.join(bem_dir, subject + '-head.fif') if op.isfile(fname_head): os.remove(fname_head) surf = _surfaces_to_bem([op.join(ws_dir, subject + '_outer_skin_surface')], [FIFF.FIFFV_BEM_SURF_ID_HEAD], sigmas=[1]) write_bem_surfaces(fname_head, surf) if show: plot_bem(subject=subject, subjects_dir=subjects_dir, orientation='coronal', slices=None, show=True) logger.info('Created %s\n\nComplete.' % (fname_head,)) def _extract_volume_info(mgz, raise_error=True): try: import nibabel as nib except ImportError: return header = nib.load(mgz).header vol_info = dict() version = header['version'] if version == 1: version = '%s # volume info valid' % version else: raise ValueError('Volume info invalid.') vol_info['valid'] = version vol_info['filename'] = mgz vol_info['volume'] = header['dims'][:3] vol_info['voxelsize'] = header['delta'] vol_info['xras'], vol_info['yras'], vol_info['zras'] = header['Mdc'].T vol_info['cras'] = header['Pxyz_c'] return vol_info s, FIFF.FIFF_MNE_SOURCE_SPACE_NORMALS) if tag is None: tag = find_tag(fid, this, FIFF.FIFF_BEM_SURF_NORMALS) if tag is None: res['nn'] = None else: res['nn'] = tag.data.copy() if res['nn'].shape[0] != res['np']: raise ValueError('Vertex normal information is incorrect') tag = find_tag(fid, this, FIFF.FIFF_BEM_SURF_TRIANGLES) if tag is None: raise ValueError('Triangulation not found') res['tris'] = tag.data - 1 if res['tris'].shape[0] != res['ntri']: raise ValueError('Triangulation information is incorrect') return res @verbose def read_bem_solution(fname, verbose=None): logger.info('Loading surfaces...') bem_surfs = read_bem_surfaces(fname, patch_stats=True, verbose=False) if len(bem_surfs) == 3: logger.info('Three-layer model surfaces loaded.') needed = np.array([FIFF.FIFFV_BEM_SURF_ID_HEAD, FIFF.FIFFV_BEM_SURF_ID_SKULL, FIFF.FIFFV_BEM_SURF_ID_BRAIN]) if not all(x['id'] in needed for x in bem_surfs): raise RuntimeError('Could not find necessary BEM surfaces') reorder = [None] * 3 for x in bem_surfs: reorder[np.where(x['id'] == needed)[0][0]] = x bem_surfs = reorder elif len(bem_surfs) == 1: if not bem_surfs[0]['id'] == FIFF.FIFFV_BEM_SURF_ID_BRAIN: raise RuntimeError('BEM Surfaces not found') logger.info('Homogeneous model surface loaded.') # convert from surfaces to solution bem = ConductorModel(is_sphere=False, surfs=bem_surfs) logger.info('\nLoading the solution matrix...\n') f, tree, _ = fiff_open(fname) with f as fid: # Find the BEM data nodes = dir_tree_find(tree, FIFF.FIFFB_BEM) if len(nodes) == 0: raise RuntimeError('No BEM data in %s' % fname) bem_node = nodes[0] # Approximation method tag = find_tag(f, bem_node, FIFF.FIFF_BEM_APPROX) if tag is None: raise RuntimeError('No BEM solution found in %s' % fname) method = tag.data[0] if method not in (FIFF.FIFFV_BEM_APPROX_CONST, FIFF.FIFFV_BEM_APPROX_LINEAR): raise RuntimeError('Cannot handle BEM approximation method : %d' % method) tag = find_tag(fid, bem_node, FIFF.FIFF_BEM_POT_SOLUTION) dims = tag.data.shape if len(dims) != 2: raise RuntimeError('Expected a two-dimensional solution matrix ' 'instead of a %d dimensional one' % dims[0]) dim = 0 for surf in bem['surfs']: if method == FIFF.FIFFV_BEM_APPROX_LINEAR: dim += surf['np'] else: # method == FIFF.FIFFV_BEM_APPROX_CONST dim += surf['ntri'] if dims[0] != dim or dims[1] != dim: raise RuntimeError('Expected a %d x %d solution matrix instead of ' 'a %d x %d one' % (dim, dim, dims[1], dims[0])) sol = tag.data nsol = dims[0] bem['solution'] = sol bem['nsol'] = nsol bem['bem_method'] = method # Gamma factors and multipliers _add_gamma_multipliers(bem) kind = { FIFF.FIFFV_BEM_APPROX_CONST: 'constant collocation', FIFF.FIFFV_BEM_APPROX_LINEAR: 'linear_collocation', }[bem['bem_method']] logger.info('Loaded %s BEM solution from %s', kind, fname) return bem def _add_gamma_multipliers(bem): bem['sigma'] = np.array([surf['sigma'] for surf in bem['surfs']]) # Dirty trick for the zero conductivity outside sigma = np.r_[0.0, bem['sigma']] bem['source_mult'] = 2.0 / (sigma[1:] + sigma[:-1]) bem['field_mult'] = sigma[1:] - sigma[:-1] # make sure subsequent "zip"s work correctly assert len(bem['surfs']) == len(bem['field_mult']) bem['gamma'] = ((sigma[1:] - sigma[:-1])[np.newaxis, :] / (sigma[1:] + sigma[:-1])[:, np.newaxis]) _surf_dict = {'inner_skull': FIFF.FIFFV_BEM_SURF_ID_BRAIN, 'outer_skull': FIFF.FIFFV_BEM_SURF_ID_SKULL, 'head': FIFF.FIFFV_BEM_SURF_ID_HEAD} def _bem_find_surface(bem, id_): if isinstance(id_, string_types): name = id_ id_ = _surf_dict[id_] else: name = _bem_explain_surface(id_) idx = np.where(np.array([s['id'] for s in bem['surfs']]) == id_)[0] if len(idx) != 1: raise RuntimeError('BEM model does not have the %s triangulation' % name.replace('_', ' ')) return bem['surfs'][idx[0]] def _bem_explain_surface(id_): _rev_dict = dict((val, key) for key, val in _surf_dict.items()) return _rev_dict[id_] # ############################################################################ # Write def write_bem_surfaces(fname, surfs): if isinstance(surfs, dict): surfs = [surfs] with start_file(fname) as fid: start_block(fid, FIFF.FIFFB_BEM) write_int(fid, FIFF.FIFF_BEM_COORD_FRAME, surfs[0]['coord_frame']) _write_bem_surfaces_block(fid, surfs) end_block(fid, FIFF.FIFFB_BEM) end_file(fid) def _write_bem_surfaces_block(fid, surfs): for surf in surfs: start_block(fid, FIFF.FIFFB_BEM_SURF) write_float(fid, FIFF.FIFF_BEM_SIGMA, surf['sigma']) write_int(fid, FIFF.FIFF_BEM_SURF_ID, surf['id']) write_int(fid, FIFF.FIFF_MNE_COORD_FRAME, surf['coord_frame']) write_int(fid, FIFF.FIFF_BEM_SURF_NNODE, surf['np']) write_int(fid, FIFF.FIFF_BEM_SURF_NTRI, surf['ntri']) write_float_matrix(fid, FIFF.FIFF_BEM_SURF_NODES, surf['rr']) # index start at 0 in Python write_int_matrix(fid, FIFF.FIFF_BEM_SURF_TRIANGLES, surf['tris'] + 1) if 'nn' in surf and surf['nn'] is not None and len(surf['nn']) > 0: write_float_matrix(fid, FIFF.FIFF_BEM_SURF_NORMALS, surf['nn']) end_block(fid, FIFF.FIFFB_BEM_SURF) def write_bem_solution(fname, bem): _check_bem_size(bem['surfs']) with start_file(fname) as fid: start_block(fid, FIFF.FIFFB_BEM) # Coordinate frame (mainly for backward compatibility) write_int(fid, FIFF.FIFF_BEM_COORD_FRAME, bem['surfs'][0]['coord_frame']) # Surfaces _write_bem_surfaces_block(fid, bem['surfs']) # The potential solution if 'solution' in bem: if bem['bem_method'] != FIFF.FWD_BEM_LINEAR_COLL: raise RuntimeError('Only linear collocation supported') write_int(fid, FIFF.FIFF_BEM_APPROX, FIFF.FIFFV_BEM_APPROX_LINEAR) write_float_matrix(fid, FIFF.FIFF_BEM_POT_SOLUTION, bem['solution']) end_block(fid, FIFF.FIFFB_BEM) end_file(fid) # ############################################################################# # Create 3-Layers BEM model from Flash MRI images def _prepare_env(subject, subjects_dir, requires_freesurfer): env = os.environ.copy() if requires_freesurfer and not os.environ.get('FREESURFER_HOME'): raise RuntimeError('I cannot find freesurfer. The FREESURFER_HOME ' 'environment variable is not set.') if not isinstance(subject, string_types): raise TypeError('The subject argument must be set') subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) if not op.isdir(subjects_dir): raise RuntimeError('Could not find the MRI data directory "%s"' % subjects_dir) subject_dir = op.join(subjects_dir, subject) if not op.isdir(subject_dir): raise RuntimeError('Could not find the subject data directory "%s"' % (subject_dir,)) env['SUBJECT'] = subject env['SUBJECTS_DIR'] = subjects_dir mri_dir = op.join(subject_dir, 'mri') bem_dir = op.join(subject_dir, 'bem') return env, mri_dir, bem_dir @verbose def convert_flash_mris(subject, flash30=True, convert=True, unwarp=False, subjects_dir=None, verbose=None): env, mri_dir = _prepare_env(subject, subjects_dir, requires_freesurfer=True)[:2] curdir = os.getcwd() # Step 1a : Data conversion to mgz format if not op.exists(op.join(mri_dir, 'flash', 'parameter_maps')): os.makedirs(op.join(mri_dir, 'flash', 'parameter_maps')) echos_done = 0 if convert: logger.info("\n---- Converting Flash images ----") echos = ['001', '002', '003', '004', '005', '006', '007', '008'] if flash30: flashes = ['05'] else: flashes = ['05', '30'] # missing = False for flash in flashes: for echo in echos: if not op.isdir(op.join('flash' + flash, echo)): missing = True if missing: echos = ['002', '003', '004', '005', '006', '007', '008', '009'] for flash in flashes: for echo in echos: if not op.isdir(op.join('flash' + flash, echo)): raise RuntimeError("Directory %s is missing." % op.join('flash' + flash, echo)) # for flash in flashes: for echo in echos: if not op.isdir(op.join('flash' + flash, echo)): raise RuntimeError("Directory %s is missing." % op.join('flash' + flash, echo)) sample_file = glob.glob(op.join('flash' + flash, echo, '*'))[0] dest_file = op.join(mri_dir, 'flash', 'mef' + flash + '_' + echo + '.mgz') # do not redo if already present if op.isfile(dest_file): logger.info("The file %s is already there") else: cmd = ['mri_convert', sample_file, dest_file] run_subprocess(cmd, env=env) echos_done += 1 # Step 1b : Run grad_unwarp on converted files os.chdir(op.join(mri_dir, "flash")) files = glob.glob("mef*.mgz") if unwarp: logger.info("\n---- Unwarp mgz data sets ----") for infile in files: outfile = infile.replace(".mgz", "u.mgz") cmd = ['grad_unwarp', '-i', infile, '-o', outfile, '-unwarp', 'true'] run_subprocess(cmd, env=env) # Clear parameter maps if some of the data were reconverted if echos_done > 0 and op.exists("parameter_maps"): shutil.rmtree("parameter_maps") logger.info("\nParameter maps directory cleared") if not op.exists("parameter_maps"): os.makedirs("parameter_maps") # Step 2 : Create the parameter maps if flash30: logger.info("\n---- Creating the parameter maps ----") if unwarp: files = glob.glob("mef05*u.mgz") if len(os.listdir('parameter_maps')) == 0: cmd = ['mri_ms_fitparms'] + files + ['parameter_maps'] run_subprocess(cmd, env=env) else: logger.info("Parameter maps were already computed") # Step 3 : Synthesize the flash 5 images logger.info("\n---- Synthesizing flash 5 images ----") os.chdir('parameter_maps') if not op.exists('flash5.mgz'): cmd = ['mri_synthesize', '20 5 5', 'T1.mgz', 'PD.mgz', 'flash5.mgz'] run_subprocess(cmd, env=env) os.remove('flash5_reg.mgz') else: logger.info("Synthesized flash 5 volume is already there") else: logger.info("\n---- Averaging flash5 echoes ----") os.chdir('parameter_maps') if unwarp: files = glob.glob("mef05*u.mgz") else: files = glob.glob("mef05*.mgz") cmd = ['mri_average', '-noconform', files, 'flash5.mgz'] run_subprocess(cmd, env=env) if op.exists('flash5_reg.mgz'): os.remove('flash5_reg.mgz') # Go back to initial directory os.chdir(curdir) @verbose def make_flash_bem(subject, overwrite=False, show=True, subjects_dir=None, flash_path=None, verbose=None): from .viz.misc import plot_bem is_test = os.environ.get('MNE_SKIP_FS_FLASH_CALL', False) env, mri_dir, bem_dir = _prepare_env(subject, subjects_dir, requires_freesurfer=True) if flash_path is None: flash_path = op.join(mri_dir, 'flash', 'parameter_maps') else: flash_path = op.abspath(flash_path) curdir = os.getcwd() subjects_dir = env['SUBJECTS_DIR'] logger.info('\nProcessing the flash MRI data to produce BEM meshes with ' 'the following parameters:\n' 'SUBJECTS_DIR = %s\n' 'SUBJECT = %s\n' 'Result dir = %s\n' % (subjects_dir, subject, op.join(bem_dir, 'flash'))) # Step 4 : Register with MPRAGE logger.info("\n---- Registering flash 5 with MPRAGE ----") flash5 = op.join(flash_path, 'flash5.mgz') flash5_reg = op.join(flash_path, 'flash5_reg.mgz') if not op.exists(flash5_reg): if op.exists(op.join(mri_dir, 'T1.mgz')): ref_volume = op.join(mri_dir, 'T1.mgz') else: ref_volume = op.join(mri_dir, 'T1') cmd = ['fsl_rigid_register', '-r', ref_volume, '-i', flash5, '-o', flash5_reg] run_subprocess(cmd, env=env) else: logger.info("Registered flash 5 image is already there") # Step 5a : Convert flash5 into COR logger.info("\n---- Converting flash5 volume into COR format ----") shutil.rmtree(op.join(mri_dir, 'flash5'), ignore_errors=True) os.makedirs(op.join(mri_dir, 'flash5')) if not is_test: # CIs don't have freesurfer, skipped when testing. cmd = ['mri_convert', flash5_reg, op.join(mri_dir, 'flash5')] run_subprocess(cmd, env=env) os.chdir(mri_dir) convert_T1 = False if not op.isdir('T1') or len(glob.glob(op.join('T1', 'COR*'))) == 0: convert_T1 = True convert_brain = False if not op.isdir('brain') or len(glob.glob(op.join('brain', 'COR*'))) == 0: convert_brain = True logger.info("\n---- Converting T1 volume into COR format ----") if convert_T1: if not op.isfile('T1.mgz'): raise RuntimeError("Both T1 mgz and T1 COR volumes missing.") os.makedirs('T1') cmd = ['mri_convert', 'T1.mgz', 'T1'] run_subprocess(cmd, env=env) else: logger.info("T1 volume is already in COR format") logger.info("\n---- Converting brain volume into COR format ----") if convert_brain: if not op.isfile('brain.mgz'): raise RuntimeError("Both brain mgz and brain COR volumes missing.") os.makedirs('brain') cmd = ['mri_convert', 'brain.mgz', 'brain'] run_subprocess(cmd, env=env) else: logger.info("Brain volume is already in COR format") if not is_test: logger.info("\n---- Creating the BEM surfaces ----") cmd = ['mri_make_bem_surfaces', subject] run_subprocess(cmd, env=env) logger.info("\n---- Converting the tri files into surf files ----") os.chdir(bem_dir) if not op.exists('flash'): os.makedirs('flash') os.chdir('flash') surfs = ['inner_skull', 'outer_skull', 'outer_skin'] for surf in surfs: shutil.move(op.join(bem_dir, surf + '.tri'), surf + '.tri') nodes, tris = read_tri(surf + '.tri', swap=True) vol_info = _extract_volume_info(flash5_reg) if vol_info is None: warn('nibabel is required to update the volume info. Volume info ' 'omitted from the written surface.') else: vol_info['head'] = np.array([20]) write_surface(surf + '.surf', nodes, tris, volume_info=vol_info) # Cleanup section logger.info("\n---- Cleaning up ----") os.chdir(bem_dir) os.remove('inner_skull_tmp.tri') os.chdir(mri_dir) if convert_T1: shutil.rmtree('T1') logger.info("Deleted the T1 COR volume") if convert_brain: shutil.rmtree('brain') logger.info("Deleted the brain COR volume") shutil.rmtree('flash5') logger.info("Deleted the flash5 COR volume") # Create symbolic links to the .surf files in the bem folder logger.info("\n---- Creating symbolic links ----") os.chdir(bem_dir) for surf in surfs: surf = surf + '.surf' if not overwrite and op.exists(surf): skip_symlink = True else: if op.exists(surf): os.remove(surf) _symlink(op.join('flash', surf), op.join(surf)) skip_symlink = False if skip_symlink: logger.info("Unable to create all symbolic links to .surf files " "in bem folder. Use --overwrite option to recreate them.") dest = op.join(bem_dir, 'flash') else: logger.info("Symbolic links to .surf files created in bem folder") dest = bem_dir logger.info("\nThank you for waiting.\nThe BEM triangulations for this " "subject are now available at:\n%s.\nWe hope the BEM meshes " "created will facilitate your MEG and EEG data analyses." % dest) # Show computed BEM surfaces if show: plot_bem(subject=subject, subjects_dir=subjects_dir, orientation='coronal', slices=None, show=True) # Go back to initial directory os.chdir(curdir) def _check_bem_size(surfs): if len(surfs) > 1 and surfs[0]['np'] > 10000: warn('The bem surfaces have %s data points. 5120 (ico grade=4) ' 'should be enough. Dense 3-layer bems may not save properly.' % surfs[0]['np']) def _symlink(src, dest): try: os.symlink(src, dest) except OSError: warn('Could not create symbolic link %s. Check that your partition ' 'handles symbolic links. The file will be copied instead.' % dest) shutil.copy(src, dest)
true
true
f717c05e56131daf3f0bdbca7cbed9fe45f2de19
930
py
Python
src/augment/basic_augmentation/noise.py
TencentYoutuResearch/SelfSupervisedLearning-DSM
655a0a23a47bf2559f3d435384ae59a8871a5ff5
[ "Apache-2.0" ]
27
2021-01-07T11:09:33.000Z
2021-08-31T02:46:23.000Z
src/augment/basic_augmentation/noise.py
TencentYoutuResearch/SelfSupervisedLearning-DSM
655a0a23a47bf2559f3d435384ae59a8871a5ff5
[ "Apache-2.0" ]
null
null
null
src/augment/basic_augmentation/noise.py
TencentYoutuResearch/SelfSupervisedLearning-DSM
655a0a23a47bf2559f3d435384ae59a8871a5ff5
[ "Apache-2.0" ]
3
2021-01-08T08:31:06.000Z
2021-11-26T04:10:23.000Z
import torch import torch.nn as nn """ usage z_rand = generate_noise([1,nzx,nzy], device=opt.device) z_rand = z_rand.expand(1,3,Z_opt.shape[2],Z_opt.shape[3]) z_prev1 = 0.95*Z_opt +0.05*z_rand """ def upsampling(im, sx, sy): m = nn.Upsample(size=[round(sx), round(sy)], mode='bilinear', align_corners=True) return m(im) def generate_noise(size, num_samp=1, device='cuda', type='gaussian', scale=1): if type == 'gaussian': noise = torch.randn(num_samp, size[0], round(size[1]/scale), round(size[2]/scale)) noise = upsampling(noise, size[1], size[2]) if type == 'gaussian_mixture': noise1 = torch.randn(num_samp, size[0], size[1], size[2]) + 5 noise2 = torch.randn(num_samp, size[0], size[1], size[2]) noise = noise1 + noise2 if type == 'uniform': noise = torch.randn(num_samp, size[0], size[1], size[2]) return noise
32.068966
90
0.609677
import torch import torch.nn as nn def upsampling(im, sx, sy): m = nn.Upsample(size=[round(sx), round(sy)], mode='bilinear', align_corners=True) return m(im) def generate_noise(size, num_samp=1, device='cuda', type='gaussian', scale=1): if type == 'gaussian': noise = torch.randn(num_samp, size[0], round(size[1]/scale), round(size[2]/scale)) noise = upsampling(noise, size[1], size[2]) if type == 'gaussian_mixture': noise1 = torch.randn(num_samp, size[0], size[1], size[2]) + 5 noise2 = torch.randn(num_samp, size[0], size[1], size[2]) noise = noise1 + noise2 if type == 'uniform': noise = torch.randn(num_samp, size[0], size[1], size[2]) return noise
true
true
f717c11ea68b58ce09246f3ab62dcc7714c8c8ca
1,921
py
Python
recipes/pneumothorax/binary_classification/train_example_deit.py
lbolanos/HugsVision
c9b1708928916bc413a795590d731308ea8c582b
[ "MIT" ]
154
2021-08-14T00:09:15.000Z
2022-03-16T02:42:01.000Z
recipes/pneumothorax/binary_classification/train_example_deit.py
lbolanos/HugsVision
c9b1708928916bc413a795590d731308ea8c582b
[ "MIT" ]
36
2021-08-13T23:42:15.000Z
2022-03-31T03:57:23.000Z
recipes/pneumothorax/binary_classification/train_example_deit.py
lbolanos/HugsVision
c9b1708928916bc413a795590d731308ea8c582b
[ "MIT" ]
12
2021-09-04T00:49:35.000Z
2022-02-24T13:20:54.000Z
import argparse from hugsvision.nnet.VisionClassifierTrainer import VisionClassifierTrainer from hugsvision.dataio.VisionDataset import VisionDataset from torchvision.datasets import ImageFolder from transformers import DeiTFeatureExtractor, DeiTForImageClassification parser = argparse.ArgumentParser(description='Image classifier') parser.add_argument('--name', type=str, default="MyVitModel", help='The name of the model') parser.add_argument('--imgs', type=str, default="./images/", help='The directory of the input images') parser.add_argument('--output', type=str, default="./out/", help='The output directory of the model') parser.add_argument('--epochs', type=int, default=1, help='Number of Epochs') args = parser.parse_args() # Load the dataset train, test, id2label, label2id = VisionDataset.fromImageFolder( args.imgs, test_ratio = 0.15, balanced = True, augmentation = True, ) # # Load the dataset # train, test, id2label, label2id = VisionDataset.fromImageFolders( # "/<PATH>/train/", # "/<PATH>/test/", # ) huggingface_model = "facebook/deit-base-distilled-patch16-224" # Train the model trainer = VisionClassifierTrainer( model_name = args.name, train = train, test = test, output_dir = args.output, max_epochs = args.epochs, cores = 4, batch_size = 32, model = DeiTForImageClassification.from_pretrained( huggingface_model, num_labels = len(label2id), label2id = label2id, id2label = id2label ), feature_extractor = DeiTFeatureExtractor.from_pretrained( huggingface_model ), ) # Evaluate on the test sub-dataset ref, hyp = trainer.evaluate_f1_score() # Test on a single image trainer.testing(img='./data/demo/42.png',expected=2) trainer.testing(img='./data/demo/3.jpg',expected=0) trainer.testing(img='./data/demo/5.jpg',expected=2) trainer.testing(img='./data/demo/4.jpg',expected=1)
32.559322
103
0.724623
import argparse from hugsvision.nnet.VisionClassifierTrainer import VisionClassifierTrainer from hugsvision.dataio.VisionDataset import VisionDataset from torchvision.datasets import ImageFolder from transformers import DeiTFeatureExtractor, DeiTForImageClassification parser = argparse.ArgumentParser(description='Image classifier') parser.add_argument('--name', type=str, default="MyVitModel", help='The name of the model') parser.add_argument('--imgs', type=str, default="./images/", help='The directory of the input images') parser.add_argument('--output', type=str, default="./out/", help='The output directory of the model') parser.add_argument('--epochs', type=int, default=1, help='Number of Epochs') args = parser.parse_args() train, test, id2label, label2id = VisionDataset.fromImageFolder( args.imgs, test_ratio = 0.15, balanced = True, augmentation = True, ) model = "facebook/deit-base-distilled-patch16-224" trainer = VisionClassifierTrainer( model_name = args.name, train = train, test = test, output_dir = args.output, max_epochs = args.epochs, cores = 4, batch_size = 32, model = DeiTForImageClassification.from_pretrained( huggingface_model, num_labels = len(label2id), label2id = label2id, id2label = id2label ), feature_extractor = DeiTFeatureExtractor.from_pretrained( huggingface_model ), ) ref, hyp = trainer.evaluate_f1_score() trainer.testing(img='./data/demo/42.png',expected=2) trainer.testing(img='./data/demo/3.jpg',expected=0) trainer.testing(img='./data/demo/5.jpg',expected=2) trainer.testing(img='./data/demo/4.jpg',expected=1)
true
true
f717c1795cee9e960f89d88b04da89c0fcbb68f9
1,593
py
Python
algorithms/LinkedList/reverseLinkedList.py
gadodia/Algorithms
714d43ce89b684d8e5c4bb77a654938957957f33
[ "MIT" ]
null
null
null
algorithms/LinkedList/reverseLinkedList.py
gadodia/Algorithms
714d43ce89b684d8e5c4bb77a654938957957f33
[ "MIT" ]
null
null
null
algorithms/LinkedList/reverseLinkedList.py
gadodia/Algorithms
714d43ce89b684d8e5c4bb77a654938957957f33
[ "MIT" ]
null
null
null
''' This problem was recently asked by Google: Given a singly-linked list, reverse the list. This can be done iteratively or recursively. Can you get both solutions? Example: Input: 4 -> 3 -> 2 -> 1 -> 0 -> NULL Output: 0 -> 1 -> 2 -> 3 -> 4 -> NULL ''' class ListNode(object): def __init__(self, x): self.val = x self.next = None # Function to print the list def printList(self): node = self output = '' while node != None: output += str(node.val) output += " " node = node.next print(output) # Iterative Solution def reverseIteratively(self, head): if not head or not head.next: return head prev = None cur = head while cur: temp = cur.next cur.next = prev prev = cur cur = temp return prev # Recursive Solution def reverseRecursively(self, head): if not head or not head.next: return head p = self.reverseRecursively(head.next) head.next.next = head head.next = None return p # Test Program # Initialize the test list: testHead = ListNode(4) node1 = ListNode(3) testHead.next = node1 node2 = ListNode(2) node1.next = node2 node3 = ListNode(1) node2.next = node3 testTail = ListNode(0) node3.next = testTail print("Initial list: ") testHead.printList() # 4 3 2 1 0 # testHead.reverseIteratively(testHead) testHead.reverseRecursively(testHead) print("List after reversal: ") testTail.printList() # 0 1 2 3 4
23.426471
118
0.591337
class ListNode(object): def __init__(self, x): self.val = x self.next = None def printList(self): node = self output = '' while node != None: output += str(node.val) output += " " node = node.next print(output) def reverseIteratively(self, head): if not head or not head.next: return head prev = None cur = head while cur: temp = cur.next cur.next = prev prev = cur cur = temp return prev def reverseRecursively(self, head): if not head or not head.next: return head p = self.reverseRecursively(head.next) head.next.next = head head.next = None return p testHead = ListNode(4) node1 = ListNode(3) testHead.next = node1 node2 = ListNode(2) node1.next = node2 node3 = ListNode(1) node2.next = node3 testTail = ListNode(0) node3.next = testTail print("Initial list: ") testHead.printList() testHead.reverseRecursively(testHead) print("List after reversal: ") testTail.printList()
true
true
f717c2255fe90f0a652e062275efe541f399cc62
22,811
py
Python
utils/exp_utils.py
NoeSamaille/medical-detection-toolkit
232d3d1444ccaac04e15a00d8030390560236871
[ "Apache-2.0" ]
1
2021-04-01T02:15:49.000Z
2021-04-01T02:15:49.000Z
utils/exp_utils.py
NoeSamaille/medical-detection-toolkit
232d3d1444ccaac04e15a00d8030390560236871
[ "Apache-2.0" ]
2
2021-06-02T02:14:01.000Z
2021-09-06T06:03:25.000Z
utils/exp_utils.py
NoeSamaille/medical-detection-toolkit
232d3d1444ccaac04e15a00d8030390560236871
[ "Apache-2.0" ]
3
2020-06-28T14:57:00.000Z
2021-09-06T08:26:26.000Z
#!/usr/bin/env python # Copyright 2018 Division of Medical Image Computing, German Cancer Research Center (DKFZ). # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from typing import Iterable, Tuple, Any, Union import os, sys import subprocess from multiprocessing import Process import importlib.util import pickle import logging from torch.utils.tensorboard import SummaryWriter from collections import OrderedDict import numpy as np import torch import pandas as pd def split_off_process(target, *args, daemon: bool=False, **kwargs): """Start a process that won't block parent script. No join(), no return value. If daemon=False: before parent exits, it waits for this to finish. :param target: the target function of the process. :params *args: args to pass to target. :param daemon: if False: before parent exits, it waits for this process to finish. :params **kwargs: kwargs to pass to target. """ p = Process(target=target, args=tuple(args), kwargs=kwargs, daemon=daemon) p.start() return p def get_formatted_duration(seconds: float, format: str="hms") -> str: """Format a time in seconds. :param format: "hms" for hours mins secs or "ms" for min secs. """ mins, secs = divmod(seconds, 60) if format == "ms": t = "{:d}m:{:02d}s".format(int(mins), int(secs)) elif format == "hms": h, mins = divmod(mins, 60) t = "{:d}h:{:02d}m:{:02d}s".format(int(h), int(mins), int(secs)) else: raise Exception("Format {} not available, only 'hms' or 'ms'".format(format)) return t class CombinedLogger(object): """Combine console and tensorboard logger and record system metrics. """ def __init__(self, name: str, log_dir: str, server_env: bool=True, fold: Union[int, str]="all"): self.pylogger = logging.getLogger(name) self.tboard = SummaryWriter(log_dir=os.path.join(log_dir, "tboard")) self.log_dir = log_dir self.fold = str(fold) self.server_env = server_env self.pylogger.setLevel(logging.DEBUG) self.log_file = os.path.join(log_dir, "fold_"+self.fold, 'exec.log') os.makedirs(os.path.dirname(self.log_file), exist_ok=True) self.pylogger.addHandler(logging.FileHandler(self.log_file)) if not server_env: self.pylogger.addHandler(ColorHandler()) else: self.pylogger.addHandler(logging.StreamHandler()) self.pylogger.propagate = False def __getattr__(self, attr): """delegate all undefined method requests to objects of this class in order pylogger, tboard (first find first serve). E.g., combinedlogger.add_scalars(...) should trigger self.tboard.add_scalars(...) """ for obj in [self.pylogger, self.tboard]: if attr in dir(obj): return getattr(obj, attr) print("logger attr not found") def set_logfile(self, fold: Union[int, str, None]=None, log_file: Union[str, None]=None): if fold is not None: self.fold = str(fold) if log_file is None: self.log_file = os.path.join(self.log_dir, "fold_"+self.fold, 'exec.log') else: self.log_file = log_file os.makedirs(os.path.dirname(self.log_file), exist_ok=True) for hdlr in self.pylogger.handlers: hdlr.close() self.pylogger.handlers = [] self.pylogger.addHandler(logging.FileHandler(self.log_file)) if not self.server_env: self.pylogger.addHandler(ColorHandler()) else: self.pylogger.addHandler(logging.StreamHandler()) def metrics2tboard(self, metrics, global_step=None, suptitle=None): """ :param metrics: {'train': dataframe, 'val':df}, df as produced in evaluator.py.evaluate_predictions """ # print("metrics", metrics) if global_step is None: global_step = len(metrics['train'][list(metrics['train'].keys())[0]]) - 1 if suptitle is not None: suptitle = str(suptitle) else: suptitle = "Fold_" + str(self.fold) for key in ['train', 'val']: # series = {k:np.array(v[-1]) for (k,v) in metrics[key].items() if not np.isnan(v[-1]) and not 'Bin_Stats' in k} loss_series = {} mon_met_series = {} for tag, val in metrics[key].items(): val = val[-1] # maybe remove list wrapping, recording in evaluator? if 'loss' in tag.lower() and not np.isnan(val): loss_series["{}".format(tag)] = val elif not np.isnan(val): mon_met_series["{}".format(tag)] = val self.tboard.add_scalars(suptitle + "/Losses/{}".format(key), loss_series, global_step) self.tboard.add_scalars(suptitle + "/Monitor_Metrics/{}".format(key), mon_met_series, global_step) self.tboard.add_scalars(suptitle + "/Learning_Rate", metrics["lr"], global_step) return def __del__(self): # otherwise might produce multiple prints e.g. in ipython console for hdlr in self.pylogger.handlers: hdlr.close() self.pylogger.handlers = [] del self.pylogger self.tboard.flush() # close somehow prevents main script from exiting # maybe revise this issue in a later pytorch version #self.tboard.close() def get_logger(exp_dir: str, server_env: bool=False) -> CombinedLogger: """ creates logger instance. writing out info to file, to terminal and to tensorboard. :param exp_dir: experiment directory, where exec.log file is stored. :param server_env: True if operating in server environment (e.g., gpu cluster) :return: custom CombinedLogger instance. """ log_dir = os.path.join(exp_dir, "logs") logger = CombinedLogger('medicaldetectiontoolkit', log_dir, server_env=server_env) print("Logging to {}".format(logger.log_file)) return logger def prep_exp(dataset_path, exp_path, server_env, use_stored_settings=True, is_training=True): """ I/O handling, creating of experiment folder structure. Also creates a snapshot of configs/model scripts and copies them to the exp_dir. This way the exp_dir contains all info needed to conduct an experiment, independent to changes in actual source code. Thus, training/inference of this experiment can be started at anytime. Therefore, the model script is copied back to the source code dir as tmp_model (tmp_backbone). Provides robust structure for cloud deployment. :param dataset_path: path to source code for specific data set. (e.g. medicaldetectiontoolkit/lidc_exp) :param exp_path: path to experiment directory. :param server_env: boolean flag. pass to configs script for cloud deployment. :param use_stored_settings: boolean flag. When starting training: If True, starts training from snapshot in existing experiment directory, else creates experiment directory on the fly using configs/model scripts from source code. :param is_training: boolean flag. distinguishes train vs. inference mode. :return: """ if is_training: if use_stored_settings: cf_file = import_module('cf_file', os.path.join(exp_path, 'configs.py')) cf = cf_file.configs(server_env) # in this mode, previously saved model and backbone need to be found in exp dir. if not os.path.isfile(os.path.join(exp_path, 'mdt_model.py')) or \ not os.path.isfile(os.path.join(exp_path, 'backbone.py')): raise Exception( "Selected use_stored_settings option but no model and/or backbone source files exist in exp dir.") cf.model_path = os.path.join(exp_path, 'mdt_model.py') cf.backbone_path = os.path.join(exp_path, 'backbone.py') else: # this case overwrites settings files in exp dir, i.e., default_configs, configs, backbone, model os.makedirs(exp_path, exist_ok=True) # run training with source code info and copy snapshot of model to exp_dir for later testing (overwrite scripts if exp_dir already exists.) subprocess.call('cp {} {}'.format('default_configs.py', os.path.join(exp_path, 'default_configs.py')), shell=True) subprocess.call( 'cp {} {}'.format(os.path.join(dataset_path, 'configs.py'), os.path.join(exp_path, 'configs.py')), shell=True) cf_file = import_module('cf_file', os.path.join(dataset_path, 'configs.py')) cf = cf_file.configs(server_env) subprocess.call('cp {} {}'.format(cf.model_path, os.path.join(exp_path, 'mdt_model.py')), shell=True) subprocess.call('cp {} {}'.format(cf.backbone_path, os.path.join(exp_path, 'backbone.py')), shell=True) if os.path.isfile(os.path.join(exp_path, "fold_ids.pickle")): subprocess.call('rm {}'.format(os.path.join(exp_path, "fold_ids.pickle")), shell=True) else: # testing, use model and backbone stored in exp dir. cf_file = import_module('cf_file', os.path.join(exp_path, 'configs.py')) cf = cf_file.configs(server_env) cf.model_path = os.path.join(exp_path, 'mdt_model.py') cf.backbone_path = os.path.join(exp_path, 'backbone.py') cf.exp_dir = exp_path cf.test_dir = os.path.join(cf.exp_dir, 'test') cf.plot_dir = os.path.join(cf.exp_dir, 'plots') if not os.path.exists(cf.test_dir): os.mkdir(cf.test_dir) if not os.path.exists(cf.plot_dir): os.mkdir(cf.plot_dir) cf.experiment_name = exp_path.split("/")[-1] cf.created_fold_id_pickle = False return cf def import_module(name: str, path: str): """ correct way of importing a module dynamically in python 3. :param name: name given to module instance. :param path: path to module. :return: module: returned module instance. """ spec = importlib.util.spec_from_file_location(name, path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module def set_params_flag(module: torch.nn.Module, flag: Tuple[str, Any], check_overwrite: bool = True) -> torch.nn.Module: """Set an attribute for all passed module parameters. :param flag: tuple (str attribute name : attr value) :param check_overwrite: if True, assert that attribute not already exists. """ for param in module.parameters(): if check_overwrite: assert not hasattr(param, flag[0]), \ "param {} already has attr {} (w/ val {})".format(param, flag[0], getattr(param, flag[0])) setattr(param, flag[0], flag[1]) return module def parse_params_for_optim(net: torch.nn.Module, weight_decay: float = 0., exclude_from_wd: Iterable = ("norm",)) -> list: """Split network parameters into weight-decay dependent groups for the optimizer. :param net: network. :param weight_decay: weight decay value for the parameters that it is applied to. excluded parameters will have weight decay 0. :param exclude_from_wd: List of strings of parameter-group names to exclude from weight decay. Options: "norm", "bias". :return: """ if weight_decay is None: weight_decay = 0. # pytorch implements parameter groups as dicts {'params': ...} and # weight decay as p.data.mul_(1 - group['lr'] * group['weight_decay']) norm_types = [torch.nn.BatchNorm1d, torch.nn.BatchNorm2d, torch.nn.BatchNorm3d, torch.nn.InstanceNorm1d, torch.nn.InstanceNorm2d, torch.nn.InstanceNorm3d, torch.nn.LayerNorm, torch.nn.GroupNorm, torch.nn.SyncBatchNorm, torch.nn.LocalResponseNorm] level_map = {"bias": "weight", "norm": "module"} type_map = {"norm": norm_types} exclude_from_wd = [str(name).lower() for name in exclude_from_wd] exclude_weight_names = [k for k, v in level_map.items() if k in exclude_from_wd and v == "weight"] exclude_module_types = tuple([type_ for k, v in level_map.items() if (k in exclude_from_wd and v == "module") for type_ in type_map[k]]) if exclude_from_wd: print("excluding {} from weight decay.".format(exclude_from_wd)) for module in net.modules(): if isinstance(module, exclude_module_types): set_params_flag(module, ("no_wd", True)) for param_name, param in net.named_parameters(): if np.any([ename in param_name for ename in exclude_weight_names]): setattr(param, "no_wd", True) with_dec, no_dec = [], [] for param in net.parameters(): if hasattr(param, "no_wd") and param.no_wd == True: no_dec.append(param) else: with_dec.append(param) orig_ps = sum(p.numel() for p in net.parameters()) with_ps = sum(p.numel() for p in with_dec) wo_ps = sum(p.numel() for p in no_dec) assert orig_ps == with_ps + wo_ps, "orig n parameters {} unequals sum of with wd {} and w/o wd {}."\ .format(orig_ps, with_ps, wo_ps) groups = [{'params': gr, 'weight_decay': wd} for (gr, wd) in [(no_dec, 0.), (with_dec, weight_decay)] if len(gr)>0] return groups class ModelSelector: ''' saves a checkpoint after each epoch as 'last_state' (can be loaded to continue interrupted training). saves the top-k (k=cf.save_n_models) ranked epochs. In inference, predictions of multiple epochs can be ensembled to improve performance. ''' def __init__(self, cf, logger): self.cf = cf self.saved_epochs = [-1] * cf.save_n_models self.logger = logger def run_model_selection(self, net: torch.nn.Module, optimizer: torch.optim.Optimizer, monitor_metrics: dict, epoch: int): # take the mean over all selection criteria in each epoch non_nan_scores = np.mean(np.array([[0 if (ii is None or np.isnan(ii)) else ii for ii in monitor_metrics['val'][sc]] for sc in self.cf.model_selection_criteria]), 0) epochs_scores = [ii for ii in non_nan_scores[1:]] # ranking of epochs according to model_selection_criterion epoch_ranking = np.argsort(epochs_scores, kind="stable")[::-1] + 1 #epochs start at 1 # if set in configs, epochs < min_save_thresh are discarded from saving process. epoch_ranking = epoch_ranking[epoch_ranking >= self.cf.min_save_thresh] # check if current epoch is among the top-k epochs. if epoch in epoch_ranking[:self.cf.save_n_models]: save_dir = os.path.join(self.cf.fold_dir, '{}_best_checkpoint'.format(epoch)) if not os.path.exists(save_dir): os.mkdir(save_dir) torch.save(net.state_dict(), os.path.join(save_dir, 'params.pth')) with open(os.path.join(save_dir, 'monitor_metrics.pickle'), 'wb') as handle: pickle.dump(monitor_metrics, handle) # save epoch_ranking to keep info for inference. np.save(os.path.join(self.cf.fold_dir, 'epoch_ranking'), epoch_ranking[:self.cf.save_n_models]) np.save(os.path.join(save_dir, 'epoch_ranking'), epoch_ranking[:self.cf.save_n_models]) self.logger.info( "saving current epoch {} at rank {}".format(epoch, np.argwhere(epoch_ranking == epoch))) # delete params of the epoch that just fell out of the top-k epochs. for se in [int(ii.split('_')[0]) for ii in os.listdir(self.cf.fold_dir) if 'best_checkpoint' in ii]: if se in epoch_ranking[self.cf.save_n_models:]: subprocess.call('rm -rf {}'.format(os.path.join(self.cf.fold_dir, '{}_best_checkpoint'.format(se))), shell=True) self.logger.info('deleting epoch {} at rank {}'.format(se, np.argwhere(epoch_ranking == se))) state = { 'epoch': epoch, 'state_dict': net.state_dict(), 'optimizer': optimizer.state_dict(), } # save checkpoint of current epoch. save_dir = os.path.join(self.cf.fold_dir, 'last_checkpoint'.format(epoch)) if not os.path.exists(save_dir): os.mkdir(save_dir) torch.save(state, os.path.join(save_dir, 'params.pth')) np.save(os.path.join(save_dir, 'epoch_ranking'), epoch_ranking[:self.cf.save_n_models]) with open(os.path.join(save_dir, 'monitor_metrics.pickle'), 'wb') as handle: pickle.dump(monitor_metrics, handle) return os.path.join(os.path.join(self.cf.fold_dir, f'{epoch_ranking[0]}_best_checkpoint')) def load_checkpoint(checkpoint_path: str, net: torch.nn.Module, optimizer: torch.optim.Optimizer) -> Tuple: checkpoint = torch.load(os.path.join(checkpoint_path, 'params.pth')) net.load_state_dict(checkpoint['state_dict']) optimizer.load_state_dict(checkpoint['optimizer']) with open(os.path.join(checkpoint_path, 'monitor_metrics.pickle'), 'rb') as handle: monitor_metrics = pickle.load(handle) starting_epoch = checkpoint['epoch'] + 1 return starting_epoch, net, optimizer, monitor_metrics def prepare_monitoring(cf): """ creates dictionaries, where train/val metrics are stored. """ metrics = {} # first entry for loss dict accounts for epoch starting at 1. metrics['train'] = OrderedDict() metrics['val'] = OrderedDict() metric_classes = [] if 'rois' in cf.report_score_level: metric_classes.extend([v for k, v in cf.class_dict.items()]) if 'patient' in cf.report_score_level: metric_classes.extend(['patient']) for cl in metric_classes: metrics['train'][cl + '_ap'] = [np.nan] metrics['val'][cl + '_ap'] = [np.nan] if cl == 'patient': metrics['train'][cl + '_auc'] = [np.nan] metrics['val'][cl + '_auc'] = [np.nan] return metrics def create_csv_output(results_list, cf, logger): """ Write out test set predictions to .csv file. output format is one line per prediction: PatientID | PredictionID | [y1 x1 y2 x2 (z1) (z2)] | score | pred_classID Note, that prediction coordinates correspond to images as loaded for training/testing and need to be adapted when plotted over raw data (before preprocessing/resampling). :param results_list: [[patient_results, patient_id], [patient_results, patient_id], ...] """ logger.info('creating csv output file at {}'.format(os.path.join(cf.test_dir, 'results.csv'))) predictions_df = pd.DataFrame(columns = ['patientID', 'predictionID', 'coords', 'score', 'pred_classID']) for r in results_list: pid = r[1] #optionally load resampling info from preprocessing to match output predictions with raw data. #with open(os.path.join(cf.exp_dir, 'test_resampling_info', pid), 'rb') as handle: # resampling_info = pickle.load(handle) for bix, box in enumerate(r[0][0]): if box["box_type"] == "gt": continue assert box['box_type'] == 'det', box['box_type'] coords = box['box_coords'] score = box['box_score'] pred_class_id = box['box_pred_class_id'] out_coords = [] if score >= cf.min_det_thresh: out_coords.append(coords[0]) #* resampling_info['scale'][0]) out_coords.append(coords[1]) #* resampling_info['scale'][1]) out_coords.append(coords[2]) #* resampling_info['scale'][0]) out_coords.append(coords[3]) #* resampling_info['scale'][1]) if len(coords) > 4: out_coords.append(coords[4]) #* resampling_info['scale'][2] + resampling_info['z_crop']) out_coords.append(coords[5]) #* resampling_info['scale'][2] + resampling_info['z_crop']) predictions_df.loc[len(predictions_df)] = [pid, bix, out_coords, score, pred_class_id] try: fold = cf.fold except: fold = 'hold_out' predictions_df.to_csv(os.path.join(cf.exp_dir, 'results_{}.csv'.format(fold)), index=False) class _AnsiColorizer(object): """ A colorizer is an object that loosely wraps around a stream, allowing callers to write text to the stream in a particular color. Colorizer classes must implement C{supported()} and C{write(text, color)}. """ _colors = dict(black=30, red=31, green=32, yellow=33, blue=34, magenta=35, cyan=36, white=37, default=39) def __init__(self, stream): self.stream = stream @classmethod def supported(cls, stream=sys.stdout): """ A class method that returns True if the current platform supports coloring terminal output using this method. Returns False otherwise. """ if not stream.isatty(): return False # auto color only on TTYs try: import curses except ImportError: return False else: try: try: return curses.tigetnum("colors") > 2 except curses.error: curses.setupterm() return curses.tigetnum("colors") > 2 except: raise # guess false in case of error return False def write(self, text, color): """ Write the given text to the stream in the given color. @param text: Text to be written to the stream. @param color: A string label for a color. e.g. 'red', 'white'. """ color = self._colors[color] self.stream.write('\x1b[%sm%s\x1b[0m' % (color, text)) class ColorHandler(logging.StreamHandler): def __init__(self, stream=sys.stdout): super(ColorHandler, self).__init__(_AnsiColorizer(stream)) def emit(self, record): msg_colors = { logging.DEBUG: "green", logging.INFO: "default", logging.WARNING: "red", logging.ERROR: "red" } color = msg_colors.get(record.levelno, "blue") self.stream.write(record.msg + "\n", color)
44.903543
287
0.639691
from typing import Iterable, Tuple, Any, Union import os, sys import subprocess from multiprocessing import Process import importlib.util import pickle import logging from torch.utils.tensorboard import SummaryWriter from collections import OrderedDict import numpy as np import torch import pandas as pd def split_off_process(target, *args, daemon: bool=False, **kwargs): p = Process(target=target, args=tuple(args), kwargs=kwargs, daemon=daemon) p.start() return p def get_formatted_duration(seconds: float, format: str="hms") -> str: mins, secs = divmod(seconds, 60) if format == "ms": t = "{:d}m:{:02d}s".format(int(mins), int(secs)) elif format == "hms": h, mins = divmod(mins, 60) t = "{:d}h:{:02d}m:{:02d}s".format(int(h), int(mins), int(secs)) else: raise Exception("Format {} not available, only 'hms' or 'ms'".format(format)) return t class CombinedLogger(object): def __init__(self, name: str, log_dir: str, server_env: bool=True, fold: Union[int, str]="all"): self.pylogger = logging.getLogger(name) self.tboard = SummaryWriter(log_dir=os.path.join(log_dir, "tboard")) self.log_dir = log_dir self.fold = str(fold) self.server_env = server_env self.pylogger.setLevel(logging.DEBUG) self.log_file = os.path.join(log_dir, "fold_"+self.fold, 'exec.log') os.makedirs(os.path.dirname(self.log_file), exist_ok=True) self.pylogger.addHandler(logging.FileHandler(self.log_file)) if not server_env: self.pylogger.addHandler(ColorHandler()) else: self.pylogger.addHandler(logging.StreamHandler()) self.pylogger.propagate = False def __getattr__(self, attr): for obj in [self.pylogger, self.tboard]: if attr in dir(obj): return getattr(obj, attr) print("logger attr not found") def set_logfile(self, fold: Union[int, str, None]=None, log_file: Union[str, None]=None): if fold is not None: self.fold = str(fold) if log_file is None: self.log_file = os.path.join(self.log_dir, "fold_"+self.fold, 'exec.log') else: self.log_file = log_file os.makedirs(os.path.dirname(self.log_file), exist_ok=True) for hdlr in self.pylogger.handlers: hdlr.close() self.pylogger.handlers = [] self.pylogger.addHandler(logging.FileHandler(self.log_file)) if not self.server_env: self.pylogger.addHandler(ColorHandler()) else: self.pylogger.addHandler(logging.StreamHandler()) def metrics2tboard(self, metrics, global_step=None, suptitle=None): if global_step is None: global_step = len(metrics['train'][list(metrics['train'].keys())[0]]) - 1 if suptitle is not None: suptitle = str(suptitle) else: suptitle = "Fold_" + str(self.fold) for key in ['train', 'val']: loss_series = {} mon_met_series = {} for tag, val in metrics[key].items(): val = val[-1] if 'loss' in tag.lower() and not np.isnan(val): loss_series["{}".format(tag)] = val elif not np.isnan(val): mon_met_series["{}".format(tag)] = val self.tboard.add_scalars(suptitle + "/Losses/{}".format(key), loss_series, global_step) self.tboard.add_scalars(suptitle + "/Monitor_Metrics/{}".format(key), mon_met_series, global_step) self.tboard.add_scalars(suptitle + "/Learning_Rate", metrics["lr"], global_step) return def __del__(self): for hdlr in self.pylogger.handlers: hdlr.close() self.pylogger.handlers = [] del self.pylogger self.tboard.flush() def get_logger(exp_dir: str, server_env: bool=False) -> CombinedLogger: log_dir = os.path.join(exp_dir, "logs") logger = CombinedLogger('medicaldetectiontoolkit', log_dir, server_env=server_env) print("Logging to {}".format(logger.log_file)) return logger def prep_exp(dataset_path, exp_path, server_env, use_stored_settings=True, is_training=True): if is_training: if use_stored_settings: cf_file = import_module('cf_file', os.path.join(exp_path, 'configs.py')) cf = cf_file.configs(server_env) if not os.path.isfile(os.path.join(exp_path, 'mdt_model.py')) or \ not os.path.isfile(os.path.join(exp_path, 'backbone.py')): raise Exception( "Selected use_stored_settings option but no model and/or backbone source files exist in exp dir.") cf.model_path = os.path.join(exp_path, 'mdt_model.py') cf.backbone_path = os.path.join(exp_path, 'backbone.py') else: os.makedirs(exp_path, exist_ok=True) subprocess.call('cp {} {}'.format('default_configs.py', os.path.join(exp_path, 'default_configs.py')), shell=True) subprocess.call( 'cp {} {}'.format(os.path.join(dataset_path, 'configs.py'), os.path.join(exp_path, 'configs.py')), shell=True) cf_file = import_module('cf_file', os.path.join(dataset_path, 'configs.py')) cf = cf_file.configs(server_env) subprocess.call('cp {} {}'.format(cf.model_path, os.path.join(exp_path, 'mdt_model.py')), shell=True) subprocess.call('cp {} {}'.format(cf.backbone_path, os.path.join(exp_path, 'backbone.py')), shell=True) if os.path.isfile(os.path.join(exp_path, "fold_ids.pickle")): subprocess.call('rm {}'.format(os.path.join(exp_path, "fold_ids.pickle")), shell=True) else: cf_file = import_module('cf_file', os.path.join(exp_path, 'configs.py')) cf = cf_file.configs(server_env) cf.model_path = os.path.join(exp_path, 'mdt_model.py') cf.backbone_path = os.path.join(exp_path, 'backbone.py') cf.exp_dir = exp_path cf.test_dir = os.path.join(cf.exp_dir, 'test') cf.plot_dir = os.path.join(cf.exp_dir, 'plots') if not os.path.exists(cf.test_dir): os.mkdir(cf.test_dir) if not os.path.exists(cf.plot_dir): os.mkdir(cf.plot_dir) cf.experiment_name = exp_path.split("/")[-1] cf.created_fold_id_pickle = False return cf def import_module(name: str, path: str): spec = importlib.util.spec_from_file_location(name, path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module def set_params_flag(module: torch.nn.Module, flag: Tuple[str, Any], check_overwrite: bool = True) -> torch.nn.Module: for param in module.parameters(): if check_overwrite: assert not hasattr(param, flag[0]), \ "param {} already has attr {} (w/ val {})".format(param, flag[0], getattr(param, flag[0])) setattr(param, flag[0], flag[1]) return module def parse_params_for_optim(net: torch.nn.Module, weight_decay: float = 0., exclude_from_wd: Iterable = ("norm",)) -> list: if weight_decay is None: weight_decay = 0. norm_types = [torch.nn.BatchNorm1d, torch.nn.BatchNorm2d, torch.nn.BatchNorm3d, torch.nn.InstanceNorm1d, torch.nn.InstanceNorm2d, torch.nn.InstanceNorm3d, torch.nn.LayerNorm, torch.nn.GroupNorm, torch.nn.SyncBatchNorm, torch.nn.LocalResponseNorm] level_map = {"bias": "weight", "norm": "module"} type_map = {"norm": norm_types} exclude_from_wd = [str(name).lower() for name in exclude_from_wd] exclude_weight_names = [k for k, v in level_map.items() if k in exclude_from_wd and v == "weight"] exclude_module_types = tuple([type_ for k, v in level_map.items() if (k in exclude_from_wd and v == "module") for type_ in type_map[k]]) if exclude_from_wd: print("excluding {} from weight decay.".format(exclude_from_wd)) for module in net.modules(): if isinstance(module, exclude_module_types): set_params_flag(module, ("no_wd", True)) for param_name, param in net.named_parameters(): if np.any([ename in param_name for ename in exclude_weight_names]): setattr(param, "no_wd", True) with_dec, no_dec = [], [] for param in net.parameters(): if hasattr(param, "no_wd") and param.no_wd == True: no_dec.append(param) else: with_dec.append(param) orig_ps = sum(p.numel() for p in net.parameters()) with_ps = sum(p.numel() for p in with_dec) wo_ps = sum(p.numel() for p in no_dec) assert orig_ps == with_ps + wo_ps, "orig n parameters {} unequals sum of with wd {} and w/o wd {}."\ .format(orig_ps, with_ps, wo_ps) groups = [{'params': gr, 'weight_decay': wd} for (gr, wd) in [(no_dec, 0.), (with_dec, weight_decay)] if len(gr)>0] return groups class ModelSelector: def __init__(self, cf, logger): self.cf = cf self.saved_epochs = [-1] * cf.save_n_models self.logger = logger def run_model_selection(self, net: torch.nn.Module, optimizer: torch.optim.Optimizer, monitor_metrics: dict, epoch: int): non_nan_scores = np.mean(np.array([[0 if (ii is None or np.isnan(ii)) else ii for ii in monitor_metrics['val'][sc]] for sc in self.cf.model_selection_criteria]), 0) epochs_scores = [ii for ii in non_nan_scores[1:]] epoch_ranking = np.argsort(epochs_scores, kind="stable")[::-1] + 1 epoch_ranking = epoch_ranking[epoch_ranking >= self.cf.min_save_thresh] if epoch in epoch_ranking[:self.cf.save_n_models]: save_dir = os.path.join(self.cf.fold_dir, '{}_best_checkpoint'.format(epoch)) if not os.path.exists(save_dir): os.mkdir(save_dir) torch.save(net.state_dict(), os.path.join(save_dir, 'params.pth')) with open(os.path.join(save_dir, 'monitor_metrics.pickle'), 'wb') as handle: pickle.dump(monitor_metrics, handle) np.save(os.path.join(self.cf.fold_dir, 'epoch_ranking'), epoch_ranking[:self.cf.save_n_models]) np.save(os.path.join(save_dir, 'epoch_ranking'), epoch_ranking[:self.cf.save_n_models]) self.logger.info( "saving current epoch {} at rank {}".format(epoch, np.argwhere(epoch_ranking == epoch))) for se in [int(ii.split('_')[0]) for ii in os.listdir(self.cf.fold_dir) if 'best_checkpoint' in ii]: if se in epoch_ranking[self.cf.save_n_models:]: subprocess.call('rm -rf {}'.format(os.path.join(self.cf.fold_dir, '{}_best_checkpoint'.format(se))), shell=True) self.logger.info('deleting epoch {} at rank {}'.format(se, np.argwhere(epoch_ranking == se))) state = { 'epoch': epoch, 'state_dict': net.state_dict(), 'optimizer': optimizer.state_dict(), } save_dir = os.path.join(self.cf.fold_dir, 'last_checkpoint'.format(epoch)) if not os.path.exists(save_dir): os.mkdir(save_dir) torch.save(state, os.path.join(save_dir, 'params.pth')) np.save(os.path.join(save_dir, 'epoch_ranking'), epoch_ranking[:self.cf.save_n_models]) with open(os.path.join(save_dir, 'monitor_metrics.pickle'), 'wb') as handle: pickle.dump(monitor_metrics, handle) return os.path.join(os.path.join(self.cf.fold_dir, f'{epoch_ranking[0]}_best_checkpoint')) def load_checkpoint(checkpoint_path: str, net: torch.nn.Module, optimizer: torch.optim.Optimizer) -> Tuple: checkpoint = torch.load(os.path.join(checkpoint_path, 'params.pth')) net.load_state_dict(checkpoint['state_dict']) optimizer.load_state_dict(checkpoint['optimizer']) with open(os.path.join(checkpoint_path, 'monitor_metrics.pickle'), 'rb') as handle: monitor_metrics = pickle.load(handle) starting_epoch = checkpoint['epoch'] + 1 return starting_epoch, net, optimizer, monitor_metrics def prepare_monitoring(cf): metrics = {} metrics['train'] = OrderedDict() metrics['val'] = OrderedDict() metric_classes = [] if 'rois' in cf.report_score_level: metric_classes.extend([v for k, v in cf.class_dict.items()]) if 'patient' in cf.report_score_level: metric_classes.extend(['patient']) for cl in metric_classes: metrics['train'][cl + '_ap'] = [np.nan] metrics['val'][cl + '_ap'] = [np.nan] if cl == 'patient': metrics['train'][cl + '_auc'] = [np.nan] metrics['val'][cl + '_auc'] = [np.nan] return metrics def create_csv_output(results_list, cf, logger): logger.info('creating csv output file at {}'.format(os.path.join(cf.test_dir, 'results.csv'))) predictions_df = pd.DataFrame(columns = ['patientID', 'predictionID', 'coords', 'score', 'pred_classID']) for r in results_list: pid = r[1] for bix, box in enumerate(r[0][0]): if box["box_type"] == "gt": continue assert box['box_type'] == 'det', box['box_type'] coords = box['box_coords'] score = box['box_score'] pred_class_id = box['box_pred_class_id'] out_coords = [] if score >= cf.min_det_thresh: out_coords.append(coords[0]) out_coords.append(coords[1]) out_coords.append(coords[2]) out_coords.append(coords[3]) if len(coords) > 4: out_coords.append(coords[4]) out_coords.append(coords[5]) predictions_df.loc[len(predictions_df)] = [pid, bix, out_coords, score, pred_class_id] try: fold = cf.fold except: fold = 'hold_out' predictions_df.to_csv(os.path.join(cf.exp_dir, 'results_{}.csv'.format(fold)), index=False) class _AnsiColorizer(object): _colors = dict(black=30, red=31, green=32, yellow=33, blue=34, magenta=35, cyan=36, white=37, default=39) def __init__(self, stream): self.stream = stream @classmethod def supported(cls, stream=sys.stdout): if not stream.isatty(): return False try: import curses except ImportError: return False else: try: try: return curses.tigetnum("colors") > 2 except curses.error: curses.setupterm() return curses.tigetnum("colors") > 2 except: raise return False def write(self, text, color): color = self._colors[color] self.stream.write('\x1b[%sm%s\x1b[0m' % (color, text)) class ColorHandler(logging.StreamHandler): def __init__(self, stream=sys.stdout): super(ColorHandler, self).__init__(_AnsiColorizer(stream)) def emit(self, record): msg_colors = { logging.DEBUG: "green", logging.INFO: "default", logging.WARNING: "red", logging.ERROR: "red" } color = msg_colors.get(record.levelno, "blue") self.stream.write(record.msg + "\n", color)
true
true
f717c2aceaf306d0f7eae56f9df7f70d7fb7e56b
2,488
py
Python
usort/util.py
thatch/usort
2ca1ff63d6cfc79e76ea95b69d162f4579c3fa3c
[ "MIT" ]
null
null
null
usort/util.py
thatch/usort
2ca1ff63d6cfc79e76ea95b69d162f4579c3fa3c
[ "MIT" ]
null
null
null
usort/util.py
thatch/usort
2ca1ff63d6cfc79e76ea95b69d162f4579c3fa3c
[ "MIT" ]
null
null
null
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from contextlib import contextmanager from contextvars import ContextVar from pathlib import Path from time import monotonic from typing import Callable, Generator, List, Optional, Tuple import libcst as cst TIMINGS: ContextVar[List[Tuple[str, float]]] = ContextVar("TIMINGS") @contextmanager def timed(msg: str) -> Generator[None, None, None]: """ Records the monotonic duration of the contained context, with a given description. Timings are stored for later use/printing with `print_timings()`. """ before = monotonic() yield after = monotonic() try: TIMINGS.get().append((msg, after - before)) except LookupError: pass @contextmanager def save_timings(to: List[Tuple[str, float]]) -> Generator[None, None, None]: token = TIMINGS.set([]) yield to.extend(TIMINGS.get()) TIMINGS.reset(token) def merge_timings(more: List[Tuple[str, float]]) -> None: TIMINGS.get().extend(more) def print_timings(fn: Callable[[str], None] = print) -> None: """ Print all stored timing values in microseconds. """ for msg, duration in TIMINGS.get(): fn(f"{msg + ':':50} {int(duration*1000000):7} µs") def try_parse(path: Path, data: Optional[bytes] = None) -> cst.Module: """ Attempts to parse the file with all syntax versions known by LibCST. If parsing fails on all supported grammar versions, then raises the parser error from the first/newest version attempted. """ if data is None: data = path.read_bytes() with timed(f"parsing {path}"): parse_error: Optional[cst.ParserSyntaxError] = None for version in cst.KNOWN_PYTHON_VERSION_STRINGS[::-1]: try: mod = cst.parse_module( data, cst.PartialParserConfig(python_version=version) ) return mod except cst.ParserSyntaxError as e: # keep the first error we see in case parsing fails on all versions if parse_error is None: parse_error = e # not caring about existing traceback here because it's not useful for parse # errors, and usort_path is already going to wrap it in a custom class raise parse_error or Exception("unknown parse failure")
30.716049
86
0.658762
from contextlib import contextmanager from contextvars import ContextVar from pathlib import Path from time import monotonic from typing import Callable, Generator, List, Optional, Tuple import libcst as cst TIMINGS: ContextVar[List[Tuple[str, float]]] = ContextVar("TIMINGS") @contextmanager def timed(msg: str) -> Generator[None, None, None]: before = monotonic() yield after = monotonic() try: TIMINGS.get().append((msg, after - before)) except LookupError: pass @contextmanager def save_timings(to: List[Tuple[str, float]]) -> Generator[None, None, None]: token = TIMINGS.set([]) yield to.extend(TIMINGS.get()) TIMINGS.reset(token) def merge_timings(more: List[Tuple[str, float]]) -> None: TIMINGS.get().extend(more) def print_timings(fn: Callable[[str], None] = print) -> None: for msg, duration in TIMINGS.get(): fn(f"{msg + ':':50} {int(duration*1000000):7} µs") def try_parse(path: Path, data: Optional[bytes] = None) -> cst.Module: if data is None: data = path.read_bytes() with timed(f"parsing {path}"): parse_error: Optional[cst.ParserSyntaxError] = None for version in cst.KNOWN_PYTHON_VERSION_STRINGS[::-1]: try: mod = cst.parse_module( data, cst.PartialParserConfig(python_version=version) ) return mod except cst.ParserSyntaxError as e: if parse_error is None: parse_error = e # errors, and usort_path is already going to wrap it in a custom class raise parse_error or Exception("unknown parse failure")
true
true
f717c2b8fff53fa6c6659e99b4b2a067e7f9823a
2,440
py
Python
model/experiment/gaussian_naive_bayes_model.py
theBraindonor/chicago-crime-arrests
64cdb82fbe828d1316cf945b67ddc205ef190293
[ "CC-BY-4.0" ]
1
2019-04-29T10:32:26.000Z
2019-04-29T10:32:26.000Z
model/experiment/gaussian_naive_bayes_model.py
theBraindonor/chicago-crime-arrests
64cdb82fbe828d1316cf945b67ddc205ef190293
[ "CC-BY-4.0" ]
4
2020-03-24T16:54:17.000Z
2021-06-01T23:33:48.000Z
model/experiment/gaussian_naive_bayes_model.py
theBraindonor/chicago-crime-arrests
64cdb82fbe828d1316cf945b67ddc205ef190293
[ "CC-BY-4.0" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Experiment with a gaussian naive bayes model with a variety of balancing techniques on the cleaned data set """ __author__ = "John Hoff" __email__ = "john.hoff@braindonor.net" __copyright__ = "Copyright 2019, John Hoff" __license__ = "Creative Commons Attribution-ShareAlike 4.0 International License" __version__ = "1.0" from imblearn.combine import SMOTEENN from imblearn.over_sampling import SMOTE from imblearn.under_sampling import RandomUnderSampler from sklearn.naive_bayes import GaussianNB from utility import Runner from model import load_clean_sample_data_frame, binned_geo_one_hot_data_mapper sample = None fit_increment = 10000 def test_gaussian_naive_bayes(): runner = Runner( 'model/experiment/output/gaussian_naive_bayes_basic', load_clean_sample_data_frame(), 'arrest', GaussianNB() ) runner.run_classification_experiment( sample=sample, record_predict_proba=True, transformer=binned_geo_one_hot_data_mapper, fit_increment=fit_increment, n_jobs=1 ) runner = Runner( 'model/experiment/output/gaussian_naive_bayes_under_sampled', load_clean_sample_data_frame(), 'arrest', GaussianNB() ) runner.run_classification_experiment( sample=sample, record_predict_proba=True, transformer=binned_geo_one_hot_data_mapper, fit_increment=fit_increment, n_jobs=1, sampling=RandomUnderSampler() ) runner = Runner( 'model/experiment/output/gaussian_naive_bayes_over_sampled', load_clean_sample_data_frame(), 'arrest', GaussianNB() ) runner.run_classification_experiment( sample=sample, record_predict_proba=True, transformer=binned_geo_one_hot_data_mapper, fit_increment=fit_increment, n_jobs=1, sampling=SMOTE() ) runner = Runner( 'model/experiment/output/gaussian_naive_bayes_combine_sampled', load_clean_sample_data_frame(), 'arrest', GaussianNB() ) runner.run_classification_experiment( sample=sample, record_predict_proba=True, transformer=binned_geo_one_hot_data_mapper, fit_increment=fit_increment, n_jobs=1, sampling=SMOTEENN() ) if __name__ == '__main__': test_gaussian_naive_bayes()
26.813187
111
0.697951
__author__ = "John Hoff" __email__ = "john.hoff@braindonor.net" __copyright__ = "Copyright 2019, John Hoff" __license__ = "Creative Commons Attribution-ShareAlike 4.0 International License" __version__ = "1.0" from imblearn.combine import SMOTEENN from imblearn.over_sampling import SMOTE from imblearn.under_sampling import RandomUnderSampler from sklearn.naive_bayes import GaussianNB from utility import Runner from model import load_clean_sample_data_frame, binned_geo_one_hot_data_mapper sample = None fit_increment = 10000 def test_gaussian_naive_bayes(): runner = Runner( 'model/experiment/output/gaussian_naive_bayes_basic', load_clean_sample_data_frame(), 'arrest', GaussianNB() ) runner.run_classification_experiment( sample=sample, record_predict_proba=True, transformer=binned_geo_one_hot_data_mapper, fit_increment=fit_increment, n_jobs=1 ) runner = Runner( 'model/experiment/output/gaussian_naive_bayes_under_sampled', load_clean_sample_data_frame(), 'arrest', GaussianNB() ) runner.run_classification_experiment( sample=sample, record_predict_proba=True, transformer=binned_geo_one_hot_data_mapper, fit_increment=fit_increment, n_jobs=1, sampling=RandomUnderSampler() ) runner = Runner( 'model/experiment/output/gaussian_naive_bayes_over_sampled', load_clean_sample_data_frame(), 'arrest', GaussianNB() ) runner.run_classification_experiment( sample=sample, record_predict_proba=True, transformer=binned_geo_one_hot_data_mapper, fit_increment=fit_increment, n_jobs=1, sampling=SMOTE() ) runner = Runner( 'model/experiment/output/gaussian_naive_bayes_combine_sampled', load_clean_sample_data_frame(), 'arrest', GaussianNB() ) runner.run_classification_experiment( sample=sample, record_predict_proba=True, transformer=binned_geo_one_hot_data_mapper, fit_increment=fit_increment, n_jobs=1, sampling=SMOTEENN() ) if __name__ == '__main__': test_gaussian_naive_bayes()
true
true
f717c597ce99c986760a12c223c014567cf34f38
96,886
py
Python
ThirdParty/ZopeInterface/zope/interface/tests/test_registry.py
OpenGeoscience/VTK
a373e975b9284a022f43a062ebf5042bb17b4e44
[ "BSD-3-Clause" ]
3
2016-02-01T02:29:51.000Z
2020-09-04T17:19:24.000Z
ThirdParty/ZopeInterface/zope/interface/tests/test_registry.py
OpenGeoscience/VTK
a373e975b9284a022f43a062ebf5042bb17b4e44
[ "BSD-3-Clause" ]
7
2021-02-08T20:22:15.000Z
2022-03-11T23:19:41.000Z
ThirdParty/ZopeInterface/zope/interface/tests/test_registry.py
OpenGeoscience/VTK
a373e975b9284a022f43a062ebf5042bb17b4e44
[ "BSD-3-Clause" ]
6
2017-02-13T09:11:02.000Z
2021-06-29T11:22:18.000Z
############################################################################## # # Copyright (c) 2001, 2002, 2009 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Component Registry Tests""" import unittest class _SilencePy3Deprecations(unittest.TestCase): # silence deprecation warnings under py3 def failUnless(self, expr): # St00pid speling. return self.assertTrue(expr) def failIf(self, expr): # St00pid speling. return self.assertFalse(expr) class ComponentsTests(_SilencePy3Deprecations): def _getTargetClass(self): from zope.interface.registry import Components return Components def _makeOne(self, name='test', *args, **kw): return self._getTargetClass()(name, *args, **kw) def _wrapEvents(self): from zope.interface import registry _events = [] def _notify(*args, **kw): _events.append((args, kw)) _monkey = _Monkey(registry, notify=_notify) return _monkey, _events def test_ctor_no_bases(self): from zope.interface.adapter import AdapterRegistry comp = self._makeOne('testing') self.assertEqual(comp.__name__, 'testing') self.assertEqual(comp.__bases__, ()) self.failUnless(isinstance(comp.adapters, AdapterRegistry)) self.failUnless(isinstance(comp.utilities, AdapterRegistry)) self.assertEqual(comp.adapters.__bases__, ()) self.assertEqual(comp.utilities.__bases__, ()) self.assertEqual(comp._utility_registrations, {}) self.assertEqual(comp._adapter_registrations, {}) self.assertEqual(comp._subscription_registrations, []) self.assertEqual(comp._handler_registrations, []) def test_ctor_w_base(self): base = self._makeOne('base') comp = self._makeOne('testing', (base,)) self.assertEqual(comp.__name__, 'testing') self.assertEqual(comp.__bases__, (base,)) self.assertEqual(comp.adapters.__bases__, (base.adapters,)) self.assertEqual(comp.utilities.__bases__, (base.utilities,)) def test___repr__(self): comp = self._makeOne('testing') self.assertEqual(repr(comp), '<Components testing>') # test _init_registries / _init_registrations via only caller, __init__. def test_assign_to___bases__(self): base1 = self._makeOne('base1') base2 = self._makeOne('base2') comp = self._makeOne() comp.__bases__ = (base1, base2) self.assertEqual(comp.__bases__, (base1, base2)) self.assertEqual(comp.adapters.__bases__, (base1.adapters, base2.adapters)) self.assertEqual(comp.utilities.__bases__, (base1.utilities, base2.utilities)) def test_registerUtility_both_factory_and_component(self): def _factory(): pass _to_reg = object() comp = self._makeOne() self.assertRaises(TypeError, comp.registerUtility, component=_to_reg, factory=_factory) def test_registerUtility_w_component(self): from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Registered from zope.interface.registry import UtilityRegistration from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _info = _u('info') _name = _u('name') _to_reg = object() comp = self._makeOne() _monkey, _events = self._wrapEvents() with _monkey: comp.registerUtility(_to_reg, ifoo, _name, _info) self.failUnless(comp.utilities._adapters[0][ifoo][_name] is _to_reg) self.assertEqual(comp._utility_registrations[ifoo, _name], (_to_reg, _info, None)) self.assertEqual(comp.utilities._subscribers[0][ifoo][''], (_to_reg,)) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Registered)) self.failUnless(isinstance(event.object, UtilityRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.failUnless(event.object.name is _name) self.failUnless(event.object.component is _to_reg) self.failUnless(event.object.info is _info) self.failUnless(event.object.factory is None) def test_registerUtility_w_factory(self): from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Registered from zope.interface.registry import UtilityRegistration from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _info = _u('info') _name = _u('name') _to_reg = object() def _factory(): return _to_reg comp = self._makeOne() _monkey, _events = self._wrapEvents() with _monkey: comp.registerUtility(None, ifoo, _name, _info, factory=_factory) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Registered)) self.failUnless(isinstance(event.object, UtilityRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.failUnless(event.object.name is _name) self.failUnless(event.object.component is _to_reg) self.failUnless(event.object.info is _info) self.failUnless(event.object.factory is _factory) def test_registerUtility_no_provided_available(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass class Foo(object): pass ifoo = IFoo('IFoo') _info = _u('info') _name = _u('name') _to_reg = Foo() comp = self._makeOne() self.assertRaises(TypeError, comp.registerUtility, _to_reg, None, _name, _info) def test_registerUtility_wo_provided(self): from zope.interface.declarations import directlyProvides from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Registered from zope.interface.registry import UtilityRegistration from zope.interface._compat import _u class IFoo(InterfaceClass): pass class Foo(object): pass ifoo = IFoo('IFoo') _info = _u('info') _name = _u('name') _to_reg = Foo() directlyProvides(_to_reg, ifoo) comp = self._makeOne() _monkey, _events = self._wrapEvents() with _monkey: comp.registerUtility(_to_reg, None, _name, _info) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Registered)) self.failUnless(isinstance(event.object, UtilityRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.failUnless(event.object.name is _name) self.failUnless(event.object.component is _to_reg) self.failUnless(event.object.info is _info) self.failUnless(event.object.factory is None) def test_registerUtility_duplicates_existing_reg(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _info = _u('info') _name = _u('name') _to_reg = object() comp = self._makeOne() comp.registerUtility(_to_reg, ifoo, _name, _info) _monkey, _events = self._wrapEvents() with _monkey: comp.registerUtility(_to_reg, ifoo, _name, _info) self.assertEqual(len(_events), 0) def test_registerUtility_replaces_existing_reg(self): from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Unregistered from zope.interface.interfaces import Registered from zope.interface.registry import UtilityRegistration from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _info = _u('info') _name = _u('name') _before, _after = object(), object() comp = self._makeOne() comp.registerUtility(_before, ifoo, _name, _info) _monkey, _events = self._wrapEvents() with _monkey: comp.registerUtility(_after, ifoo, _name, _info) self.assertEqual(len(_events), 2) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Unregistered)) self.failUnless(isinstance(event.object, UtilityRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.failUnless(event.object.name is _name) self.failUnless(event.object.component is _before) self.failUnless(event.object.info is _info) self.failUnless(event.object.factory is None) args, kw = _events[1] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Registered)) self.failUnless(isinstance(event.object, UtilityRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.failUnless(event.object.name is _name) self.failUnless(event.object.component is _after) self.failUnless(event.object.info is _info) self.failUnless(event.object.factory is None) def test_registerUtility_w_existing_subscr(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _info = _u('info') _name1 = _u('name1') _name2 = _u('name2') _to_reg = object() comp = self._makeOne() comp.registerUtility(_to_reg, ifoo, _name1, _info) _monkey, _events = self._wrapEvents() with _monkey: comp.registerUtility(_to_reg, ifoo, _name2, _info) self.assertEqual(comp.utilities._subscribers[0][ifoo][''], (_to_reg,)) def test_registerUtility_wo_event(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _info = _u('info') _name = _u('name') _to_reg = object() comp = self._makeOne() _monkey, _events = self._wrapEvents() with _monkey: comp.registerUtility(_to_reg, ifoo, _name, _info, False) self.assertEqual(len(_events), 0) def test_unregisterUtility_neither_factory_nor_component_nor_provided(self): comp = self._makeOne() self.assertRaises(TypeError, comp.unregisterUtility, component=None, provided=None, factory=None) def test_unregisterUtility_both_factory_and_component(self): def _factory(): pass _to_reg = object() comp = self._makeOne() self.assertRaises(TypeError, comp.unregisterUtility, component=_to_reg, factory=_factory) def test_unregisterUtility_w_component_miss(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _name = _u('name') _to_reg = object() comp = self._makeOne() _monkey, _events = self._wrapEvents() with _monkey: unreg = comp.unregisterUtility(_to_reg, ifoo, _name) self.failIf(unreg) self.failIf(_events) def test_unregisterUtility_w_component(self): from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Unregistered from zope.interface.registry import UtilityRegistration from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _name = _u('name') _to_reg = object() comp = self._makeOne() comp.registerUtility(_to_reg, ifoo, _name) _monkey, _events = self._wrapEvents() with _monkey: unreg = comp.unregisterUtility(_to_reg, ifoo, _name) self.failUnless(unreg) self.failIf(comp.utilities._adapters) # all erased self.failIf((ifoo, _name) in comp._utility_registrations) self.failIf(comp.utilities._subscribers) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Unregistered)) self.failUnless(isinstance(event.object, UtilityRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.failUnless(event.object.name is _name) self.failUnless(event.object.component is _to_reg) self.failUnless(event.object.factory is None) def test_unregisterUtility_w_factory(self): from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Unregistered from zope.interface.registry import UtilityRegistration from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _info = _u('info') _name = _u('name') _to_reg = object() def _factory(): return _to_reg comp = self._makeOne() comp.registerUtility(None, ifoo, _name, _info, factory=_factory) _monkey, _events = self._wrapEvents() with _monkey: unreg = comp.unregisterUtility(None, ifoo, _name, factory=_factory) self.failUnless(unreg) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Unregistered)) self.failUnless(isinstance(event.object, UtilityRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.failUnless(event.object.name is _name) self.failUnless(event.object.component is _to_reg) self.failUnless(event.object.factory is _factory) def test_unregisterUtility_wo_explicit_provided(self): from zope.interface.declarations import directlyProvides from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Unregistered from zope.interface.registry import UtilityRegistration from zope.interface._compat import _u class IFoo(InterfaceClass): pass class Foo(object): pass ifoo = IFoo('IFoo') _info = _u('info') _name = _u('name') _to_reg = Foo() directlyProvides(_to_reg, ifoo) comp = self._makeOne() comp.registerUtility(_to_reg, ifoo, _name, _info) _monkey, _events = self._wrapEvents() with _monkey: unreg = comp.unregisterUtility(_to_reg, None, _name) self.failUnless(unreg) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Unregistered)) self.failUnless(isinstance(event.object, UtilityRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.failUnless(event.object.name is _name) self.failUnless(event.object.component is _to_reg) self.failUnless(event.object.info is _info) self.failUnless(event.object.factory is None) def test_unregisterUtility_wo_component_or_factory(self): from zope.interface.declarations import directlyProvides from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Unregistered from zope.interface.registry import UtilityRegistration from zope.interface._compat import _u class IFoo(InterfaceClass): pass class Foo(object): pass ifoo = IFoo('IFoo') _info = _u('info') _name = _u('name') _to_reg = Foo() directlyProvides(_to_reg, ifoo) comp = self._makeOne() comp.registerUtility(_to_reg, ifoo, _name, _info) _monkey, _events = self._wrapEvents() with _monkey: # Just pass the interface / name unreg = comp.unregisterUtility(provided=ifoo, name=_name) self.failUnless(unreg) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Unregistered)) self.failUnless(isinstance(event.object, UtilityRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.failUnless(event.object.name is _name) self.failUnless(event.object.component is _to_reg) self.failUnless(event.object.info is _info) self.failUnless(event.object.factory is None) def test_unregisterUtility_w_existing_subscr(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _info = _u('info') _name1 = _u('name1') _name2 = _u('name2') _to_reg = object() comp = self._makeOne() comp.registerUtility(_to_reg, ifoo, _name1, _info) comp.registerUtility(_to_reg, ifoo, _name2, _info) _monkey, _events = self._wrapEvents() with _monkey: comp.unregisterUtility(_to_reg, ifoo, _name2) self.assertEqual(comp.utilities._subscribers[0][ifoo][''], (_to_reg,)) def test_registeredUtilities_empty(self): comp = self._makeOne() self.assertEqual(list(comp.registeredUtilities()), []) def test_registeredUtilities_notempty(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u from zope.interface.registry import UtilityRegistration class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _info = _u('info') _name1 = _u('name1') _name2 = _u('name2') _to_reg = object() comp = self._makeOne() comp.registerUtility(_to_reg, ifoo, _name1, _info) comp.registerUtility(_to_reg, ifoo, _name2, _info) reg = sorted(comp.registeredUtilities(), key=lambda r: r.name) self.assertEqual(len(reg), 2) self.failUnless(isinstance(reg[0], UtilityRegistration)) self.failUnless(reg[0].registry is comp) self.failUnless(reg[0].provided is ifoo) self.failUnless(reg[0].name is _name1) self.failUnless(reg[0].component is _to_reg) self.failUnless(reg[0].info is _info) self.failUnless(reg[0].factory is None) self.failUnless(isinstance(reg[1], UtilityRegistration)) self.failUnless(reg[1].registry is comp) self.failUnless(reg[1].provided is ifoo) self.failUnless(reg[1].name is _name2) self.failUnless(reg[1].component is _to_reg) self.failUnless(reg[1].info is _info) self.failUnless(reg[1].factory is None) def test_queryUtility_miss_no_default(self): from zope.interface.declarations import InterfaceClass class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') comp = self._makeOne() self.failUnless(comp.queryUtility(ifoo) is None) def test_queryUtility_miss_w_default(self): from zope.interface.declarations import InterfaceClass class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') comp = self._makeOne() _default = object() self.failUnless(comp.queryUtility(ifoo, default=_default) is _default) def test_queryUtility_hit(self): from zope.interface.declarations import InterfaceClass class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _to_reg = object() comp = self._makeOne() comp.registerUtility(_to_reg, ifoo) self.failUnless(comp.queryUtility(ifoo) is _to_reg) def test_getUtility_miss(self): from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import ComponentLookupError class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') comp = self._makeOne() self.assertRaises(ComponentLookupError, comp.getUtility, ifoo) def test_getUtility_hit(self): from zope.interface.declarations import InterfaceClass class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _to_reg = object() comp = self._makeOne() comp.registerUtility(_to_reg, ifoo) self.failUnless(comp.getUtility(ifoo) is _to_reg) def test_getUtilitiesFor_miss(self): from zope.interface.declarations import InterfaceClass class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') comp = self._makeOne() self.assertEqual(list(comp.getUtilitiesFor(ifoo)), []) def test_getUtilitiesFor_hit(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _name1 = _u('name1') _name2 = _u('name2') _to_reg = object() comp = self._makeOne() comp.registerUtility(_to_reg, ifoo, name=_name1) comp.registerUtility(_to_reg, ifoo, name=_name2) self.assertEqual(sorted(comp.getUtilitiesFor(ifoo)), [(_name1, _to_reg), (_name2, _to_reg)]) def test_getAllUtilitiesRegisteredFor_miss(self): from zope.interface.declarations import InterfaceClass class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') comp = self._makeOne() self.assertEqual(list(comp.getAllUtilitiesRegisteredFor(ifoo)), []) def test_getAllUtilitiesRegisteredFor_hit(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _name1 = _u('name1') _name2 = _u('name2') _to_reg = object() comp = self._makeOne() comp.registerUtility(_to_reg, ifoo, name=_name1) comp.registerUtility(_to_reg, ifoo, name=_name2) self.assertEqual(list(comp.getAllUtilitiesRegisteredFor(ifoo)), [_to_reg]) def test_registerAdapter_w_explicit_provided_and_required(self): from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Registered from zope.interface.registry import AdapterRegistration from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') _info = _u('info') _name = _u('name') _to_reg = object() def _factory(context): return _to_reg comp = self._makeOne() _monkey, _events = self._wrapEvents() with _monkey: comp.registerAdapter(_factory, (ibar,), ifoo, _name, _info) self.failUnless(comp.adapters._adapters[1][ibar][ifoo][_name] is _factory) self.assertEqual(comp._adapter_registrations[(ibar,), ifoo, _name], (_factory, _info)) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Registered)) self.failUnless(isinstance(event.object, AdapterRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.assertEqual(event.object.required, (ibar,)) self.failUnless(event.object.name is _name) self.failUnless(event.object.info is _info) self.failUnless(event.object.factory is _factory) def test_registerAdapter_no_provided_available(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') _info = _u('info') _name = _u('name') _to_reg = object() class _Factory(object): def __init__(self, context): self._context = context comp = self._makeOne() self.assertRaises(TypeError, comp.registerAdapter, _Factory, (ibar,), name=_name, info=_info) def test_registerAdapter_wo_explicit_provided(self): from zope.interface.declarations import InterfaceClass from zope.interface.declarations import implementer from zope.interface.interfaces import Registered from zope.interface.registry import AdapterRegistration from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') _info = _u('info') _name = _u('name') _to_reg = object() @implementer(ifoo) class _Factory(object): def __init__(self, context): self._context = context comp = self._makeOne() _monkey, _events = self._wrapEvents() with _monkey: comp.registerAdapter(_Factory, (ibar,), name=_name, info=_info) self.failUnless(comp.adapters._adapters[1][ibar][ifoo][_name] is _Factory) self.assertEqual(comp._adapter_registrations[(ibar,), ifoo, _name], (_Factory, _info)) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Registered)) self.failUnless(isinstance(event.object, AdapterRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.assertEqual(event.object.required, (ibar,)) self.failUnless(event.object.name is _name) self.failUnless(event.object.info is _info) self.failUnless(event.object.factory is _Factory) def test_registerAdapter_no_required_available(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') _info = _u('info') _name = _u('name') class _Factory(object): def __init__(self, context): self._context = context comp = self._makeOne() self.assertRaises(TypeError, comp.registerAdapter, _Factory, provided=ifoo, name=_name, info=_info) def test_registerAdapter_w_invalid_required(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') _info = _u('info') _name = _u('name') class _Factory(object): def __init__(self, context): self._context = context comp = self._makeOne() self.assertRaises(TypeError, comp.registerAdapter, _Factory, ibar, provided=ifoo, name=_name, info=_info) def test_registerAdapter_w_required_containing_None(self): from zope.interface.declarations import InterfaceClass from zope.interface.interface import Interface from zope.interface.interfaces import Registered from zope.interface.registry import AdapterRegistration from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _info = _u('info') _name = _u('name') class _Factory(object): def __init__(self, context): self._context = context comp = self._makeOne() _monkey, _events = self._wrapEvents() with _monkey: comp.registerAdapter(_Factory, [None], provided=ifoo, name=_name, info=_info) self.failUnless(comp.adapters._adapters[1][Interface][ifoo][_name] is _Factory) self.assertEqual(comp._adapter_registrations[(Interface,), ifoo, _name], (_Factory, _info)) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Registered)) self.failUnless(isinstance(event.object, AdapterRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.assertEqual(event.object.required, (Interface,)) self.failUnless(event.object.name is _name) self.failUnless(event.object.info is _info) self.failUnless(event.object.factory is _Factory) def test_registerAdapter_w_required_containing_class(self): from zope.interface.declarations import InterfaceClass from zope.interface.declarations import implementer from zope.interface.declarations import implementedBy from zope.interface.interfaces import Registered from zope.interface.registry import AdapterRegistration from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') _info = _u('info') _name = _u('name') class _Factory(object): def __init__(self, context): self._context = context @implementer(ibar) class _Context(object): pass _ctx_impl = implementedBy(_Context) comp = self._makeOne() _monkey, _events = self._wrapEvents() with _monkey: comp.registerAdapter(_Factory, [_Context], provided=ifoo, name=_name, info=_info) self.failUnless(comp.adapters._adapters[1][_ctx_impl][ifoo][_name] is _Factory) self.assertEqual(comp._adapter_registrations[(_ctx_impl,), ifoo, _name], (_Factory, _info)) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Registered)) self.failUnless(isinstance(event.object, AdapterRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.assertEqual(event.object.required, (_ctx_impl,)) self.failUnless(event.object.name is _name) self.failUnless(event.object.info is _info) self.failUnless(event.object.factory is _Factory) def test_registerAdapter_w_required_containing_junk(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') _info = _u('info') _name = _u('name') class _Factory(object): def __init__(self, context): self._context = context comp = self._makeOne() self.assertRaises(TypeError, comp.registerAdapter, _Factory, [object()], provided=ifoo, name=_name, info=_info) def test_registerAdapter_wo_explicit_required(self): from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Registered from zope.interface.registry import AdapterRegistration from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') _info = _u('info') _name = _u('name') class _Factory(object): __component_adapts__ = (ibar,) def __init__(self, context): self._context = context comp = self._makeOne() _monkey, _events = self._wrapEvents() with _monkey: comp.registerAdapter(_Factory, provided=ifoo, name=_name, info=_info) self.failUnless(comp.adapters._adapters[1][ibar][ifoo][_name] is _Factory) self.assertEqual(comp._adapter_registrations[(ibar,), ifoo, _name], (_Factory, _info)) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Registered)) self.failUnless(isinstance(event.object, AdapterRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.assertEqual(event.object.required, (ibar,)) self.failUnless(event.object.name is _name) self.failUnless(event.object.info is _info) self.failUnless(event.object.factory is _Factory) def test_registerAdapter_wo_event(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') _info = _u('info') _name = _u('name') _to_reg = object() def _factory(context): return _to_reg comp = self._makeOne() _monkey, _events = self._wrapEvents() with _monkey: comp.registerAdapter(_factory, (ibar,), ifoo, _name, _info, event=False) self.assertEqual(len(_events), 0) def test_unregisterAdapter_neither_factory_nor_provided(self): comp = self._makeOne() self.assertRaises(TypeError, comp.unregisterAdapter, factory=None, provided=None) def test_unregisterAdapter_neither_factory_nor_required(self): from zope.interface.declarations import InterfaceClass class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') comp = self._makeOne() self.assertRaises(TypeError, comp.unregisterAdapter, factory=None, provided=ifoo, required=None) def test_unregisterAdapter_miss(self): from zope.interface.declarations import InterfaceClass class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') class _Factory(object): def __init__(self, context): self._context = context comp = self._makeOne() _monkey, _events = self._wrapEvents() with _monkey: unreg = comp.unregisterAdapter(_Factory, (ibar,), ifoo) self.failIf(unreg) def test_unregisterAdapter_hit_w_explicit_provided_and_required(self): from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Unregistered from zope.interface.registry import AdapterRegistration class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') class _Factory(object): def __init__(self, context): self._context = context comp = self._makeOne() comp.registerAdapter(_Factory, (ibar,), ifoo) _monkey, _events = self._wrapEvents() with _monkey: unreg = comp.unregisterAdapter(_Factory, (ibar,), ifoo) self.failUnless(unreg) self.failIf(comp.adapters._adapters) self.failIf(comp._adapter_registrations) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Unregistered)) self.failUnless(isinstance(event.object, AdapterRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.assertEqual(event.object.required, (ibar,)) self.assertEqual(event.object.name, '') self.assertEqual(event.object.info, '') self.failUnless(event.object.factory is _Factory) def test_unregisterAdapter_wo_explicit_provided(self): from zope.interface.declarations import InterfaceClass from zope.interface.declarations import implementer from zope.interface.interfaces import Unregistered from zope.interface.registry import AdapterRegistration class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') @implementer(ifoo) class _Factory(object): def __init__(self, context): self._context = context comp = self._makeOne() comp.registerAdapter(_Factory, (ibar,), ifoo) _monkey, _events = self._wrapEvents() with _monkey: unreg = comp.unregisterAdapter(_Factory, (ibar,)) self.failUnless(unreg) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Unregistered)) self.failUnless(isinstance(event.object, AdapterRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.assertEqual(event.object.required, (ibar,)) self.assertEqual(event.object.name, '') self.assertEqual(event.object.info, '') self.failUnless(event.object.factory is _Factory) def test_unregisterAdapter_wo_explicit_required(self): from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Unregistered from zope.interface.registry import AdapterRegistration class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') class _Factory(object): __component_adapts__ = (ibar,) def __init__(self, context): self._context = context comp = self._makeOne() comp.registerAdapter(_Factory, (ibar,), ifoo) _monkey, _events = self._wrapEvents() with _monkey: unreg = comp.unregisterAdapter(_Factory, provided=ifoo) self.failUnless(unreg) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Unregistered)) self.failUnless(isinstance(event.object, AdapterRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.assertEqual(event.object.required, (ibar,)) self.assertEqual(event.object.name, '') self.assertEqual(event.object.info, '') self.failUnless(event.object.factory is _Factory) def test_registeredAdapters_empty(self): comp = self._makeOne() self.assertEqual(list(comp.registeredAdapters()), []) def test_registeredAdapters_notempty(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u from zope.interface.registry import AdapterRegistration class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IFoo') _info = _u('info') _name1 = _u('name1') _name2 = _u('name2') class _Factory(object): def __init__(self, context): pass comp = self._makeOne() comp.registerAdapter(_Factory, (ibar,), ifoo, _name1, _info) comp.registerAdapter(_Factory, (ibar,), ifoo, _name2, _info) reg = sorted(comp.registeredAdapters(), key=lambda r: r.name) self.assertEqual(len(reg), 2) self.failUnless(isinstance(reg[0], AdapterRegistration)) self.failUnless(reg[0].registry is comp) self.failUnless(reg[0].provided is ifoo) self.assertEqual(reg[0].required, (ibar,)) self.failUnless(reg[0].name is _name1) self.failUnless(reg[0].info is _info) self.failUnless(reg[0].factory is _Factory) self.failUnless(isinstance(reg[1], AdapterRegistration)) self.failUnless(reg[1].registry is comp) self.failUnless(reg[1].provided is ifoo) self.assertEqual(reg[1].required, (ibar,)) self.failUnless(reg[1].name is _name2) self.failUnless(reg[1].info is _info) self.failUnless(reg[1].factory is _Factory) def test_queryAdapter_miss_no_default(self): from zope.interface.declarations import InterfaceClass class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') comp = self._makeOne() _context = object() self.failUnless(comp.queryAdapter(_context, ifoo) is None) def test_queryAdapter_miss_w_default(self): from zope.interface.declarations import InterfaceClass class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') comp = self._makeOne() _context = object() _default = object() self.failUnless( comp.queryAdapter(_context, ifoo, default=_default) is _default) def test_queryAdapter_hit(self): from zope.interface.declarations import InterfaceClass from zope.interface.declarations import implementer class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') class _Factory(object): def __init__(self, context): self.context = context @implementer(ibar) class _Context(object): pass _context = _Context() comp = self._makeOne() comp.registerAdapter(_Factory, (ibar,), ifoo) adapter = comp.queryAdapter(_context, ifoo) self.failUnless(isinstance(adapter, _Factory)) self.failUnless(adapter.context is _context) def test_getAdapter_miss(self): from zope.interface.declarations import InterfaceClass from zope.interface.declarations import implementer from zope.interface.interfaces import ComponentLookupError class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') @implementer(ibar) class _Context(object): pass _context = _Context() comp = self._makeOne() self.assertRaises(ComponentLookupError, comp.getAdapter, _context, ifoo) def test_getAdapter_hit(self): from zope.interface.declarations import InterfaceClass from zope.interface.declarations import implementer class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') class _Factory(object): def __init__(self, context): self.context = context @implementer(ibar) class _Context(object): pass _context = _Context() comp = self._makeOne() comp.registerAdapter(_Factory, (ibar,), ifoo) adapter = comp.getAdapter(_context, ifoo) self.failUnless(isinstance(adapter, _Factory)) self.failUnless(adapter.context is _context) def test_queryMultiAdapter_miss(self): from zope.interface.declarations import InterfaceClass from zope.interface.declarations import implementer class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') ibaz = IFoo('IBaz') @implementer(ibar) class _Context1(object): pass @implementer(ibaz) class _Context2(object): pass _context1 = _Context1() _context2 = _Context2() comp = self._makeOne() self.assertEqual(comp.queryMultiAdapter((_context1, _context2), ifoo), None) def test_queryMultiAdapter_miss_w_default(self): from zope.interface.declarations import InterfaceClass from zope.interface.declarations import implementer class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') ibaz = IFoo('IBaz') @implementer(ibar) class _Context1(object): pass @implementer(ibaz) class _Context2(object): pass _context1 = _Context1() _context2 = _Context2() _default = object() comp = self._makeOne() self.failUnless( comp.queryMultiAdapter((_context1, _context2), ifoo, default=_default) is _default) def test_queryMultiAdapter_hit(self): from zope.interface.declarations import InterfaceClass from zope.interface.declarations import implementer class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') ibaz = IFoo('IBaz') @implementer(ibar) class _Context1(object): pass @implementer(ibaz) class _Context2(object): pass _context1 = _Context1() _context2 = _Context2() class _Factory(object): def __init__(self, context1, context2): self.context = context1, context2 comp = self._makeOne() comp.registerAdapter(_Factory, (ibar, ibaz), ifoo) adapter = comp.queryMultiAdapter((_context1, _context2), ifoo) self.failUnless(isinstance(adapter, _Factory)) self.assertEqual(adapter.context, (_context1, _context2)) def test_getMultiAdapter_miss(self): from zope.interface.declarations import InterfaceClass from zope.interface.declarations import implementer from zope.interface.interfaces import ComponentLookupError class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') ibaz = IFoo('IBaz') @implementer(ibar) class _Context1(object): pass @implementer(ibaz) class _Context2(object): pass _context1 = _Context1() _context2 = _Context2() comp = self._makeOne() self.assertRaises(ComponentLookupError, comp.getMultiAdapter, (_context1, _context2), ifoo) def test_getMultiAdapter_hit(self): from zope.interface.declarations import InterfaceClass from zope.interface.declarations import implementer class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') ibaz = IFoo('IBaz') @implementer(ibar) class _Context1(object): pass @implementer(ibaz) class _Context2(object): pass _context1 = _Context1() _context2 = _Context2() class _Factory(object): def __init__(self, context1, context2): self.context = context1, context2 comp = self._makeOne() comp.registerAdapter(_Factory, (ibar, ibaz), ifoo) adapter = comp.getMultiAdapter((_context1, _context2), ifoo) self.failUnless(isinstance(adapter, _Factory)) self.assertEqual(adapter.context, (_context1, _context2)) def test_getAdapters_empty(self): from zope.interface.declarations import InterfaceClass from zope.interface.declarations import implementer class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') ibaz = IFoo('IBaz') @implementer(ibar) class _Context1(object): pass @implementer(ibaz) class _Context2(object): pass _context1 = _Context1() _context2 = _Context2() comp = self._makeOne() self.assertEqual( list(comp.getAdapters((_context1, _context2), ifoo)), []) def test_getAdapters_non_empty(self): from zope.interface.declarations import InterfaceClass from zope.interface.declarations import implementer from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') ibaz = IFoo('IBaz') @implementer(ibar) class _Context1(object): pass @implementer(ibaz) class _Context2(object): pass _context1 = _Context1() _context2 = _Context2() class _Factory1(object): def __init__(self, context1, context2): self.context = context1, context2 class _Factory2(object): def __init__(self, context1, context2): self.context = context1, context2 _name1 = _u('name1') _name2 = _u('name2') comp = self._makeOne() comp.registerAdapter(_Factory1, (ibar, ibaz), ifoo, name=_name1) comp.registerAdapter(_Factory2, (ibar, ibaz), ifoo, name=_name2) found = sorted(comp.getAdapters((_context1, _context2), ifoo)) self.assertEqual(len(found), 2) self.assertEqual(found[0][0], _name1) self.failUnless(isinstance(found[0][1], _Factory1)) self.assertEqual(found[1][0], _name2) self.failUnless(isinstance(found[1][1], _Factory2)) def test_registerSubscriptionAdapter_w_nonblank_name(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') _name = _u('name') _info = _u('info') _to_reg = object() def _factory(context): return _to_reg comp = self._makeOne() self.assertRaises(TypeError, comp.registerSubscriptionAdapter, _factory, (ibar,), ifoo, _name, _info) def test_registerSubscriptionAdapter_w_explicit_provided_and_required(self): from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Registered from zope.interface.registry import SubscriptionRegistration from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') _blank = _u('') _info = _u('info') _to_reg = object() def _factory(context): return _to_reg comp = self._makeOne() _monkey, _events = self._wrapEvents() with _monkey: comp.registerSubscriptionAdapter(_factory, (ibar,), ifoo, info=_info) reg = comp.adapters._subscribers[1][ibar][ifoo][_blank] self.assertEqual(len(reg), 1) self.failUnless(reg[0] is _factory) self.assertEqual(comp._subscription_registrations, [((ibar,), ifoo, _blank, _factory, _info)]) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Registered)) self.failUnless(isinstance(event.object, SubscriptionRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.assertEqual(event.object.required, (ibar,)) self.assertEqual(event.object.name, _blank) self.failUnless(event.object.info is _info) self.failUnless(event.object.factory is _factory) def test_registerSubscriptionAdapter_wo_explicit_provided(self): from zope.interface.declarations import InterfaceClass from zope.interface.declarations import implementer from zope.interface.interfaces import Registered from zope.interface.registry import SubscriptionRegistration from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') _info = _u('info') _blank = _u('') _to_reg = object() @implementer(ifoo) class _Factory(object): def __init__(self, context): self._context = context comp = self._makeOne() _monkey, _events = self._wrapEvents() with _monkey: comp.registerSubscriptionAdapter(_Factory, (ibar,), info=_info) reg = comp.adapters._subscribers[1][ibar][ifoo][_blank] self.assertEqual(len(reg), 1) self.failUnless(reg[0] is _Factory) self.assertEqual(comp._subscription_registrations, [((ibar,), ifoo, _blank, _Factory, _info)]) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Registered)) self.failUnless(isinstance(event.object, SubscriptionRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.assertEqual(event.object.required, (ibar,)) self.assertEqual(event.object.name, _blank) self.failUnless(event.object.info is _info) self.failUnless(event.object.factory is _Factory) def test_registerSubscriptionAdapter_wo_explicit_required(self): from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Registered from zope.interface.registry import SubscriptionRegistration from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') _info = _u('info') _blank = _u('') class _Factory(object): __component_adapts__ = (ibar,) def __init__(self, context): self._context = context comp = self._makeOne() _monkey, _events = self._wrapEvents() with _monkey: comp.registerSubscriptionAdapter( _Factory, provided=ifoo, info=_info) reg = comp.adapters._subscribers[1][ibar][ifoo][_blank] self.assertEqual(len(reg), 1) self.failUnless(reg[0] is _Factory) self.assertEqual(comp._subscription_registrations, [((ibar,), ifoo, _blank, _Factory, _info)]) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Registered)) self.failUnless(isinstance(event.object, SubscriptionRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.assertEqual(event.object.required, (ibar,)) self.assertEqual(event.object.name, _blank) self.failUnless(event.object.info is _info) self.failUnless(event.object.factory is _Factory) def test_registerSubscriptionAdapter_wo_event(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') _blank = _u('') _info = _u('info') _to_reg = object() def _factory(context): return _to_reg comp = self._makeOne() _monkey, _events = self._wrapEvents() with _monkey: comp.registerSubscriptionAdapter(_factory, (ibar,), ifoo, info=_info, event=False) self.assertEqual(len(_events), 0) def test_registeredSubscriptionAdapters_empty(self): comp = self._makeOne() self.assertEqual(list(comp.registeredSubscriptionAdapters()), []) def test_registeredSubscriptionAdapters_notempty(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u from zope.interface.registry import SubscriptionRegistration class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IFoo') _info = _u('info') _blank = _u('') class _Factory(object): def __init__(self, context): pass comp = self._makeOne() comp.registerSubscriptionAdapter(_Factory, (ibar,), ifoo, info=_info) comp.registerSubscriptionAdapter(_Factory, (ibar,), ifoo, info=_info) reg = list(comp.registeredSubscriptionAdapters()) self.assertEqual(len(reg), 2) self.failUnless(isinstance(reg[0], SubscriptionRegistration)) self.failUnless(reg[0].registry is comp) self.failUnless(reg[0].provided is ifoo) self.assertEqual(reg[0].required, (ibar,)) self.assertEqual(reg[0].name, _blank) self.failUnless(reg[0].info is _info) self.failUnless(reg[0].factory is _Factory) self.failUnless(isinstance(reg[1], SubscriptionRegistration)) self.failUnless(reg[1].registry is comp) self.failUnless(reg[1].provided is ifoo) self.assertEqual(reg[1].required, (ibar,)) self.assertEqual(reg[1].name, _blank) self.failUnless(reg[1].info is _info) self.failUnless(reg[1].factory is _Factory) def test_unregisterSubscriptionAdapter_w_nonblank_name(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') _nonblank = _u('nonblank') comp = self._makeOne() self.assertRaises(TypeError, comp.unregisterSubscriptionAdapter, required=ifoo, provided=ibar, name=_nonblank) def test_unregisterSubscriptionAdapter_neither_factory_nor_provided(self): comp = self._makeOne() self.assertRaises(TypeError, comp.unregisterSubscriptionAdapter, factory=None, provided=None) def test_unregisterSubscriptionAdapter_neither_factory_nor_required(self): from zope.interface.declarations import InterfaceClass class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') comp = self._makeOne() self.assertRaises(TypeError, comp.unregisterSubscriptionAdapter, factory=None, provided=ifoo, required=None) def test_unregisterSubscriptionAdapter_miss(self): from zope.interface.declarations import InterfaceClass class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') class _Factory(object): def __init__(self, context): self._context = context comp = self._makeOne() _monkey, _events = self._wrapEvents() with _monkey: unreg = comp.unregisterSubscriptionAdapter(_Factory, (ibar,), ifoo) self.failIf(unreg) self.failIf(_events) def test_unregisterSubscriptionAdapter_hit_wo_factory(self): from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Unregistered from zope.interface.registry import SubscriptionRegistration class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') class _Factory(object): def __init__(self, context): self._context = context comp = self._makeOne() comp.registerSubscriptionAdapter(_Factory, (ibar,), ifoo) _monkey, _events = self._wrapEvents() with _monkey: unreg = comp.unregisterSubscriptionAdapter(None, (ibar,), ifoo) self.failUnless(unreg) self.failIf(comp.adapters._subscribers) self.failIf(comp._subscription_registrations) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Unregistered)) self.failUnless(isinstance(event.object, SubscriptionRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.assertEqual(event.object.required, (ibar,)) self.assertEqual(event.object.name, '') self.assertEqual(event.object.info, '') self.failUnless(event.object.factory is None) def test_unregisterSubscriptionAdapter_hit_w_factory(self): from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Unregistered from zope.interface.registry import SubscriptionRegistration class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') class _Factory(object): def __init__(self, context): self._context = context comp = self._makeOne() comp.registerSubscriptionAdapter(_Factory, (ibar,), ifoo) _monkey, _events = self._wrapEvents() with _monkey: unreg = comp.unregisterSubscriptionAdapter(_Factory, (ibar,), ifoo) self.failUnless(unreg) self.failIf(comp.adapters._subscribers) self.failIf(comp._subscription_registrations) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Unregistered)) self.failUnless(isinstance(event.object, SubscriptionRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.assertEqual(event.object.required, (ibar,)) self.assertEqual(event.object.name, '') self.assertEqual(event.object.info, '') self.failUnless(event.object.factory is _Factory) def test_unregisterSubscriptionAdapter_wo_explicit_provided(self): from zope.interface.declarations import InterfaceClass from zope.interface.declarations import implementer from zope.interface.interfaces import Unregistered from zope.interface.registry import SubscriptionRegistration class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') @implementer(ifoo) class _Factory(object): def __init__(self, context): self._context = context comp = self._makeOne() comp.registerSubscriptionAdapter(_Factory, (ibar,), ifoo) _monkey, _events = self._wrapEvents() with _monkey: unreg = comp.unregisterSubscriptionAdapter(_Factory, (ibar,)) self.failUnless(unreg) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Unregistered)) self.failUnless(isinstance(event.object, SubscriptionRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.assertEqual(event.object.required, (ibar,)) self.assertEqual(event.object.name, '') self.assertEqual(event.object.info, '') self.failUnless(event.object.factory is _Factory) def test_unregisterSubscriptionAdapter_wo_explicit_required(self): from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Unregistered from zope.interface.registry import SubscriptionRegistration class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') class _Factory(object): __component_adapts__ = (ibar,) def __init__(self, context): self._context = context comp = self._makeOne() comp.registerSubscriptionAdapter(_Factory, (ibar,), ifoo) _monkey, _events = self._wrapEvents() with _monkey: unreg = comp.unregisterSubscriptionAdapter(_Factory, provided=ifoo) self.failUnless(unreg) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Unregistered)) self.failUnless(isinstance(event.object, SubscriptionRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.assertEqual(event.object.required, (ibar,)) self.assertEqual(event.object.name, '') self.assertEqual(event.object.info, '') self.failUnless(event.object.factory is _Factory) def test_subscribers_empty(self): from zope.interface.declarations import InterfaceClass from zope.interface.declarations import implementer class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') comp = self._makeOne() @implementer(ibar) class Bar(object): pass bar = Bar() self.assertEqual(list(comp.subscribers((bar,), ifoo)), []) def test_subscribers_non_empty(self): from zope.interface.declarations import InterfaceClass from zope.interface.declarations import implementer class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') class _Factory(object): __component_adapts__ = (ibar,) def __init__(self, context): self._context = context class _Derived(_Factory): pass comp = self._makeOne() comp.registerSubscriptionAdapter(_Factory, (ibar,), ifoo) comp.registerSubscriptionAdapter(_Derived, (ibar,), ifoo) @implementer(ibar) class Bar(object): pass bar = Bar() subscribers = comp.subscribers((bar,), ifoo) def _klassname(x): return x.__class__.__name__ subscribers = sorted(subscribers, key=_klassname) self.assertEqual(len(subscribers), 2) self.failUnless(isinstance(subscribers[0], _Derived)) self.failUnless(isinstance(subscribers[1], _Factory)) def test_registerHandler_w_nonblank_name(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _nonblank = _u('nonblank') comp = self._makeOne() def _factory(context): pass self.assertRaises(TypeError, comp.registerHandler, _factory, required=ifoo, name=_nonblank) def test_registerHandler_w_explicit_required(self): from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Registered from zope.interface.registry import HandlerRegistration from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _blank = _u('') _info = _u('info') _to_reg = object() def _factory(context): return _to_reg comp = self._makeOne() _monkey, _events = self._wrapEvents() with _monkey: comp.registerHandler(_factory, (ifoo,), info=_info) reg = comp.adapters._subscribers[1][ifoo][None][_blank] self.assertEqual(len(reg), 1) self.failUnless(reg[0] is _factory) self.assertEqual(comp._handler_registrations, [((ifoo,), _blank, _factory, _info)]) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Registered)) self.failUnless(isinstance(event.object, HandlerRegistration)) self.failUnless(event.object.registry is comp) self.assertEqual(event.object.required, (ifoo,)) self.assertEqual(event.object.name, _blank) self.failUnless(event.object.info is _info) self.failUnless(event.object.factory is _factory) def test_registerHandler_wo_explicit_required(self): from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Registered from zope.interface.registry import HandlerRegistration from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _info = _u('info') _blank = _u('') class _Factory(object): __component_adapts__ = (ifoo,) def __init__(self, context): self._context = context comp = self._makeOne() _monkey, _events = self._wrapEvents() with _monkey: comp.registerHandler(_Factory, info=_info) reg = comp.adapters._subscribers[1][ifoo][None][_blank] self.assertEqual(len(reg), 1) self.failUnless(reg[0] is _Factory) self.assertEqual(comp._handler_registrations, [((ifoo,), _blank, _Factory, _info)]) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Registered)) self.failUnless(isinstance(event.object, HandlerRegistration)) self.failUnless(event.object.registry is comp) self.assertEqual(event.object.required, (ifoo,)) self.assertEqual(event.object.name, _blank) self.failUnless(event.object.info is _info) self.failUnless(event.object.factory is _Factory) def test_registeredHandlers_empty(self): from zope.interface.declarations import InterfaceClass class IFoo(InterfaceClass): pass comp = self._makeOne() self.failIf(list(comp.registeredHandlers())) def test_registeredHandlers_non_empty(self): from zope.interface.declarations import InterfaceClass from zope.interface.registry import HandlerRegistration class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') def _factory1(context): pass def _factory2(context): pass comp = self._makeOne() comp.registerHandler(_factory1, (ifoo,)) comp.registerHandler(_factory2, (ifoo,)) def _factory_name(x): return x.factory.__code__.co_name subscribers = sorted(comp.registeredHandlers(), key=_factory_name) self.assertEqual(len(subscribers), 2) self.failUnless(isinstance(subscribers[0], HandlerRegistration)) self.assertEqual(subscribers[0].required, (ifoo,)) self.assertEqual(subscribers[0].name, '') self.assertEqual(subscribers[0].factory, _factory1) self.assertEqual(subscribers[0].info, '') self.failUnless(isinstance(subscribers[1], HandlerRegistration)) self.assertEqual(subscribers[1].required, (ifoo,)) self.assertEqual(subscribers[1].name, '') self.assertEqual(subscribers[1].factory, _factory2) self.assertEqual(subscribers[1].info, '') def test_unregisterHandler_w_nonblank_name(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _nonblank = _u('nonblank') comp = self._makeOne() self.assertRaises(TypeError, comp.unregisterHandler, required=(ifoo,), name=_nonblank) def test_unregisterHandler_neither_factory_nor_required(self): from zope.interface.declarations import InterfaceClass class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') comp = self._makeOne() self.assertRaises(TypeError, comp.unregisterHandler) def test_unregisterHandler_miss(self): from zope.interface.declarations import InterfaceClass class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') comp = self._makeOne() unreg = comp.unregisterHandler(required=(ifoo,)) self.failIf(unreg) def test_unregisterHandler_hit_w_factory_and_explicit_provided(self): from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Unregistered from zope.interface.registry import HandlerRegistration class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') comp = self._makeOne() _to_reg = object() def _factory(context): return _to_reg comp = self._makeOne() comp.registerHandler(_factory, (ifoo,)) _monkey, _events = self._wrapEvents() with _monkey: unreg = comp.unregisterHandler(_factory, (ifoo,)) self.failUnless(unreg) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Unregistered)) self.failUnless(isinstance(event.object, HandlerRegistration)) self.failUnless(event.object.registry is comp) self.assertEqual(event.object.required, (ifoo,)) self.assertEqual(event.object.name, '') self.failUnless(event.object.factory is _factory) def test_unregisterHandler_hit_w_only_explicit_provided(self): from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Unregistered from zope.interface.registry import HandlerRegistration class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') comp = self._makeOne() _to_reg = object() def _factory(context): return _to_reg comp = self._makeOne() comp.registerHandler(_factory, (ifoo,)) _monkey, _events = self._wrapEvents() with _monkey: unreg = comp.unregisterHandler(required=(ifoo,)) self.failUnless(unreg) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Unregistered)) self.failUnless(isinstance(event.object, HandlerRegistration)) self.failUnless(event.object.registry is comp) self.assertEqual(event.object.required, (ifoo,)) self.assertEqual(event.object.name, '') self.failUnless(event.object.factory is None) def test_unregisterHandler_wo_explicit_required(self): from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Unregistered from zope.interface.registry import HandlerRegistration class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') class _Factory(object): __component_adapts__ = (ifoo,) def __init__(self, context): self._context = context comp = self._makeOne() comp.registerHandler(_Factory) _monkey, _events = self._wrapEvents() with _monkey: unreg = comp.unregisterHandler(_Factory) self.failUnless(unreg) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Unregistered)) self.failUnless(isinstance(event.object, HandlerRegistration)) self.failUnless(event.object.registry is comp) self.assertEqual(event.object.required, (ifoo,)) self.assertEqual(event.object.name, '') self.assertEqual(event.object.info, '') self.failUnless(event.object.factory is _Factory) def test_handle_empty(self): from zope.interface.declarations import InterfaceClass from zope.interface.declarations import implementer class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') comp = self._makeOne() @implementer(ifoo) class Bar(object): pass bar = Bar() comp.handle((bar,)) # doesn't raise def test_handle_non_empty(self): from zope.interface.declarations import InterfaceClass from zope.interface.declarations import implementer class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _called_1 = [] def _factory_1(context): _called_1.append(context) _called_2 = [] def _factory_2(context): _called_2.append(context) comp = self._makeOne() comp.registerHandler(_factory_1, (ifoo,)) comp.registerHandler(_factory_2, (ifoo,)) @implementer(ifoo) class Bar(object): pass bar = Bar() comp.handle(bar) self.assertEqual(_called_1, [bar]) self.assertEqual(_called_2, [bar]) # Test _getUtilityProvided, _getAdapterProvided, _getAdapterRequired via their # callers (Component.registerUtility, Component.registerAdapter). class UtilityRegistrationTests(_SilencePy3Deprecations): def _getTargetClass(self): from zope.interface.registry import UtilityRegistration return UtilityRegistration def _makeOne(self, component=None, factory=None): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') class _Registry(object): def __repr__(self): return '_REGISTRY' registry = _Registry() name = _u('name') doc = 'DOCSTRING' klass = self._getTargetClass() return (klass(registry, ifoo, name, component, doc, factory), registry, name, ) def test_class_conforms_to_IUtilityRegistration(self): from zope.interface.verify import verifyClass from zope.interface.interfaces import IUtilityRegistration verifyClass(IUtilityRegistration, self._getTargetClass()) def test_instance_conforms_to_IUtilityRegistration(self): from zope.interface.verify import verifyObject from zope.interface.interfaces import IUtilityRegistration ur, _, _ = self._makeOne() verifyObject(IUtilityRegistration, ur) def test___repr__(self): class _Component(object): __name__ = 'TEST' _component = _Component() ur, _registry, _name = self._makeOne(_component) self.assertEqual(repr(ur), "UtilityRegistration(_REGISTRY, IFoo, %r, TEST, None, 'DOCSTRING')" % (_name)) def test___repr___provided_wo_name(self): class _Component(object): def __repr__(self): return 'TEST' _component = _Component() ur, _registry, _name = self._makeOne(_component) ur.provided = object() self.assertEqual(repr(ur), "UtilityRegistration(_REGISTRY, None, %r, TEST, None, 'DOCSTRING')" % (_name)) def test___repr___component_wo_name(self): class _Component(object): def __repr__(self): return 'TEST' _component = _Component() ur, _registry, _name = self._makeOne(_component) ur.provided = object() self.assertEqual(repr(ur), "UtilityRegistration(_REGISTRY, None, %r, TEST, None, 'DOCSTRING')" % (_name)) def test___hash__(self): _component = object() ur, _registry, _name = self._makeOne(_component) self.assertEqual(ur.__hash__(), id(ur)) def test___eq___identity(self): _component = object() ur, _registry, _name = self._makeOne(_component) self.failUnless(ur == ur) def test___eq___hit(self): _component = object() ur, _registry, _name = self._makeOne(_component) ur2, _, _ = self._makeOne(_component) self.failUnless(ur == ur2) def test___eq___miss(self): _component = object() _component2 = object() ur, _registry, _name = self._makeOne(_component) ur2, _, _ = self._makeOne(_component2) self.failIf(ur == ur2) def test___ne___identity(self): _component = object() ur, _registry, _name = self._makeOne(_component) self.failIf(ur != ur) def test___ne___hit(self): _component = object() ur, _registry, _name = self._makeOne(_component) ur2, _, _ = self._makeOne(_component) self.failIf(ur != ur2) def test___ne___miss(self): _component = object() _component2 = object() ur, _registry, _name = self._makeOne(_component) ur2, _, _ = self._makeOne(_component2) self.failUnless(ur != ur2) def test___lt___identity(self): _component = object() ur, _registry, _name = self._makeOne(_component) self.failIf(ur < ur) def test___lt___hit(self): _component = object() ur, _registry, _name = self._makeOne(_component) ur2, _, _ = self._makeOne(_component) self.failIf(ur < ur2) def test___lt___miss(self): _component = object() _component2 = object() ur, _registry, _name = self._makeOne(_component) ur2, _, _ = self._makeOne(_component2) ur2.name = _name + '2' self.failUnless(ur < ur2) def test___le___identity(self): _component = object() ur, _registry, _name = self._makeOne(_component) self.failUnless(ur <= ur) def test___le___hit(self): _component = object() ur, _registry, _name = self._makeOne(_component) ur2, _, _ = self._makeOne(_component) self.failUnless(ur <= ur2) def test___le___miss(self): _component = object() _component2 = object() ur, _registry, _name = self._makeOne(_component) ur2, _, _ = self._makeOne(_component2) ur2.name = _name + '2' self.failUnless(ur <= ur2) def test___gt___identity(self): _component = object() ur, _registry, _name = self._makeOne(_component) self.failIf(ur > ur) def test___gt___hit(self): _component = object() _component2 = object() ur, _registry, _name = self._makeOne(_component) ur2, _, _ = self._makeOne(_component2) ur2.name = _name + '2' self.failUnless(ur2 > ur) def test___gt___miss(self): _component = object() ur, _registry, _name = self._makeOne(_component) ur2, _, _ = self._makeOne(_component) self.failIf(ur2 > ur) def test___ge___identity(self): _component = object() ur, _registry, _name = self._makeOne(_component) self.failUnless(ur >= ur) def test___ge___miss(self): _component = object() _component2 = object() ur, _registry, _name = self._makeOne(_component) ur2, _, _ = self._makeOne(_component2) ur2.name = _name + '2' self.failIf(ur >= ur2) def test___ge___hit(self): _component = object() ur, _registry, _name = self._makeOne(_component) ur2, _, _ = self._makeOne(_component) ur2.name = _name + '2' self.failUnless(ur2 >= ur) class AdapterRegistrationTests(_SilencePy3Deprecations): def _getTargetClass(self): from zope.interface.registry import AdapterRegistration return AdapterRegistration def _makeOne(self, component=None): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') class _Registry(object): def __repr__(self): return '_REGISTRY' registry = _Registry() name = _u('name') doc = 'DOCSTRING' klass = self._getTargetClass() return (klass(registry, (ibar,), ifoo, name, component, doc), registry, name, ) def test_class_conforms_to_IAdapterRegistration(self): from zope.interface.verify import verifyClass from zope.interface.interfaces import IAdapterRegistration verifyClass(IAdapterRegistration, self._getTargetClass()) def test_instance_conforms_to_IAdapterRegistration(self): from zope.interface.verify import verifyObject from zope.interface.interfaces import IAdapterRegistration ar, _, _ = self._makeOne() verifyObject(IAdapterRegistration, ar) def test___repr__(self): class _Component(object): __name__ = 'TEST' _component = _Component() ar, _registry, _name = self._makeOne(_component) self.assertEqual(repr(ar), ("AdapterRegistration(_REGISTRY, [IBar], IFoo, %r, TEST, " + "'DOCSTRING')") % (_name)) def test___repr___provided_wo_name(self): class _Component(object): def __repr__(self): return 'TEST' _component = _Component() ar, _registry, _name = self._makeOne(_component) ar.provided = object() self.assertEqual(repr(ar), ("AdapterRegistration(_REGISTRY, [IBar], None, %r, TEST, " + "'DOCSTRING')") % (_name)) def test___repr___component_wo_name(self): class _Component(object): def __repr__(self): return 'TEST' _component = _Component() ar, _registry, _name = self._makeOne(_component) ar.provided = object() self.assertEqual(repr(ar), ("AdapterRegistration(_REGISTRY, [IBar], None, %r, TEST, " + "'DOCSTRING')") % (_name)) def test___hash__(self): _component = object() ar, _registry, _name = self._makeOne(_component) self.assertEqual(ar.__hash__(), id(ar)) def test___eq___identity(self): _component = object() ar, _registry, _name = self._makeOne(_component) self.failUnless(ar == ar) def test___eq___hit(self): _component = object() ar, _registry, _name = self._makeOne(_component) ar2, _, _ = self._makeOne(_component) self.failUnless(ar == ar2) def test___eq___miss(self): _component = object() _component2 = object() ar, _registry, _name = self._makeOne(_component) ar2, _, _ = self._makeOne(_component2) self.failIf(ar == ar2) def test___ne___identity(self): _component = object() ar, _registry, _name = self._makeOne(_component) self.failIf(ar != ar) def test___ne___miss(self): _component = object() ar, _registry, _name = self._makeOne(_component) ar2, _, _ = self._makeOne(_component) self.failIf(ar != ar2) def test___ne___hit_component(self): _component = object() _component2 = object() ar, _registry, _name = self._makeOne(_component) ar2, _, _ = self._makeOne(_component2) self.failUnless(ar != ar2) def test___ne___hit_provided(self): from zope.interface.declarations import InterfaceClass class IFoo(InterfaceClass): pass ibaz = IFoo('IBaz') _component = object() ar, _registry, _name = self._makeOne(_component) ar2, _, _ = self._makeOne(_component) ar2.provided = ibaz self.failUnless(ar != ar2) def test___ne___hit_required(self): from zope.interface.declarations import InterfaceClass class IFoo(InterfaceClass): pass ibaz = IFoo('IBaz') _component = object() _component2 = object() ar, _registry, _name = self._makeOne(_component) ar2, _, _ = self._makeOne(_component2) ar2.required = (ibaz,) self.failUnless(ar != ar2) def test___lt___identity(self): _component = object() ar, _registry, _name = self._makeOne(_component) self.failIf(ar < ar) def test___lt___hit(self): _component = object() ar, _registry, _name = self._makeOne(_component) ar2, _, _ = self._makeOne(_component) self.failIf(ar < ar2) def test___lt___miss(self): _component = object() _component2 = object() ar, _registry, _name = self._makeOne(_component) ar2, _, _ = self._makeOne(_component2) ar2.name = _name + '2' self.failUnless(ar < ar2) def test___le___identity(self): _component = object() ar, _registry, _name = self._makeOne(_component) self.failUnless(ar <= ar) def test___le___hit(self): _component = object() ar, _registry, _name = self._makeOne(_component) ar2, _, _ = self._makeOne(_component) self.failUnless(ar <= ar2) def test___le___miss(self): _component = object() _component2 = object() ar, _registry, _name = self._makeOne(_component) ar2, _, _ = self._makeOne(_component2) ar2.name = _name + '2' self.failUnless(ar <= ar2) def test___gt___identity(self): _component = object() ar, _registry, _name = self._makeOne(_component) self.failIf(ar > ar) def test___gt___hit(self): _component = object() _component2 = object() ar, _registry, _name = self._makeOne(_component) ar2, _, _ = self._makeOne(_component2) ar2.name = _name + '2' self.failUnless(ar2 > ar) def test___gt___miss(self): _component = object() ar, _registry, _name = self._makeOne(_component) ar2, _, _ = self._makeOne(_component) self.failIf(ar2 > ar) def test___ge___identity(self): _component = object() ar, _registry, _name = self._makeOne(_component) self.failUnless(ar >= ar) def test___ge___miss(self): _component = object() _component2 = object() ar, _registry, _name = self._makeOne(_component) ar2, _, _ = self._makeOne(_component2) ar2.name = _name + '2' self.failIf(ar >= ar2) def test___ge___hit(self): _component = object() ar, _registry, _name = self._makeOne(_component) ar2, _, _ = self._makeOne(_component) ar2.name = _name + '2' self.failUnless(ar2 >= ar) class SubscriptionRegistrationTests(unittest.TestCase): def _getTargetClass(self): from zope.interface.registry import SubscriptionRegistration return SubscriptionRegistration def _makeOne(self, component=None): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') class _Registry(object): def __repr__(self): return '_REGISTRY' registry = _Registry() name = _u('name') doc = 'DOCSTRING' klass = self._getTargetClass() return (klass(registry, (ibar,), ifoo, name, component, doc), registry, name, ) def test_class_conforms_to_ISubscriptionAdapterRegistration(self): from zope.interface.verify import verifyClass from zope.interface.interfaces import ISubscriptionAdapterRegistration verifyClass(ISubscriptionAdapterRegistration, self._getTargetClass()) def test_instance_conforms_to_ISubscriptionAdapterRegistration(self): from zope.interface.verify import verifyObject from zope.interface.interfaces import ISubscriptionAdapterRegistration sar, _, _ = self._makeOne() verifyObject(ISubscriptionAdapterRegistration, sar) class HandlerRegistrationTests(_SilencePy3Deprecations): def _getTargetClass(self): from zope.interface.registry import HandlerRegistration return HandlerRegistration def _makeOne(self, component=None): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') class _Registry(object): def __repr__(self): return '_REGISTRY' registry = _Registry() name = _u('name') doc = 'DOCSTRING' klass = self._getTargetClass() return (klass(registry, (ifoo,), name, component, doc), registry, name, ) def test_class_conforms_to_IHandlerRegistration(self): from zope.interface.verify import verifyClass from zope.interface.interfaces import IHandlerRegistration verifyClass(IHandlerRegistration, self._getTargetClass()) def test_instance_conforms_to_IHandlerRegistration(self): from zope.interface.verify import verifyObject from zope.interface.interfaces import IHandlerRegistration hr, _, _ = self._makeOne() verifyObject(IHandlerRegistration, hr) def test_properties(self): def _factory(context): pass hr, _, _ = self._makeOne(_factory) self.failUnless(hr.handler is _factory) self.failUnless(hr.factory is hr.handler) self.failUnless(hr.provided is None) def test___repr___factory_w_name(self): class _Factory(object): __name__ = 'TEST' hr, _registry, _name = self._makeOne(_Factory()) self.assertEqual(repr(hr), ("HandlerRegistration(_REGISTRY, [IFoo], %r, TEST, " + "'DOCSTRING')") % (_name)) def test___repr___factory_wo_name(self): class _Factory(object): def __repr__(self): return 'TEST' hr, _registry, _name = self._makeOne(_Factory()) self.assertEqual(repr(hr), ("HandlerRegistration(_REGISTRY, [IFoo], %r, TEST, " + "'DOCSTRING')") % (_name)) class _Monkey(object): # context-manager for replacing module names in the scope of a test. def __init__(self, module, **kw): self.module = module self.to_restore = dict([(key, getattr(module, key)) for key in kw]) for key, value in kw.items(): setattr(module, key, value) def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): for key, value in self.to_restore.items(): setattr(self.module, key, value) def test_suite(): return unittest.TestSuite(( unittest.makeSuite(ComponentsTests), unittest.makeSuite(UtilityRegistrationTests), unittest.makeSuite(AdapterRegistrationTests), unittest.makeSuite(SubscriptionRegistrationTests), unittest.makeSuite(AdapterRegistrationTests), ))
39.464766
80
0.630783
e.interface.declarations import directlyProvides from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Registered from zope.interface.registry import UtilityRegistration from zope.interface._compat import _u class IFoo(InterfaceClass): pass class Foo(object): pass ifoo = IFoo('IFoo') _info = _u('info') _name = _u('name') _to_reg = Foo() directlyProvides(_to_reg, ifoo) comp = self._makeOne() _monkey, _events = self._wrapEvents() with _monkey: comp.registerUtility(_to_reg, None, _name, _info) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Registered)) self.failUnless(isinstance(event.object, UtilityRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.failUnless(event.object.name is _name) self.failUnless(event.object.component is _to_reg) self.failUnless(event.object.info is _info) self.failUnless(event.object.factory is None) def test_registerUtility_duplicates_existing_reg(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _info = _u('info') _name = _u('name') _to_reg = object() comp = self._makeOne() comp.registerUtility(_to_reg, ifoo, _name, _info) _monkey, _events = self._wrapEvents() with _monkey: comp.registerUtility(_to_reg, ifoo, _name, _info) self.assertEqual(len(_events), 0) def test_registerUtility_replaces_existing_reg(self): from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Unregistered from zope.interface.interfaces import Registered from zope.interface.registry import UtilityRegistration from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _info = _u('info') _name = _u('name') _before, _after = object(), object() comp = self._makeOne() comp.registerUtility(_before, ifoo, _name, _info) _monkey, _events = self._wrapEvents() with _monkey: comp.registerUtility(_after, ifoo, _name, _info) self.assertEqual(len(_events), 2) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Unregistered)) self.failUnless(isinstance(event.object, UtilityRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.failUnless(event.object.name is _name) self.failUnless(event.object.component is _before) self.failUnless(event.object.info is _info) self.failUnless(event.object.factory is None) args, kw = _events[1] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Registered)) self.failUnless(isinstance(event.object, UtilityRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.failUnless(event.object.name is _name) self.failUnless(event.object.component is _after) self.failUnless(event.object.info is _info) self.failUnless(event.object.factory is None) def test_registerUtility_w_existing_subscr(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _info = _u('info') _name1 = _u('name1') _name2 = _u('name2') _to_reg = object() comp = self._makeOne() comp.registerUtility(_to_reg, ifoo, _name1, _info) _monkey, _events = self._wrapEvents() with _monkey: comp.registerUtility(_to_reg, ifoo, _name2, _info) self.assertEqual(comp.utilities._subscribers[0][ifoo][''], (_to_reg,)) def test_registerUtility_wo_event(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _info = _u('info') _name = _u('name') _to_reg = object() comp = self._makeOne() _monkey, _events = self._wrapEvents() with _monkey: comp.registerUtility(_to_reg, ifoo, _name, _info, False) self.assertEqual(len(_events), 0) def test_unregisterUtility_neither_factory_nor_component_nor_provided(self): comp = self._makeOne() self.assertRaises(TypeError, comp.unregisterUtility, component=None, provided=None, factory=None) def test_unregisterUtility_both_factory_and_component(self): def _factory(): pass _to_reg = object() comp = self._makeOne() self.assertRaises(TypeError, comp.unregisterUtility, component=_to_reg, factory=_factory) def test_unregisterUtility_w_component_miss(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _name = _u('name') _to_reg = object() comp = self._makeOne() _monkey, _events = self._wrapEvents() with _monkey: unreg = comp.unregisterUtility(_to_reg, ifoo, _name) self.failIf(unreg) self.failIf(_events) def test_unregisterUtility_w_component(self): from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Unregistered from zope.interface.registry import UtilityRegistration from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _name = _u('name') _to_reg = object() comp = self._makeOne() comp.registerUtility(_to_reg, ifoo, _name) _monkey, _events = self._wrapEvents() with _monkey: unreg = comp.unregisterUtility(_to_reg, ifoo, _name) self.failUnless(unreg) self.failIf(comp.utilities._adapters) self.failIf((ifoo, _name) in comp._utility_registrations) self.failIf(comp.utilities._subscribers) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Unregistered)) self.failUnless(isinstance(event.object, UtilityRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.failUnless(event.object.name is _name) self.failUnless(event.object.component is _to_reg) self.failUnless(event.object.factory is None) def test_unregisterUtility_w_factory(self): from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Unregistered from zope.interface.registry import UtilityRegistration from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _info = _u('info') _name = _u('name') _to_reg = object() def _factory(): return _to_reg comp = self._makeOne() comp.registerUtility(None, ifoo, _name, _info, factory=_factory) _monkey, _events = self._wrapEvents() with _monkey: unreg = comp.unregisterUtility(None, ifoo, _name, factory=_factory) self.failUnless(unreg) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Unregistered)) self.failUnless(isinstance(event.object, UtilityRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.failUnless(event.object.name is _name) self.failUnless(event.object.component is _to_reg) self.failUnless(event.object.factory is _factory) def test_unregisterUtility_wo_explicit_provided(self): from zope.interface.declarations import directlyProvides from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Unregistered from zope.interface.registry import UtilityRegistration from zope.interface._compat import _u class IFoo(InterfaceClass): pass class Foo(object): pass ifoo = IFoo('IFoo') _info = _u('info') _name = _u('name') _to_reg = Foo() directlyProvides(_to_reg, ifoo) comp = self._makeOne() comp.registerUtility(_to_reg, ifoo, _name, _info) _monkey, _events = self._wrapEvents() with _monkey: unreg = comp.unregisterUtility(_to_reg, None, _name) self.failUnless(unreg) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Unregistered)) self.failUnless(isinstance(event.object, UtilityRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.failUnless(event.object.name is _name) self.failUnless(event.object.component is _to_reg) self.failUnless(event.object.info is _info) self.failUnless(event.object.factory is None) def test_unregisterUtility_wo_component_or_factory(self): from zope.interface.declarations import directlyProvides from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Unregistered from zope.interface.registry import UtilityRegistration from zope.interface._compat import _u class IFoo(InterfaceClass): pass class Foo(object): pass ifoo = IFoo('IFoo') _info = _u('info') _name = _u('name') _to_reg = Foo() directlyProvides(_to_reg, ifoo) comp = self._makeOne() comp.registerUtility(_to_reg, ifoo, _name, _info) _monkey, _events = self._wrapEvents() with _monkey: unreg = comp.unregisterUtility(provided=ifoo, name=_name) self.failUnless(unreg) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Unregistered)) self.failUnless(isinstance(event.object, UtilityRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.failUnless(event.object.name is _name) self.failUnless(event.object.component is _to_reg) self.failUnless(event.object.info is _info) self.failUnless(event.object.factory is None) def test_unregisterUtility_w_existing_subscr(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _info = _u('info') _name1 = _u('name1') _name2 = _u('name2') _to_reg = object() comp = self._makeOne() comp.registerUtility(_to_reg, ifoo, _name1, _info) comp.registerUtility(_to_reg, ifoo, _name2, _info) _monkey, _events = self._wrapEvents() with _monkey: comp.unregisterUtility(_to_reg, ifoo, _name2) self.assertEqual(comp.utilities._subscribers[0][ifoo][''], (_to_reg,)) def test_registeredUtilities_empty(self): comp = self._makeOne() self.assertEqual(list(comp.registeredUtilities()), []) def test_registeredUtilities_notempty(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u from zope.interface.registry import UtilityRegistration class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _info = _u('info') _name1 = _u('name1') _name2 = _u('name2') _to_reg = object() comp = self._makeOne() comp.registerUtility(_to_reg, ifoo, _name1, _info) comp.registerUtility(_to_reg, ifoo, _name2, _info) reg = sorted(comp.registeredUtilities(), key=lambda r: r.name) self.assertEqual(len(reg), 2) self.failUnless(isinstance(reg[0], UtilityRegistration)) self.failUnless(reg[0].registry is comp) self.failUnless(reg[0].provided is ifoo) self.failUnless(reg[0].name is _name1) self.failUnless(reg[0].component is _to_reg) self.failUnless(reg[0].info is _info) self.failUnless(reg[0].factory is None) self.failUnless(isinstance(reg[1], UtilityRegistration)) self.failUnless(reg[1].registry is comp) self.failUnless(reg[1].provided is ifoo) self.failUnless(reg[1].name is _name2) self.failUnless(reg[1].component is _to_reg) self.failUnless(reg[1].info is _info) self.failUnless(reg[1].factory is None) def test_queryUtility_miss_no_default(self): from zope.interface.declarations import InterfaceClass class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') comp = self._makeOne() self.failUnless(comp.queryUtility(ifoo) is None) def test_queryUtility_miss_w_default(self): from zope.interface.declarations import InterfaceClass class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') comp = self._makeOne() _default = object() self.failUnless(comp.queryUtility(ifoo, default=_default) is _default) def test_queryUtility_hit(self): from zope.interface.declarations import InterfaceClass class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _to_reg = object() comp = self._makeOne() comp.registerUtility(_to_reg, ifoo) self.failUnless(comp.queryUtility(ifoo) is _to_reg) def test_getUtility_miss(self): from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import ComponentLookupError class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') comp = self._makeOne() self.assertRaises(ComponentLookupError, comp.getUtility, ifoo) def test_getUtility_hit(self): from zope.interface.declarations import InterfaceClass class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _to_reg = object() comp = self._makeOne() comp.registerUtility(_to_reg, ifoo) self.failUnless(comp.getUtility(ifoo) is _to_reg) def test_getUtilitiesFor_miss(self): from zope.interface.declarations import InterfaceClass class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') comp = self._makeOne() self.assertEqual(list(comp.getUtilitiesFor(ifoo)), []) def test_getUtilitiesFor_hit(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _name1 = _u('name1') _name2 = _u('name2') _to_reg = object() comp = self._makeOne() comp.registerUtility(_to_reg, ifoo, name=_name1) comp.registerUtility(_to_reg, ifoo, name=_name2) self.assertEqual(sorted(comp.getUtilitiesFor(ifoo)), [(_name1, _to_reg), (_name2, _to_reg)]) def test_getAllUtilitiesRegisteredFor_miss(self): from zope.interface.declarations import InterfaceClass class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') comp = self._makeOne() self.assertEqual(list(comp.getAllUtilitiesRegisteredFor(ifoo)), []) def test_getAllUtilitiesRegisteredFor_hit(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _name1 = _u('name1') _name2 = _u('name2') _to_reg = object() comp = self._makeOne() comp.registerUtility(_to_reg, ifoo, name=_name1) comp.registerUtility(_to_reg, ifoo, name=_name2) self.assertEqual(list(comp.getAllUtilitiesRegisteredFor(ifoo)), [_to_reg]) def test_registerAdapter_w_explicit_provided_and_required(self): from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Registered from zope.interface.registry import AdapterRegistration from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') _info = _u('info') _name = _u('name') _to_reg = object() def _factory(context): return _to_reg comp = self._makeOne() _monkey, _events = self._wrapEvents() with _monkey: comp.registerAdapter(_factory, (ibar,), ifoo, _name, _info) self.failUnless(comp.adapters._adapters[1][ibar][ifoo][_name] is _factory) self.assertEqual(comp._adapter_registrations[(ibar,), ifoo, _name], (_factory, _info)) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Registered)) self.failUnless(isinstance(event.object, AdapterRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.assertEqual(event.object.required, (ibar,)) self.failUnless(event.object.name is _name) self.failUnless(event.object.info is _info) self.failUnless(event.object.factory is _factory) def test_registerAdapter_no_provided_available(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') _info = _u('info') _name = _u('name') _to_reg = object() class _Factory(object): def __init__(self, context): self._context = context comp = self._makeOne() self.assertRaises(TypeError, comp.registerAdapter, _Factory, (ibar,), name=_name, info=_info) def test_registerAdapter_wo_explicit_provided(self): from zope.interface.declarations import InterfaceClass from zope.interface.declarations import implementer from zope.interface.interfaces import Registered from zope.interface.registry import AdapterRegistration from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') _info = _u('info') _name = _u('name') _to_reg = object() @implementer(ifoo) class _Factory(object): def __init__(self, context): self._context = context comp = self._makeOne() _monkey, _events = self._wrapEvents() with _monkey: comp.registerAdapter(_Factory, (ibar,), name=_name, info=_info) self.failUnless(comp.adapters._adapters[1][ibar][ifoo][_name] is _Factory) self.assertEqual(comp._adapter_registrations[(ibar,), ifoo, _name], (_Factory, _info)) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Registered)) self.failUnless(isinstance(event.object, AdapterRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.assertEqual(event.object.required, (ibar,)) self.failUnless(event.object.name is _name) self.failUnless(event.object.info is _info) self.failUnless(event.object.factory is _Factory) def test_registerAdapter_no_required_available(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') _info = _u('info') _name = _u('name') class _Factory(object): def __init__(self, context): self._context = context comp = self._makeOne() self.assertRaises(TypeError, comp.registerAdapter, _Factory, provided=ifoo, name=_name, info=_info) def test_registerAdapter_w_invalid_required(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') _info = _u('info') _name = _u('name') class _Factory(object): def __init__(self, context): self._context = context comp = self._makeOne() self.assertRaises(TypeError, comp.registerAdapter, _Factory, ibar, provided=ifoo, name=_name, info=_info) def test_registerAdapter_w_required_containing_None(self): from zope.interface.declarations import InterfaceClass from zope.interface.interface import Interface from zope.interface.interfaces import Registered from zope.interface.registry import AdapterRegistration from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _info = _u('info') _name = _u('name') class _Factory(object): def __init__(self, context): self._context = context comp = self._makeOne() _monkey, _events = self._wrapEvents() with _monkey: comp.registerAdapter(_Factory, [None], provided=ifoo, name=_name, info=_info) self.failUnless(comp.adapters._adapters[1][Interface][ifoo][_name] is _Factory) self.assertEqual(comp._adapter_registrations[(Interface,), ifoo, _name], (_Factory, _info)) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Registered)) self.failUnless(isinstance(event.object, AdapterRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.assertEqual(event.object.required, (Interface,)) self.failUnless(event.object.name is _name) self.failUnless(event.object.info is _info) self.failUnless(event.object.factory is _Factory) def test_registerAdapter_w_required_containing_class(self): from zope.interface.declarations import InterfaceClass from zope.interface.declarations import implementer from zope.interface.declarations import implementedBy from zope.interface.interfaces import Registered from zope.interface.registry import AdapterRegistration from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') _info = _u('info') _name = _u('name') class _Factory(object): def __init__(self, context): self._context = context @implementer(ibar) class _Context(object): pass _ctx_impl = implementedBy(_Context) comp = self._makeOne() _monkey, _events = self._wrapEvents() with _monkey: comp.registerAdapter(_Factory, [_Context], provided=ifoo, name=_name, info=_info) self.failUnless(comp.adapters._adapters[1][_ctx_impl][ifoo][_name] is _Factory) self.assertEqual(comp._adapter_registrations[(_ctx_impl,), ifoo, _name], (_Factory, _info)) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Registered)) self.failUnless(isinstance(event.object, AdapterRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.assertEqual(event.object.required, (_ctx_impl,)) self.failUnless(event.object.name is _name) self.failUnless(event.object.info is _info) self.failUnless(event.object.factory is _Factory) def test_registerAdapter_w_required_containing_junk(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') _info = _u('info') _name = _u('name') class _Factory(object): def __init__(self, context): self._context = context comp = self._makeOne() self.assertRaises(TypeError, comp.registerAdapter, _Factory, [object()], provided=ifoo, name=_name, info=_info) def test_registerAdapter_wo_explicit_required(self): from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Registered from zope.interface.registry import AdapterRegistration from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') _info = _u('info') _name = _u('name') class _Factory(object): __component_adapts__ = (ibar,) def __init__(self, context): self._context = context comp = self._makeOne() _monkey, _events = self._wrapEvents() with _monkey: comp.registerAdapter(_Factory, provided=ifoo, name=_name, info=_info) self.failUnless(comp.adapters._adapters[1][ibar][ifoo][_name] is _Factory) self.assertEqual(comp._adapter_registrations[(ibar,), ifoo, _name], (_Factory, _info)) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Registered)) self.failUnless(isinstance(event.object, AdapterRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.assertEqual(event.object.required, (ibar,)) self.failUnless(event.object.name is _name) self.failUnless(event.object.info is _info) self.failUnless(event.object.factory is _Factory) def test_registerAdapter_wo_event(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') _info = _u('info') _name = _u('name') _to_reg = object() def _factory(context): return _to_reg comp = self._makeOne() _monkey, _events = self._wrapEvents() with _monkey: comp.registerAdapter(_factory, (ibar,), ifoo, _name, _info, event=False) self.assertEqual(len(_events), 0) def test_unregisterAdapter_neither_factory_nor_provided(self): comp = self._makeOne() self.assertRaises(TypeError, comp.unregisterAdapter, factory=None, provided=None) def test_unregisterAdapter_neither_factory_nor_required(self): from zope.interface.declarations import InterfaceClass class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') comp = self._makeOne() self.assertRaises(TypeError, comp.unregisterAdapter, factory=None, provided=ifoo, required=None) def test_unregisterAdapter_miss(self): from zope.interface.declarations import InterfaceClass class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') class _Factory(object): def __init__(self, context): self._context = context comp = self._makeOne() _monkey, _events = self._wrapEvents() with _monkey: unreg = comp.unregisterAdapter(_Factory, (ibar,), ifoo) self.failIf(unreg) def test_unregisterAdapter_hit_w_explicit_provided_and_required(self): from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Unregistered from zope.interface.registry import AdapterRegistration class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') class _Factory(object): def __init__(self, context): self._context = context comp = self._makeOne() comp.registerAdapter(_Factory, (ibar,), ifoo) _monkey, _events = self._wrapEvents() with _monkey: unreg = comp.unregisterAdapter(_Factory, (ibar,), ifoo) self.failUnless(unreg) self.failIf(comp.adapters._adapters) self.failIf(comp._adapter_registrations) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Unregistered)) self.failUnless(isinstance(event.object, AdapterRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.assertEqual(event.object.required, (ibar,)) self.assertEqual(event.object.name, '') self.assertEqual(event.object.info, '') self.failUnless(event.object.factory is _Factory) def test_unregisterAdapter_wo_explicit_provided(self): from zope.interface.declarations import InterfaceClass from zope.interface.declarations import implementer from zope.interface.interfaces import Unregistered from zope.interface.registry import AdapterRegistration class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') @implementer(ifoo) class _Factory(object): def __init__(self, context): self._context = context comp = self._makeOne() comp.registerAdapter(_Factory, (ibar,), ifoo) _monkey, _events = self._wrapEvents() with _monkey: unreg = comp.unregisterAdapter(_Factory, (ibar,)) self.failUnless(unreg) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Unregistered)) self.failUnless(isinstance(event.object, AdapterRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.assertEqual(event.object.required, (ibar,)) self.assertEqual(event.object.name, '') self.assertEqual(event.object.info, '') self.failUnless(event.object.factory is _Factory) def test_unregisterAdapter_wo_explicit_required(self): from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Unregistered from zope.interface.registry import AdapterRegistration class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') class _Factory(object): __component_adapts__ = (ibar,) def __init__(self, context): self._context = context comp = self._makeOne() comp.registerAdapter(_Factory, (ibar,), ifoo) _monkey, _events = self._wrapEvents() with _monkey: unreg = comp.unregisterAdapter(_Factory, provided=ifoo) self.failUnless(unreg) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Unregistered)) self.failUnless(isinstance(event.object, AdapterRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.assertEqual(event.object.required, (ibar,)) self.assertEqual(event.object.name, '') self.assertEqual(event.object.info, '') self.failUnless(event.object.factory is _Factory) def test_registeredAdapters_empty(self): comp = self._makeOne() self.assertEqual(list(comp.registeredAdapters()), []) def test_registeredAdapters_notempty(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u from zope.interface.registry import AdapterRegistration class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IFoo') _info = _u('info') _name1 = _u('name1') _name2 = _u('name2') class _Factory(object): def __init__(self, context): pass comp = self._makeOne() comp.registerAdapter(_Factory, (ibar,), ifoo, _name1, _info) comp.registerAdapter(_Factory, (ibar,), ifoo, _name2, _info) reg = sorted(comp.registeredAdapters(), key=lambda r: r.name) self.assertEqual(len(reg), 2) self.failUnless(isinstance(reg[0], AdapterRegistration)) self.failUnless(reg[0].registry is comp) self.failUnless(reg[0].provided is ifoo) self.assertEqual(reg[0].required, (ibar,)) self.failUnless(reg[0].name is _name1) self.failUnless(reg[0].info is _info) self.failUnless(reg[0].factory is _Factory) self.failUnless(isinstance(reg[1], AdapterRegistration)) self.failUnless(reg[1].registry is comp) self.failUnless(reg[1].provided is ifoo) self.assertEqual(reg[1].required, (ibar,)) self.failUnless(reg[1].name is _name2) self.failUnless(reg[1].info is _info) self.failUnless(reg[1].factory is _Factory) def test_queryAdapter_miss_no_default(self): from zope.interface.declarations import InterfaceClass class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') comp = self._makeOne() _context = object() self.failUnless(comp.queryAdapter(_context, ifoo) is None) def test_queryAdapter_miss_w_default(self): from zope.interface.declarations import InterfaceClass class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') comp = self._makeOne() _context = object() _default = object() self.failUnless( comp.queryAdapter(_context, ifoo, default=_default) is _default) def test_queryAdapter_hit(self): from zope.interface.declarations import InterfaceClass from zope.interface.declarations import implementer class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') class _Factory(object): def __init__(self, context): self.context = context @implementer(ibar) class _Context(object): pass _context = _Context() comp = self._makeOne() comp.registerAdapter(_Factory, (ibar,), ifoo) adapter = comp.queryAdapter(_context, ifoo) self.failUnless(isinstance(adapter, _Factory)) self.failUnless(adapter.context is _context) def test_getAdapter_miss(self): from zope.interface.declarations import InterfaceClass from zope.interface.declarations import implementer from zope.interface.interfaces import ComponentLookupError class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') @implementer(ibar) class _Context(object): pass _context = _Context() comp = self._makeOne() self.assertRaises(ComponentLookupError, comp.getAdapter, _context, ifoo) def test_getAdapter_hit(self): from zope.interface.declarations import InterfaceClass from zope.interface.declarations import implementer class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') class _Factory(object): def __init__(self, context): self.context = context @implementer(ibar) class _Context(object): pass _context = _Context() comp = self._makeOne() comp.registerAdapter(_Factory, (ibar,), ifoo) adapter = comp.getAdapter(_context, ifoo) self.failUnless(isinstance(adapter, _Factory)) self.failUnless(adapter.context is _context) def test_queryMultiAdapter_miss(self): from zope.interface.declarations import InterfaceClass from zope.interface.declarations import implementer class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') ibaz = IFoo('IBaz') @implementer(ibar) class _Context1(object): pass @implementer(ibaz) class _Context2(object): pass _context1 = _Context1() _context2 = _Context2() comp = self._makeOne() self.assertEqual(comp.queryMultiAdapter((_context1, _context2), ifoo), None) def test_queryMultiAdapter_miss_w_default(self): from zope.interface.declarations import InterfaceClass from zope.interface.declarations import implementer class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') ibaz = IFoo('IBaz') @implementer(ibar) class _Context1(object): pass @implementer(ibaz) class _Context2(object): pass _context1 = _Context1() _context2 = _Context2() _default = object() comp = self._makeOne() self.failUnless( comp.queryMultiAdapter((_context1, _context2), ifoo, default=_default) is _default) def test_queryMultiAdapter_hit(self): from zope.interface.declarations import InterfaceClass from zope.interface.declarations import implementer class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') ibaz = IFoo('IBaz') @implementer(ibar) class _Context1(object): pass @implementer(ibaz) class _Context2(object): pass _context1 = _Context1() _context2 = _Context2() class _Factory(object): def __init__(self, context1, context2): self.context = context1, context2 comp = self._makeOne() comp.registerAdapter(_Factory, (ibar, ibaz), ifoo) adapter = comp.queryMultiAdapter((_context1, _context2), ifoo) self.failUnless(isinstance(adapter, _Factory)) self.assertEqual(adapter.context, (_context1, _context2)) def test_getMultiAdapter_miss(self): from zope.interface.declarations import InterfaceClass from zope.interface.declarations import implementer from zope.interface.interfaces import ComponentLookupError class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') ibaz = IFoo('IBaz') @implementer(ibar) class _Context1(object): pass @implementer(ibaz) class _Context2(object): pass _context1 = _Context1() _context2 = _Context2() comp = self._makeOne() self.assertRaises(ComponentLookupError, comp.getMultiAdapter, (_context1, _context2), ifoo) def test_getMultiAdapter_hit(self): from zope.interface.declarations import InterfaceClass from zope.interface.declarations import implementer class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') ibaz = IFoo('IBaz') @implementer(ibar) class _Context1(object): pass @implementer(ibaz) class _Context2(object): pass _context1 = _Context1() _context2 = _Context2() class _Factory(object): def __init__(self, context1, context2): self.context = context1, context2 comp = self._makeOne() comp.registerAdapter(_Factory, (ibar, ibaz), ifoo) adapter = comp.getMultiAdapter((_context1, _context2), ifoo) self.failUnless(isinstance(adapter, _Factory)) self.assertEqual(adapter.context, (_context1, _context2)) def test_getAdapters_empty(self): from zope.interface.declarations import InterfaceClass from zope.interface.declarations import implementer class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') ibaz = IFoo('IBaz') @implementer(ibar) class _Context1(object): pass @implementer(ibaz) class _Context2(object): pass _context1 = _Context1() _context2 = _Context2() comp = self._makeOne() self.assertEqual( list(comp.getAdapters((_context1, _context2), ifoo)), []) def test_getAdapters_non_empty(self): from zope.interface.declarations import InterfaceClass from zope.interface.declarations import implementer from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') ibaz = IFoo('IBaz') @implementer(ibar) class _Context1(object): pass @implementer(ibaz) class _Context2(object): pass _context1 = _Context1() _context2 = _Context2() class _Factory1(object): def __init__(self, context1, context2): self.context = context1, context2 class _Factory2(object): def __init__(self, context1, context2): self.context = context1, context2 _name1 = _u('name1') _name2 = _u('name2') comp = self._makeOne() comp.registerAdapter(_Factory1, (ibar, ibaz), ifoo, name=_name1) comp.registerAdapter(_Factory2, (ibar, ibaz), ifoo, name=_name2) found = sorted(comp.getAdapters((_context1, _context2), ifoo)) self.assertEqual(len(found), 2) self.assertEqual(found[0][0], _name1) self.failUnless(isinstance(found[0][1], _Factory1)) self.assertEqual(found[1][0], _name2) self.failUnless(isinstance(found[1][1], _Factory2)) def test_registerSubscriptionAdapter_w_nonblank_name(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') _name = _u('name') _info = _u('info') _to_reg = object() def _factory(context): return _to_reg comp = self._makeOne() self.assertRaises(TypeError, comp.registerSubscriptionAdapter, _factory, (ibar,), ifoo, _name, _info) def test_registerSubscriptionAdapter_w_explicit_provided_and_required(self): from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Registered from zope.interface.registry import SubscriptionRegistration from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') _blank = _u('') _info = _u('info') _to_reg = object() def _factory(context): return _to_reg comp = self._makeOne() _monkey, _events = self._wrapEvents() with _monkey: comp.registerSubscriptionAdapter(_factory, (ibar,), ifoo, info=_info) reg = comp.adapters._subscribers[1][ibar][ifoo][_blank] self.assertEqual(len(reg), 1) self.failUnless(reg[0] is _factory) self.assertEqual(comp._subscription_registrations, [((ibar,), ifoo, _blank, _factory, _info)]) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Registered)) self.failUnless(isinstance(event.object, SubscriptionRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.assertEqual(event.object.required, (ibar,)) self.assertEqual(event.object.name, _blank) self.failUnless(event.object.info is _info) self.failUnless(event.object.factory is _factory) def test_registerSubscriptionAdapter_wo_explicit_provided(self): from zope.interface.declarations import InterfaceClass from zope.interface.declarations import implementer from zope.interface.interfaces import Registered from zope.interface.registry import SubscriptionRegistration from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') _info = _u('info') _blank = _u('') _to_reg = object() @implementer(ifoo) class _Factory(object): def __init__(self, context): self._context = context comp = self._makeOne() _monkey, _events = self._wrapEvents() with _monkey: comp.registerSubscriptionAdapter(_Factory, (ibar,), info=_info) reg = comp.adapters._subscribers[1][ibar][ifoo][_blank] self.assertEqual(len(reg), 1) self.failUnless(reg[0] is _Factory) self.assertEqual(comp._subscription_registrations, [((ibar,), ifoo, _blank, _Factory, _info)]) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Registered)) self.failUnless(isinstance(event.object, SubscriptionRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.assertEqual(event.object.required, (ibar,)) self.assertEqual(event.object.name, _blank) self.failUnless(event.object.info is _info) self.failUnless(event.object.factory is _Factory) def test_registerSubscriptionAdapter_wo_explicit_required(self): from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Registered from zope.interface.registry import SubscriptionRegistration from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') _info = _u('info') _blank = _u('') class _Factory(object): __component_adapts__ = (ibar,) def __init__(self, context): self._context = context comp = self._makeOne() _monkey, _events = self._wrapEvents() with _monkey: comp.registerSubscriptionAdapter( _Factory, provided=ifoo, info=_info) reg = comp.adapters._subscribers[1][ibar][ifoo][_blank] self.assertEqual(len(reg), 1) self.failUnless(reg[0] is _Factory) self.assertEqual(comp._subscription_registrations, [((ibar,), ifoo, _blank, _Factory, _info)]) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Registered)) self.failUnless(isinstance(event.object, SubscriptionRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.assertEqual(event.object.required, (ibar,)) self.assertEqual(event.object.name, _blank) self.failUnless(event.object.info is _info) self.failUnless(event.object.factory is _Factory) def test_registerSubscriptionAdapter_wo_event(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') _blank = _u('') _info = _u('info') _to_reg = object() def _factory(context): return _to_reg comp = self._makeOne() _monkey, _events = self._wrapEvents() with _monkey: comp.registerSubscriptionAdapter(_factory, (ibar,), ifoo, info=_info, event=False) self.assertEqual(len(_events), 0) def test_registeredSubscriptionAdapters_empty(self): comp = self._makeOne() self.assertEqual(list(comp.registeredSubscriptionAdapters()), []) def test_registeredSubscriptionAdapters_notempty(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u from zope.interface.registry import SubscriptionRegistration class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IFoo') _info = _u('info') _blank = _u('') class _Factory(object): def __init__(self, context): pass comp = self._makeOne() comp.registerSubscriptionAdapter(_Factory, (ibar,), ifoo, info=_info) comp.registerSubscriptionAdapter(_Factory, (ibar,), ifoo, info=_info) reg = list(comp.registeredSubscriptionAdapters()) self.assertEqual(len(reg), 2) self.failUnless(isinstance(reg[0], SubscriptionRegistration)) self.failUnless(reg[0].registry is comp) self.failUnless(reg[0].provided is ifoo) self.assertEqual(reg[0].required, (ibar,)) self.assertEqual(reg[0].name, _blank) self.failUnless(reg[0].info is _info) self.failUnless(reg[0].factory is _Factory) self.failUnless(isinstance(reg[1], SubscriptionRegistration)) self.failUnless(reg[1].registry is comp) self.failUnless(reg[1].provided is ifoo) self.assertEqual(reg[1].required, (ibar,)) self.assertEqual(reg[1].name, _blank) self.failUnless(reg[1].info is _info) self.failUnless(reg[1].factory is _Factory) def test_unregisterSubscriptionAdapter_w_nonblank_name(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') _nonblank = _u('nonblank') comp = self._makeOne() self.assertRaises(TypeError, comp.unregisterSubscriptionAdapter, required=ifoo, provided=ibar, name=_nonblank) def test_unregisterSubscriptionAdapter_neither_factory_nor_provided(self): comp = self._makeOne() self.assertRaises(TypeError, comp.unregisterSubscriptionAdapter, factory=None, provided=None) def test_unregisterSubscriptionAdapter_neither_factory_nor_required(self): from zope.interface.declarations import InterfaceClass class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') comp = self._makeOne() self.assertRaises(TypeError, comp.unregisterSubscriptionAdapter, factory=None, provided=ifoo, required=None) def test_unregisterSubscriptionAdapter_miss(self): from zope.interface.declarations import InterfaceClass class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') class _Factory(object): def __init__(self, context): self._context = context comp = self._makeOne() _monkey, _events = self._wrapEvents() with _monkey: unreg = comp.unregisterSubscriptionAdapter(_Factory, (ibar,), ifoo) self.failIf(unreg) self.failIf(_events) def test_unregisterSubscriptionAdapter_hit_wo_factory(self): from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Unregistered from zope.interface.registry import SubscriptionRegistration class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') class _Factory(object): def __init__(self, context): self._context = context comp = self._makeOne() comp.registerSubscriptionAdapter(_Factory, (ibar,), ifoo) _monkey, _events = self._wrapEvents() with _monkey: unreg = comp.unregisterSubscriptionAdapter(None, (ibar,), ifoo) self.failUnless(unreg) self.failIf(comp.adapters._subscribers) self.failIf(comp._subscription_registrations) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Unregistered)) self.failUnless(isinstance(event.object, SubscriptionRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.assertEqual(event.object.required, (ibar,)) self.assertEqual(event.object.name, '') self.assertEqual(event.object.info, '') self.failUnless(event.object.factory is None) def test_unregisterSubscriptionAdapter_hit_w_factory(self): from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Unregistered from zope.interface.registry import SubscriptionRegistration class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') class _Factory(object): def __init__(self, context): self._context = context comp = self._makeOne() comp.registerSubscriptionAdapter(_Factory, (ibar,), ifoo) _monkey, _events = self._wrapEvents() with _monkey: unreg = comp.unregisterSubscriptionAdapter(_Factory, (ibar,), ifoo) self.failUnless(unreg) self.failIf(comp.adapters._subscribers) self.failIf(comp._subscription_registrations) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Unregistered)) self.failUnless(isinstance(event.object, SubscriptionRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.assertEqual(event.object.required, (ibar,)) self.assertEqual(event.object.name, '') self.assertEqual(event.object.info, '') self.failUnless(event.object.factory is _Factory) def test_unregisterSubscriptionAdapter_wo_explicit_provided(self): from zope.interface.declarations import InterfaceClass from zope.interface.declarations import implementer from zope.interface.interfaces import Unregistered from zope.interface.registry import SubscriptionRegistration class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') @implementer(ifoo) class _Factory(object): def __init__(self, context): self._context = context comp = self._makeOne() comp.registerSubscriptionAdapter(_Factory, (ibar,), ifoo) _monkey, _events = self._wrapEvents() with _monkey: unreg = comp.unregisterSubscriptionAdapter(_Factory, (ibar,)) self.failUnless(unreg) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Unregistered)) self.failUnless(isinstance(event.object, SubscriptionRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.assertEqual(event.object.required, (ibar,)) self.assertEqual(event.object.name, '') self.assertEqual(event.object.info, '') self.failUnless(event.object.factory is _Factory) def test_unregisterSubscriptionAdapter_wo_explicit_required(self): from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Unregistered from zope.interface.registry import SubscriptionRegistration class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') class _Factory(object): __component_adapts__ = (ibar,) def __init__(self, context): self._context = context comp = self._makeOne() comp.registerSubscriptionAdapter(_Factory, (ibar,), ifoo) _monkey, _events = self._wrapEvents() with _monkey: unreg = comp.unregisterSubscriptionAdapter(_Factory, provided=ifoo) self.failUnless(unreg) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Unregistered)) self.failUnless(isinstance(event.object, SubscriptionRegistration)) self.failUnless(event.object.registry is comp) self.failUnless(event.object.provided is ifoo) self.assertEqual(event.object.required, (ibar,)) self.assertEqual(event.object.name, '') self.assertEqual(event.object.info, '') self.failUnless(event.object.factory is _Factory) def test_subscribers_empty(self): from zope.interface.declarations import InterfaceClass from zope.interface.declarations import implementer class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') comp = self._makeOne() @implementer(ibar) class Bar(object): pass bar = Bar() self.assertEqual(list(comp.subscribers((bar,), ifoo)), []) def test_subscribers_non_empty(self): from zope.interface.declarations import InterfaceClass from zope.interface.declarations import implementer class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') class _Factory(object): __component_adapts__ = (ibar,) def __init__(self, context): self._context = context class _Derived(_Factory): pass comp = self._makeOne() comp.registerSubscriptionAdapter(_Factory, (ibar,), ifoo) comp.registerSubscriptionAdapter(_Derived, (ibar,), ifoo) @implementer(ibar) class Bar(object): pass bar = Bar() subscribers = comp.subscribers((bar,), ifoo) def _klassname(x): return x.__class__.__name__ subscribers = sorted(subscribers, key=_klassname) self.assertEqual(len(subscribers), 2) self.failUnless(isinstance(subscribers[0], _Derived)) self.failUnless(isinstance(subscribers[1], _Factory)) def test_registerHandler_w_nonblank_name(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _nonblank = _u('nonblank') comp = self._makeOne() def _factory(context): pass self.assertRaises(TypeError, comp.registerHandler, _factory, required=ifoo, name=_nonblank) def test_registerHandler_w_explicit_required(self): from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Registered from zope.interface.registry import HandlerRegistration from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _blank = _u('') _info = _u('info') _to_reg = object() def _factory(context): return _to_reg comp = self._makeOne() _monkey, _events = self._wrapEvents() with _monkey: comp.registerHandler(_factory, (ifoo,), info=_info) reg = comp.adapters._subscribers[1][ifoo][None][_blank] self.assertEqual(len(reg), 1) self.failUnless(reg[0] is _factory) self.assertEqual(comp._handler_registrations, [((ifoo,), _blank, _factory, _info)]) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Registered)) self.failUnless(isinstance(event.object, HandlerRegistration)) self.failUnless(event.object.registry is comp) self.assertEqual(event.object.required, (ifoo,)) self.assertEqual(event.object.name, _blank) self.failUnless(event.object.info is _info) self.failUnless(event.object.factory is _factory) def test_registerHandler_wo_explicit_required(self): from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Registered from zope.interface.registry import HandlerRegistration from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _info = _u('info') _blank = _u('') class _Factory(object): __component_adapts__ = (ifoo,) def __init__(self, context): self._context = context comp = self._makeOne() _monkey, _events = self._wrapEvents() with _monkey: comp.registerHandler(_Factory, info=_info) reg = comp.adapters._subscribers[1][ifoo][None][_blank] self.assertEqual(len(reg), 1) self.failUnless(reg[0] is _Factory) self.assertEqual(comp._handler_registrations, [((ifoo,), _blank, _Factory, _info)]) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Registered)) self.failUnless(isinstance(event.object, HandlerRegistration)) self.failUnless(event.object.registry is comp) self.assertEqual(event.object.required, (ifoo,)) self.assertEqual(event.object.name, _blank) self.failUnless(event.object.info is _info) self.failUnless(event.object.factory is _Factory) def test_registeredHandlers_empty(self): from zope.interface.declarations import InterfaceClass class IFoo(InterfaceClass): pass comp = self._makeOne() self.failIf(list(comp.registeredHandlers())) def test_registeredHandlers_non_empty(self): from zope.interface.declarations import InterfaceClass from zope.interface.registry import HandlerRegistration class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') def _factory1(context): pass def _factory2(context): pass comp = self._makeOne() comp.registerHandler(_factory1, (ifoo,)) comp.registerHandler(_factory2, (ifoo,)) def _factory_name(x): return x.factory.__code__.co_name subscribers = sorted(comp.registeredHandlers(), key=_factory_name) self.assertEqual(len(subscribers), 2) self.failUnless(isinstance(subscribers[0], HandlerRegistration)) self.assertEqual(subscribers[0].required, (ifoo,)) self.assertEqual(subscribers[0].name, '') self.assertEqual(subscribers[0].factory, _factory1) self.assertEqual(subscribers[0].info, '') self.failUnless(isinstance(subscribers[1], HandlerRegistration)) self.assertEqual(subscribers[1].required, (ifoo,)) self.assertEqual(subscribers[1].name, '') self.assertEqual(subscribers[1].factory, _factory2) self.assertEqual(subscribers[1].info, '') def test_unregisterHandler_w_nonblank_name(self): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _nonblank = _u('nonblank') comp = self._makeOne() self.assertRaises(TypeError, comp.unregisterHandler, required=(ifoo,), name=_nonblank) def test_unregisterHandler_neither_factory_nor_required(self): from zope.interface.declarations import InterfaceClass class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') comp = self._makeOne() self.assertRaises(TypeError, comp.unregisterHandler) def test_unregisterHandler_miss(self): from zope.interface.declarations import InterfaceClass class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') comp = self._makeOne() unreg = comp.unregisterHandler(required=(ifoo,)) self.failIf(unreg) def test_unregisterHandler_hit_w_factory_and_explicit_provided(self): from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Unregistered from zope.interface.registry import HandlerRegistration class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') comp = self._makeOne() _to_reg = object() def _factory(context): return _to_reg comp = self._makeOne() comp.registerHandler(_factory, (ifoo,)) _monkey, _events = self._wrapEvents() with _monkey: unreg = comp.unregisterHandler(_factory, (ifoo,)) self.failUnless(unreg) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Unregistered)) self.failUnless(isinstance(event.object, HandlerRegistration)) self.failUnless(event.object.registry is comp) self.assertEqual(event.object.required, (ifoo,)) self.assertEqual(event.object.name, '') self.failUnless(event.object.factory is _factory) def test_unregisterHandler_hit_w_only_explicit_provided(self): from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Unregistered from zope.interface.registry import HandlerRegistration class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') comp = self._makeOne() _to_reg = object() def _factory(context): return _to_reg comp = self._makeOne() comp.registerHandler(_factory, (ifoo,)) _monkey, _events = self._wrapEvents() with _monkey: unreg = comp.unregisterHandler(required=(ifoo,)) self.failUnless(unreg) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Unregistered)) self.failUnless(isinstance(event.object, HandlerRegistration)) self.failUnless(event.object.registry is comp) self.assertEqual(event.object.required, (ifoo,)) self.assertEqual(event.object.name, '') self.failUnless(event.object.factory is None) def test_unregisterHandler_wo_explicit_required(self): from zope.interface.declarations import InterfaceClass from zope.interface.interfaces import Unregistered from zope.interface.registry import HandlerRegistration class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') class _Factory(object): __component_adapts__ = (ifoo,) def __init__(self, context): self._context = context comp = self._makeOne() comp.registerHandler(_Factory) _monkey, _events = self._wrapEvents() with _monkey: unreg = comp.unregisterHandler(_Factory) self.failUnless(unreg) self.assertEqual(len(_events), 1) args, kw = _events[0] event, = args self.assertEqual(kw, {}) self.failUnless(isinstance(event, Unregistered)) self.failUnless(isinstance(event.object, HandlerRegistration)) self.failUnless(event.object.registry is comp) self.assertEqual(event.object.required, (ifoo,)) self.assertEqual(event.object.name, '') self.assertEqual(event.object.info, '') self.failUnless(event.object.factory is _Factory) def test_handle_empty(self): from zope.interface.declarations import InterfaceClass from zope.interface.declarations import implementer class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') comp = self._makeOne() @implementer(ifoo) class Bar(object): pass bar = Bar() comp.handle((bar,)) def test_handle_non_empty(self): from zope.interface.declarations import InterfaceClass from zope.interface.declarations import implementer class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') _called_1 = [] def _factory_1(context): _called_1.append(context) _called_2 = [] def _factory_2(context): _called_2.append(context) comp = self._makeOne() comp.registerHandler(_factory_1, (ifoo,)) comp.registerHandler(_factory_2, (ifoo,)) @implementer(ifoo) class Bar(object): pass bar = Bar() comp.handle(bar) self.assertEqual(_called_1, [bar]) self.assertEqual(_called_2, [bar]) # Test _getUtilityProvided, _getAdapterProvided, _getAdapterRequired via their # callers (Component.registerUtility, Component.registerAdapter). class UtilityRegistrationTests(_SilencePy3Deprecations): def _getTargetClass(self): from zope.interface.registry import UtilityRegistration return UtilityRegistration def _makeOne(self, component=None, factory=None): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') class _Registry(object): def __repr__(self): return '_REGISTRY' registry = _Registry() name = _u('name') doc = 'DOCSTRING' klass = self._getTargetClass() return (klass(registry, ifoo, name, component, doc, factory), registry, name, ) def test_class_conforms_to_IUtilityRegistration(self): from zope.interface.verify import verifyClass from zope.interface.interfaces import IUtilityRegistration verifyClass(IUtilityRegistration, self._getTargetClass()) def test_instance_conforms_to_IUtilityRegistration(self): from zope.interface.verify import verifyObject from zope.interface.interfaces import IUtilityRegistration ur, _, _ = self._makeOne() verifyObject(IUtilityRegistration, ur) def test___repr__(self): class _Component(object): __name__ = 'TEST' _component = _Component() ur, _registry, _name = self._makeOne(_component) self.assertEqual(repr(ur), "UtilityRegistration(_REGISTRY, IFoo, %r, TEST, None, 'DOCSTRING')" % (_name)) def test___repr___provided_wo_name(self): class _Component(object): def __repr__(self): return 'TEST' _component = _Component() ur, _registry, _name = self._makeOne(_component) ur.provided = object() self.assertEqual(repr(ur), "UtilityRegistration(_REGISTRY, None, %r, TEST, None, 'DOCSTRING')" % (_name)) def test___repr___component_wo_name(self): class _Component(object): def __repr__(self): return 'TEST' _component = _Component() ur, _registry, _name = self._makeOne(_component) ur.provided = object() self.assertEqual(repr(ur), "UtilityRegistration(_REGISTRY, None, %r, TEST, None, 'DOCSTRING')" % (_name)) def test___hash__(self): _component = object() ur, _registry, _name = self._makeOne(_component) self.assertEqual(ur.__hash__(), id(ur)) def test___eq___identity(self): _component = object() ur, _registry, _name = self._makeOne(_component) self.failUnless(ur == ur) def test___eq___hit(self): _component = object() ur, _registry, _name = self._makeOne(_component) ur2, _, _ = self._makeOne(_component) self.failUnless(ur == ur2) def test___eq___miss(self): _component = object() _component2 = object() ur, _registry, _name = self._makeOne(_component) ur2, _, _ = self._makeOne(_component2) self.failIf(ur == ur2) def test___ne___identity(self): _component = object() ur, _registry, _name = self._makeOne(_component) self.failIf(ur != ur) def test___ne___hit(self): _component = object() ur, _registry, _name = self._makeOne(_component) ur2, _, _ = self._makeOne(_component) self.failIf(ur != ur2) def test___ne___miss(self): _component = object() _component2 = object() ur, _registry, _name = self._makeOne(_component) ur2, _, _ = self._makeOne(_component2) self.failUnless(ur != ur2) def test___lt___identity(self): _component = object() ur, _registry, _name = self._makeOne(_component) self.failIf(ur < ur) def test___lt___hit(self): _component = object() ur, _registry, _name = self._makeOne(_component) ur2, _, _ = self._makeOne(_component) self.failIf(ur < ur2) def test___lt___miss(self): _component = object() _component2 = object() ur, _registry, _name = self._makeOne(_component) ur2, _, _ = self._makeOne(_component2) ur2.name = _name + '2' self.failUnless(ur < ur2) def test___le___identity(self): _component = object() ur, _registry, _name = self._makeOne(_component) self.failUnless(ur <= ur) def test___le___hit(self): _component = object() ur, _registry, _name = self._makeOne(_component) ur2, _, _ = self._makeOne(_component) self.failUnless(ur <= ur2) def test___le___miss(self): _component = object() _component2 = object() ur, _registry, _name = self._makeOne(_component) ur2, _, _ = self._makeOne(_component2) ur2.name = _name + '2' self.failUnless(ur <= ur2) def test___gt___identity(self): _component = object() ur, _registry, _name = self._makeOne(_component) self.failIf(ur > ur) def test___gt___hit(self): _component = object() _component2 = object() ur, _registry, _name = self._makeOne(_component) ur2, _, _ = self._makeOne(_component2) ur2.name = _name + '2' self.failUnless(ur2 > ur) def test___gt___miss(self): _component = object() ur, _registry, _name = self._makeOne(_component) ur2, _, _ = self._makeOne(_component) self.failIf(ur2 > ur) def test___ge___identity(self): _component = object() ur, _registry, _name = self._makeOne(_component) self.failUnless(ur >= ur) def test___ge___miss(self): _component = object() _component2 = object() ur, _registry, _name = self._makeOne(_component) ur2, _, _ = self._makeOne(_component2) ur2.name = _name + '2' self.failIf(ur >= ur2) def test___ge___hit(self): _component = object() ur, _registry, _name = self._makeOne(_component) ur2, _, _ = self._makeOne(_component) ur2.name = _name + '2' self.failUnless(ur2 >= ur) class AdapterRegistrationTests(_SilencePy3Deprecations): def _getTargetClass(self): from zope.interface.registry import AdapterRegistration return AdapterRegistration def _makeOne(self, component=None): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') class _Registry(object): def __repr__(self): return '_REGISTRY' registry = _Registry() name = _u('name') doc = 'DOCSTRING' klass = self._getTargetClass() return (klass(registry, (ibar,), ifoo, name, component, doc), registry, name, ) def test_class_conforms_to_IAdapterRegistration(self): from zope.interface.verify import verifyClass from zope.interface.interfaces import IAdapterRegistration verifyClass(IAdapterRegistration, self._getTargetClass()) def test_instance_conforms_to_IAdapterRegistration(self): from zope.interface.verify import verifyObject from zope.interface.interfaces import IAdapterRegistration ar, _, _ = self._makeOne() verifyObject(IAdapterRegistration, ar) def test___repr__(self): class _Component(object): __name__ = 'TEST' _component = _Component() ar, _registry, _name = self._makeOne(_component) self.assertEqual(repr(ar), ("AdapterRegistration(_REGISTRY, [IBar], IFoo, %r, TEST, " + "'DOCSTRING')") % (_name)) def test___repr___provided_wo_name(self): class _Component(object): def __repr__(self): return 'TEST' _component = _Component() ar, _registry, _name = self._makeOne(_component) ar.provided = object() self.assertEqual(repr(ar), ("AdapterRegistration(_REGISTRY, [IBar], None, %r, TEST, " + "'DOCSTRING')") % (_name)) def test___repr___component_wo_name(self): class _Component(object): def __repr__(self): return 'TEST' _component = _Component() ar, _registry, _name = self._makeOne(_component) ar.provided = object() self.assertEqual(repr(ar), ("AdapterRegistration(_REGISTRY, [IBar], None, %r, TEST, " + "'DOCSTRING')") % (_name)) def test___hash__(self): _component = object() ar, _registry, _name = self._makeOne(_component) self.assertEqual(ar.__hash__(), id(ar)) def test___eq___identity(self): _component = object() ar, _registry, _name = self._makeOne(_component) self.failUnless(ar == ar) def test___eq___hit(self): _component = object() ar, _registry, _name = self._makeOne(_component) ar2, _, _ = self._makeOne(_component) self.failUnless(ar == ar2) def test___eq___miss(self): _component = object() _component2 = object() ar, _registry, _name = self._makeOne(_component) ar2, _, _ = self._makeOne(_component2) self.failIf(ar == ar2) def test___ne___identity(self): _component = object() ar, _registry, _name = self._makeOne(_component) self.failIf(ar != ar) def test___ne___miss(self): _component = object() ar, _registry, _name = self._makeOne(_component) ar2, _, _ = self._makeOne(_component) self.failIf(ar != ar2) def test___ne___hit_component(self): _component = object() _component2 = object() ar, _registry, _name = self._makeOne(_component) ar2, _, _ = self._makeOne(_component2) self.failUnless(ar != ar2) def test___ne___hit_provided(self): from zope.interface.declarations import InterfaceClass class IFoo(InterfaceClass): pass ibaz = IFoo('IBaz') _component = object() ar, _registry, _name = self._makeOne(_component) ar2, _, _ = self._makeOne(_component) ar2.provided = ibaz self.failUnless(ar != ar2) def test___ne___hit_required(self): from zope.interface.declarations import InterfaceClass class IFoo(InterfaceClass): pass ibaz = IFoo('IBaz') _component = object() _component2 = object() ar, _registry, _name = self._makeOne(_component) ar2, _, _ = self._makeOne(_component2) ar2.required = (ibaz,) self.failUnless(ar != ar2) def test___lt___identity(self): _component = object() ar, _registry, _name = self._makeOne(_component) self.failIf(ar < ar) def test___lt___hit(self): _component = object() ar, _registry, _name = self._makeOne(_component) ar2, _, _ = self._makeOne(_component) self.failIf(ar < ar2) def test___lt___miss(self): _component = object() _component2 = object() ar, _registry, _name = self._makeOne(_component) ar2, _, _ = self._makeOne(_component2) ar2.name = _name + '2' self.failUnless(ar < ar2) def test___le___identity(self): _component = object() ar, _registry, _name = self._makeOne(_component) self.failUnless(ar <= ar) def test___le___hit(self): _component = object() ar, _registry, _name = self._makeOne(_component) ar2, _, _ = self._makeOne(_component) self.failUnless(ar <= ar2) def test___le___miss(self): _component = object() _component2 = object() ar, _registry, _name = self._makeOne(_component) ar2, _, _ = self._makeOne(_component2) ar2.name = _name + '2' self.failUnless(ar <= ar2) def test___gt___identity(self): _component = object() ar, _registry, _name = self._makeOne(_component) self.failIf(ar > ar) def test___gt___hit(self): _component = object() _component2 = object() ar, _registry, _name = self._makeOne(_component) ar2, _, _ = self._makeOne(_component2) ar2.name = _name + '2' self.failUnless(ar2 > ar) def test___gt___miss(self): _component = object() ar, _registry, _name = self._makeOne(_component) ar2, _, _ = self._makeOne(_component) self.failIf(ar2 > ar) def test___ge___identity(self): _component = object() ar, _registry, _name = self._makeOne(_component) self.failUnless(ar >= ar) def test___ge___miss(self): _component = object() _component2 = object() ar, _registry, _name = self._makeOne(_component) ar2, _, _ = self._makeOne(_component2) ar2.name = _name + '2' self.failIf(ar >= ar2) def test___ge___hit(self): _component = object() ar, _registry, _name = self._makeOne(_component) ar2, _, _ = self._makeOne(_component) ar2.name = _name + '2' self.failUnless(ar2 >= ar) class SubscriptionRegistrationTests(unittest.TestCase): def _getTargetClass(self): from zope.interface.registry import SubscriptionRegistration return SubscriptionRegistration def _makeOne(self, component=None): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') ibar = IFoo('IBar') class _Registry(object): def __repr__(self): return '_REGISTRY' registry = _Registry() name = _u('name') doc = 'DOCSTRING' klass = self._getTargetClass() return (klass(registry, (ibar,), ifoo, name, component, doc), registry, name, ) def test_class_conforms_to_ISubscriptionAdapterRegistration(self): from zope.interface.verify import verifyClass from zope.interface.interfaces import ISubscriptionAdapterRegistration verifyClass(ISubscriptionAdapterRegistration, self._getTargetClass()) def test_instance_conforms_to_ISubscriptionAdapterRegistration(self): from zope.interface.verify import verifyObject from zope.interface.interfaces import ISubscriptionAdapterRegistration sar, _, _ = self._makeOne() verifyObject(ISubscriptionAdapterRegistration, sar) class HandlerRegistrationTests(_SilencePy3Deprecations): def _getTargetClass(self): from zope.interface.registry import HandlerRegistration return HandlerRegistration def _makeOne(self, component=None): from zope.interface.declarations import InterfaceClass from zope.interface._compat import _u class IFoo(InterfaceClass): pass ifoo = IFoo('IFoo') class _Registry(object): def __repr__(self): return '_REGISTRY' registry = _Registry() name = _u('name') doc = 'DOCSTRING' klass = self._getTargetClass() return (klass(registry, (ifoo,), name, component, doc), registry, name, ) def test_class_conforms_to_IHandlerRegistration(self): from zope.interface.verify import verifyClass from zope.interface.interfaces import IHandlerRegistration verifyClass(IHandlerRegistration, self._getTargetClass()) def test_instance_conforms_to_IHandlerRegistration(self): from zope.interface.verify import verifyObject from zope.interface.interfaces import IHandlerRegistration hr, _, _ = self._makeOne() verifyObject(IHandlerRegistration, hr) def test_properties(self): def _factory(context): pass hr, _, _ = self._makeOne(_factory) self.failUnless(hr.handler is _factory) self.failUnless(hr.factory is hr.handler) self.failUnless(hr.provided is None) def test___repr___factory_w_name(self): class _Factory(object): __name__ = 'TEST' hr, _registry, _name = self._makeOne(_Factory()) self.assertEqual(repr(hr), ("HandlerRegistration(_REGISTRY, [IFoo], %r, TEST, " + "'DOCSTRING')") % (_name)) def test___repr___factory_wo_name(self): class _Factory(object): def __repr__(self): return 'TEST' hr, _registry, _name = self._makeOne(_Factory()) self.assertEqual(repr(hr), ("HandlerRegistration(_REGISTRY, [IFoo], %r, TEST, " + "'DOCSTRING')") % (_name)) class _Monkey(object): # context-manager for replacing module names in the scope of a test. def __init__(self, module, **kw): self.module = module self.to_restore = dict([(key, getattr(module, key)) for key in kw]) for key, value in kw.items(): setattr(module, key, value) def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): for key, value in self.to_restore.items(): setattr(self.module, key, value) def test_suite(): return unittest.TestSuite(( unittest.makeSuite(ComponentsTests), unittest.makeSuite(UtilityRegistrationTests), unittest.makeSuite(AdapterRegistrationTests), unittest.makeSuite(SubscriptionRegistrationTests), unittest.makeSuite(AdapterRegistrationTests), ))
true
true
f717c69030d602486ed1591a2382be46b01ff559
3,373
py
Python
hw/ip/otbn/dv/otbnsim/sim/csr.py
Jacob-Levy/opentitan
13ed3e95572168f7db0e3178d06a72e72ee5a745
[ "Apache-2.0" ]
2
2019-11-21T14:05:14.000Z
2020-07-10T12:40:54.000Z
hw/ip/otbn/dv/otbnsim/sim/csr.py
Jacob-Levy/opentitan
13ed3e95572168f7db0e3178d06a72e72ee5a745
[ "Apache-2.0" ]
null
null
null
hw/ip/otbn/dv/otbnsim/sim/csr.py
Jacob-Levy/opentitan
13ed3e95572168f7db0e3178d06a72e72ee5a745
[ "Apache-2.0" ]
null
null
null
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 from .flags import FlagGroups from .wsr import WSRFile class CSRFile: '''A model of the CSR file''' def __init__(self) -> None: self.flags = FlagGroups() self._known_indices = set() self._known_indices.add(0x7c0) # FG0 self._known_indices.add(0x7c1) # FG1 self._known_indices.add(0x7c8) # FLAGS for idx in range(0x7d0, 0x7d8): self._known_indices.add(idx) # MODi self._known_indices.add(0x7d8) # RND_PREFETCH self._known_indices.add(0xfc0) # RND self._known_indices.add(0xfc1) # URND @staticmethod def _get_field(field_idx: int, field_size: int, val: int) -> int: mask = (1 << field_size) - 1 return (val >> (field_size * field_idx)) & mask @staticmethod def _set_field(field_idx: int, field_size: int, field_val: int, old_val: int) -> int: assert 0 <= field_val < (1 << field_size) mask = (1 << field_size) - 1 shift = field_size * field_idx return (old_val & ~(mask << shift)) | (field_val << shift) def check_idx(self, idx: int) -> bool: '''Return True if idx points to a valid CSR; False otherwise.''' return idx in self._known_indices def read_unsigned(self, wsrs: WSRFile, idx: int) -> int: if 0x7c0 <= idx <= 0x7c1: # FG0/FG1 fg = idx - 0x7c0 return self._get_field(fg, 4, self.flags.read_unsigned()) if idx == 0x7c8: # FLAGS register return self.flags.read_unsigned() if 0x7d0 <= idx <= 0x7d7: # MOD0 .. MOD7. MODi is bits [32*(i+1)-1..32*i] mod_n = idx - 0x7d0 return self._get_field(mod_n, 32, wsrs.MOD.read_unsigned()) if idx == 0x7d8: # RND_PREFETCH register return 0 if idx == 0xfc0: # RND register return wsrs.RND.read_u32() if idx == 0xfc1: # URND register return wsrs.URND.read_u32() raise RuntimeError('Unknown CSR index: {:#x}'.format(idx)) def write_unsigned(self, wsrs: WSRFile, idx: int, value: int) -> None: assert 0 <= value < (1 << 32) if 0x7c0 <= idx <= 0x7c1: # FG0/FG1 fg = idx - 0x7c0 old = self.flags.read_unsigned() self.flags.write_unsigned(self._set_field(fg, 4, value & 0xf, old)) return if idx == 0x7c8: # FLAGS register self.flags.write_unsigned(value) return if 0x7d0 <= idx <= 0x7d7: # MOD0 .. MOD7. MODi is bits [32*(i+1)-1..32*i]. read,modify,write. mod_n = idx - 0x7d0 old = wsrs.MOD.read_unsigned() wsrs.MOD.write_unsigned(self._set_field(mod_n, 32, value, old)) return if idx == 0x7d8: # RND_PREFETCH wsrs.RND.pending_request = True return if idx == 0xfc0: # RND register (which ignores writes) return if idx == 0xfc1: # URND register (which ignores writes) return raise RuntimeError('Unknown CSR index: {:#x}'.format(idx))
31.820755
79
0.555885
from .flags import FlagGroups from .wsr import WSRFile class CSRFile: def __init__(self) -> None: self.flags = FlagGroups() self._known_indices = set() self._known_indices.add(0x7c0) self._known_indices.add(0x7c1) self._known_indices.add(0x7c8) for idx in range(0x7d0, 0x7d8): self._known_indices.add(idx) self._known_indices.add(0x7d8) self._known_indices.add(0xfc0) self._known_indices.add(0xfc1) @staticmethod def _get_field(field_idx: int, field_size: int, val: int) -> int: mask = (1 << field_size) - 1 return (val >> (field_size * field_idx)) & mask @staticmethod def _set_field(field_idx: int, field_size: int, field_val: int, old_val: int) -> int: assert 0 <= field_val < (1 << field_size) mask = (1 << field_size) - 1 shift = field_size * field_idx return (old_val & ~(mask << shift)) | (field_val << shift) def check_idx(self, idx: int) -> bool: return idx in self._known_indices def read_unsigned(self, wsrs: WSRFile, idx: int) -> int: if 0x7c0 <= idx <= 0x7c1: fg = idx - 0x7c0 return self._get_field(fg, 4, self.flags.read_unsigned()) if idx == 0x7c8: return self.flags.read_unsigned() if 0x7d0 <= idx <= 0x7d7: mod_n = idx - 0x7d0 return self._get_field(mod_n, 32, wsrs.MOD.read_unsigned()) if idx == 0x7d8: return 0 if idx == 0xfc0: return wsrs.RND.read_u32() if idx == 0xfc1: return wsrs.URND.read_u32() raise RuntimeError('Unknown CSR index: {:#x}'.format(idx)) def write_unsigned(self, wsrs: WSRFile, idx: int, value: int) -> None: assert 0 <= value < (1 << 32) if 0x7c0 <= idx <= 0x7c1: fg = idx - 0x7c0 old = self.flags.read_unsigned() self.flags.write_unsigned(self._set_field(fg, 4, value & 0xf, old)) return if idx == 0x7c8: self.flags.write_unsigned(value) return if 0x7d0 <= idx <= 0x7d7: mod_n = idx - 0x7d0 old = wsrs.MOD.read_unsigned() wsrs.MOD.write_unsigned(self._set_field(mod_n, 32, value, old)) return if idx == 0x7d8: wsrs.RND.pending_request = True return if idx == 0xfc0: return if idx == 0xfc1: return raise RuntimeError('Unknown CSR index: {:#x}'.format(idx))
true
true
f717c7a5b3ca5f9a8a20ce7a7c9f7a50b5ae1c68
14,021
py
Python
tests/ci/sync_requirements.py
lolwww/rally
fcb1fb6c608e29dd62549cf6b3cec2e90529932f
[ "Apache-2.0" ]
null
null
null
tests/ci/sync_requirements.py
lolwww/rally
fcb1fb6c608e29dd62549cf6b3cec2e90529932f
[ "Apache-2.0" ]
null
null
null
tests/ci/sync_requirements.py
lolwww/rally
fcb1fb6c608e29dd62549cf6b3cec2e90529932f
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Synchronizes, formats and prepares requirements to release(obtains and adds maximum allowed version). """ import collections import logging import re import sys import textwrap import requests LOG = logging.getLogger(__name__) if not LOG.handlers: LOG.addHandler(logging.StreamHandler()) LOG.setLevel(logging.INFO) GLOBAL_REQUIREMENTS_LOCATIONS = ( "https://raw.githubusercontent.com/openstack/requirements/master/", "http://opendev.org/openstack/requirements/raw/branch/master/" ) RALLY_REQUIREMENTS_FILES = ( "requirements.txt", "test-requirements.txt" ) DO_NOT_TOUCH_TAG = "[do-not-touch]" class Comment(object): def __init__(self, s=None, finished=False): self._comments = [] self.is_finished = finished if s: self.append(s) def finish_him(self): self.is_finished = True def append(self, s): self._comments.append(s[1:].strip()) def __str__(self): return textwrap.fill("\n".join(self._comments), width=80, initial_indent="# ", subsequent_indent="# ") _PYPI_CACHE = {} class PYPIPackage(object): # NOTE(andreykurilin): one license can have different labels. Let's use # unified variant. LICENSE_MAP = {"MIT license": "MIT", "MIT License": "MIT", "BSD License": "BSD", "Apache 2.0": "Apache License, Version 2.0"} def __init__(self, package_name): self.package_name = package_name self._pypi_info = None self._pypi_license = None @property def pypi_info(self): if self._pypi_info is None: if self.package_name in _PYPI_CACHE: self._pypi_info = _PYPI_CACHE[self.package_name] else: resp = requests.get("https://pypi.org/pypi/%s/json" % self.package_name) if resp.status_code != 200: print("An error occurred while checking '%s' package at " "pypi." % self.package_name) raise Exception(resp.text) self._pypi_info = resp.json() # let's cache it for the case when we need to sync requirements # and update upper constrains _PYPI_CACHE[self.package_name] = self._pypi_info return self._pypi_info @property def pypi_version(self): return self.pypi_info["info"]["version"] @property def pypi_license(self): if self._pypi_license is None: if self.pypi_info["info"]["license"]: self._pypi_license = self.pypi_info["info"]["license"] else: # try to parse classifiers prefix = "License :: OSI Approved :: " classifiers = [c[len(prefix):] for c in self.pypi_info["info"]["classifiers"] if c.startswith(prefix)] self._pypi_license = "/".join(classifiers) self._license = self.LICENSE_MAP.get(self._pypi_license, self._pypi_license) if self._pypi_license == "UNKNOWN": self._pypi_license = None return self._license def __eq__(self, other): return (isinstance(other, PYPIPackage) and self.package_name == other.package_name) class Requirement(PYPIPackage): RE_NAME = re.compile(r"[a-zA-Z0-9-._]+") RE_CONST_VERSION = re.compile(r"==[a-zA-Z0-9.]+") RE_MIN_VERSION = re.compile(r">=?[a-zA-Z0-9.]+") RE_MAX_VERSION = re.compile(r"<=?[a-zA-Z0-9.]+") RE_NE_VERSIONS = re.compile(r"!=[a-zA-Z0-9.]+") def __init__(self, package_name, version): super(Requirement, self).__init__(package_name) self.version = version self.do_not_touch = False def sync_max_version_with_pypy(self): if isinstance(self.version, dict) and not self.do_not_touch: self.version["max"] = "<=%s" % self.pypi_version @classmethod def parse_line(cls, line): match = cls.RE_NAME.match(line) if match: name = match.group() # remove name versions = line.replace(name, "") # remove comments versions = versions.split("#")[0] # remove python classifiers versions = versions.split(";")[0].strip() if not cls.RE_CONST_VERSION.match(versions): versions = versions.strip().split(",") min_version = None max_version = None ne_versions = [] for version in versions: if cls.RE_MIN_VERSION.match(version): if min_version: raise Exception("Found several min versions for " "%s package." % name) min_version = version elif cls.RE_MAX_VERSION.match(version): if max_version: raise Exception("Found several max versions for " "%s package." % name) max_version = version elif cls.RE_NE_VERSIONS.match(version): ne_versions.append(version) versions = {"min": min_version, "max": max_version, "ne": ne_versions} return cls(name, versions) def __str__(self): if isinstance(self.version, dict): version = [] min_equal_to_max = False if self.version["min"] and self.version["max"]: if ( self.version["min"].startswith(">=") and self.version["max"].startswith("<=") and self.version["min"][2:] == self.version["max"][2:] ): # min and max versions are equal there is no need to write # both of them min_equal_to_max = True version.append("==%s" % self.version["min"][2:]) if not min_equal_to_max and self.version["min"]: version.append(self.version["min"]) if not min_equal_to_max and self.version["ne"]: version.extend(self.version["ne"]) if not min_equal_to_max and self.version["max"]: version.append(self.version["max"]) version = ",".join(version) else: if self.do_not_touch: version = self.version else: # remove const version version = ">=%s" % self.version[2:] string = "%s%s" % (self.package_name, version) if self.pypi_license: # NOTE(andreykurilin): When I start implementation of this script, # python-keystoneclient dependency string took around ~45-55 # chars, so let's use this length as indent. Feel free to modify # it to lower or greater value. magic_number = 55 if len(string) < magic_number: indent = magic_number - len(string) else: indent = 2 string += " " * indent + "# " + self.pypi_license return string def __eq__(self, other): return (isinstance(other, self.__class__) and self.package_name == other.package_name) def __ne__(self, other): return not self.__eq__(other) class UpperConstraint(PYPIPackage): RE_LINE = re.compile( r"(?P<package_name>[a-zA-Z0-9-._]+)===(?P<version>[a-zA-Z0-9.]+)") def __init__(self, package_name, version=None): super(UpperConstraint, self).__init__(package_name) self._version = version def __str__(self): return "%s===%s" % (self.package_name, self.version) @property def version(self): if self._version is None: self._version = self.pypi_version return self._version @classmethod def parse_line(cls, line): match = cls.RE_LINE.match(line) if match: return cls(**match.groupdict()) def update(self, version): self._version = version def parse_data(raw_data, include_comments=True, dependency_cls=Requirement): # first elem is None to simplify checks of last elem in requirements requirements = [None] for line in raw_data.split("\n"): if line.startswith("#"): if not include_comments: continue if getattr(requirements[-1], "is_finished", True): requirements.append(Comment()) requirements[-1].append(line) elif line == "": # just empty line if isinstance(requirements[-1], Comment): requirements[-1].finish_him() requirements.append(Comment(finished=True)) else: if (isinstance(requirements[-1], Comment) and not requirements[-1].is_finished): requirements[-1].finish_him() # parse_line dep = dependency_cls.parse_line(line) if dep: if (isinstance(requirements[-1], Comment) and DO_NOT_TOUCH_TAG in str(requirements[-1])): dep.do_not_touch = True requirements.append(dep) for i in range(len(requirements) - 1, 0, -1): # remove empty lines at the end of file if isinstance(requirements[i], Comment): if str(requirements[i]) == "": requirements.pop(i) else: break return collections.OrderedDict( (v if isinstance(v, Comment) else v.package_name, v) for v in requirements if v) def _fetch_from_gr(filename): """Try to fetch data from OpenStack global-requirements repo""" for i in range(0, len(GLOBAL_REQUIREMENTS_LOCATIONS)): url = GLOBAL_REQUIREMENTS_LOCATIONS[i] + filename LOG.debug("Try to obtain %s from %s" % (filename, url)) try: return requests.get(url).text except requests.ConnectionError as e: LOG.exception(e) raise Exception("Unable to obtain %s" % filename) def _write_requirements(filename, requirements): """Saves requirements to file.""" if isinstance(requirements, dict): requirements = requirements.values() LOG.info("Saving requirements to %s." % filename) with open(filename, "w") as f: for entity in requirements: f.write(str(entity)) f.write("\n") def sync_requirements(): """Synchronizes Rally requirements with OpenStack global-requirements.""" LOG.info("Obtaining global-requirements of OpenStack...") raw_gr = _fetch_from_gr("global-requirements.txt") # NOTE(andreykurilin): global-requirements includes comments which can be # unrelated to Rally project, so let's just ignore them gr = parse_data(raw_gr, include_comments=False) for file_name in RALLY_REQUIREMENTS_FILES: LOG.debug("Processing '%s'." % file_name) with open(file_name) as f: requirements = parse_data(f.read()) for name, req in requirements.items(): if isinstance(req, Requirement) and not req.do_not_touch: if name in gr: req.version = gr[req.package_name].version else: # it not g-r requirements if isinstance(req.version, dict): req.version["max"] = None _write_requirements(file_name, requirements) def update_upper_constraints(): """Obtains latest version of packages and put them to upper-constraints.""" LOG.info("Obtaining upper-constrains from OpenStack...") raw_g_uc = _fetch_from_gr("upper-constraints.txt") # NOTE(andreykurilin): global OpenStack upper-constraints file includes # comments which can be unrelated to Rally project, so let's just ignore # them. global_uc = parse_data(raw_g_uc, include_comments=False, dependency_cls=UpperConstraint) with open("upper-constraints.txt") as f: our_uc = parse_data(f.read(), dependency_cls=UpperConstraint) with open("requirements.txt") as f: our_requirements = parse_data(f.read(), include_comments=False) for name, req in our_requirements.items(): if isinstance(req, Comment): continue if name not in our_uc: our_uc[name] = UpperConstraint(name) if name in global_uc: # we cannot use whatever we want versions in CI. OpenStack CI # ignores versions listed in requirements of # particular project and use versions from global u-c file. # It means that we need to suggest to use the same versions our_uc[name].update(global_uc[name].version) our_uc = sorted(our_uc.values(), key=lambda o: o.package_name.upper()) _write_requirements("upper-constraints.txt", our_uc) def main(): sync_requirements() update_upper_constraints() if __name__ == "__main__": sys.exit(main())
36.136598
79
0.57799
import collections import logging import re import sys import textwrap import requests LOG = logging.getLogger(__name__) if not LOG.handlers: LOG.addHandler(logging.StreamHandler()) LOG.setLevel(logging.INFO) GLOBAL_REQUIREMENTS_LOCATIONS = ( "https://raw.githubusercontent.com/openstack/requirements/master/", "http://opendev.org/openstack/requirements/raw/branch/master/" ) RALLY_REQUIREMENTS_FILES = ( "requirements.txt", "test-requirements.txt" ) DO_NOT_TOUCH_TAG = "[do-not-touch]" class Comment(object): def __init__(self, s=None, finished=False): self._comments = [] self.is_finished = finished if s: self.append(s) def finish_him(self): self.is_finished = True def append(self, s): self._comments.append(s[1:].strip()) def __str__(self): return textwrap.fill("\n".join(self._comments), width=80, initial_indent="# ", subsequent_indent="# ") _PYPI_CACHE = {} class PYPIPackage(object): # unified variant. LICENSE_MAP = {"MIT license": "MIT", "MIT License": "MIT", "BSD License": "BSD", "Apache 2.0": "Apache License, Version 2.0"} def __init__(self, package_name): self.package_name = package_name self._pypi_info = None self._pypi_license = None @property def pypi_info(self): if self._pypi_info is None: if self.package_name in _PYPI_CACHE: self._pypi_info = _PYPI_CACHE[self.package_name] else: resp = requests.get("https://pypi.org/pypi/%s/json" % self.package_name) if resp.status_code != 200: print("An error occurred while checking '%s' package at " "pypi." % self.package_name) raise Exception(resp.text) self._pypi_info = resp.json() # let's cache it for the case when we need to sync requirements _PYPI_CACHE[self.package_name] = self._pypi_info return self._pypi_info @property def pypi_version(self): return self.pypi_info["info"]["version"] @property def pypi_license(self): if self._pypi_license is None: if self.pypi_info["info"]["license"]: self._pypi_license = self.pypi_info["info"]["license"] else: prefix = "License :: OSI Approved :: " classifiers = [c[len(prefix):] for c in self.pypi_info["info"]["classifiers"] if c.startswith(prefix)] self._pypi_license = "/".join(classifiers) self._license = self.LICENSE_MAP.get(self._pypi_license, self._pypi_license) if self._pypi_license == "UNKNOWN": self._pypi_license = None return self._license def __eq__(self, other): return (isinstance(other, PYPIPackage) and self.package_name == other.package_name) class Requirement(PYPIPackage): RE_NAME = re.compile(r"[a-zA-Z0-9-._]+") RE_CONST_VERSION = re.compile(r"==[a-zA-Z0-9.]+") RE_MIN_VERSION = re.compile(r">=?[a-zA-Z0-9.]+") RE_MAX_VERSION = re.compile(r"<=?[a-zA-Z0-9.]+") RE_NE_VERSIONS = re.compile(r"!=[a-zA-Z0-9.]+") def __init__(self, package_name, version): super(Requirement, self).__init__(package_name) self.version = version self.do_not_touch = False def sync_max_version_with_pypy(self): if isinstance(self.version, dict) and not self.do_not_touch: self.version["max"] = "<=%s" % self.pypi_version @classmethod def parse_line(cls, line): match = cls.RE_NAME.match(line) if match: name = match.group() versions = line.replace(name, "") versions = versions.split("#")[0] versions = versions.split(";")[0].strip() if not cls.RE_CONST_VERSION.match(versions): versions = versions.strip().split(",") min_version = None max_version = None ne_versions = [] for version in versions: if cls.RE_MIN_VERSION.match(version): if min_version: raise Exception("Found several min versions for " "%s package." % name) min_version = version elif cls.RE_MAX_VERSION.match(version): if max_version: raise Exception("Found several max versions for " "%s package." % name) max_version = version elif cls.RE_NE_VERSIONS.match(version): ne_versions.append(version) versions = {"min": min_version, "max": max_version, "ne": ne_versions} return cls(name, versions) def __str__(self): if isinstance(self.version, dict): version = [] min_equal_to_max = False if self.version["min"] and self.version["max"]: if ( self.version["min"].startswith(">=") and self.version["max"].startswith("<=") and self.version["min"][2:] == self.version["max"][2:] ): min_equal_to_max = True version.append("==%s" % self.version["min"][2:]) if not min_equal_to_max and self.version["min"]: version.append(self.version["min"]) if not min_equal_to_max and self.version["ne"]: version.extend(self.version["ne"]) if not min_equal_to_max and self.version["max"]: version.append(self.version["max"]) version = ",".join(version) else: if self.do_not_touch: version = self.version else: version = ">=%s" % self.version[2:] string = "%s%s" % (self.package_name, version) if self.pypi_license: # it to lower or greater value. magic_number = 55 if len(string) < magic_number: indent = magic_number - len(string) else: indent = 2 string += " " * indent + "# " + self.pypi_license return string def __eq__(self, other): return (isinstance(other, self.__class__) and self.package_name == other.package_name) def __ne__(self, other): return not self.__eq__(other) class UpperConstraint(PYPIPackage): RE_LINE = re.compile( r"(?P<package_name>[a-zA-Z0-9-._]+)===(?P<version>[a-zA-Z0-9.]+)") def __init__(self, package_name, version=None): super(UpperConstraint, self).__init__(package_name) self._version = version def __str__(self): return "%s===%s" % (self.package_name, self.version) @property def version(self): if self._version is None: self._version = self.pypi_version return self._version @classmethod def parse_line(cls, line): match = cls.RE_LINE.match(line) if match: return cls(**match.groupdict()) def update(self, version): self._version = version def parse_data(raw_data, include_comments=True, dependency_cls=Requirement): # first elem is None to simplify checks of last elem in requirements requirements = [None] for line in raw_data.split("\n"): if line.startswith("#"): if not include_comments: continue if getattr(requirements[-1], "is_finished", True): requirements.append(Comment()) requirements[-1].append(line) elif line == "": # just empty line if isinstance(requirements[-1], Comment): requirements[-1].finish_him() requirements.append(Comment(finished=True)) else: if (isinstance(requirements[-1], Comment) and not requirements[-1].is_finished): requirements[-1].finish_him() # parse_line dep = dependency_cls.parse_line(line) if dep: if (isinstance(requirements[-1], Comment) and DO_NOT_TOUCH_TAG in str(requirements[-1])): dep.do_not_touch = True requirements.append(dep) for i in range(len(requirements) - 1, 0, -1): # remove empty lines at the end of file if isinstance(requirements[i], Comment): if str(requirements[i]) == "": requirements.pop(i) else: break return collections.OrderedDict( (v if isinstance(v, Comment) else v.package_name, v) for v in requirements if v) def _fetch_from_gr(filename): for i in range(0, len(GLOBAL_REQUIREMENTS_LOCATIONS)): url = GLOBAL_REQUIREMENTS_LOCATIONS[i] + filename LOG.debug("Try to obtain %s from %s" % (filename, url)) try: return requests.get(url).text except requests.ConnectionError as e: LOG.exception(e) raise Exception("Unable to obtain %s" % filename) def _write_requirements(filename, requirements): if isinstance(requirements, dict): requirements = requirements.values() LOG.info("Saving requirements to %s." % filename) with open(filename, "w") as f: for entity in requirements: f.write(str(entity)) f.write("\n") def sync_requirements(): LOG.info("Obtaining global-requirements of OpenStack...") raw_gr = _fetch_from_gr("global-requirements.txt") # NOTE(andreykurilin): global-requirements includes comments which can be # unrelated to Rally project, so let's just ignore them gr = parse_data(raw_gr, include_comments=False) for file_name in RALLY_REQUIREMENTS_FILES: LOG.debug("Processing '%s'." % file_name) with open(file_name) as f: requirements = parse_data(f.read()) for name, req in requirements.items(): if isinstance(req, Requirement) and not req.do_not_touch: if name in gr: req.version = gr[req.package_name].version else: if isinstance(req.version, dict): req.version["max"] = None _write_requirements(file_name, requirements) def update_upper_constraints(): LOG.info("Obtaining upper-constrains from OpenStack...") raw_g_uc = _fetch_from_gr("upper-constraints.txt") # them. global_uc = parse_data(raw_g_uc, include_comments=False, dependency_cls=UpperConstraint) with open("upper-constraints.txt") as f: our_uc = parse_data(f.read(), dependency_cls=UpperConstraint) with open("requirements.txt") as f: our_requirements = parse_data(f.read(), include_comments=False) for name, req in our_requirements.items(): if isinstance(req, Comment): continue if name not in our_uc: our_uc[name] = UpperConstraint(name) if name in global_uc: # we cannot use whatever we want versions in CI. OpenStack CI # ignores versions listed in requirements of # particular project and use versions from global u-c file. # It means that we need to suggest to use the same versions our_uc[name].update(global_uc[name].version) our_uc = sorted(our_uc.values(), key=lambda o: o.package_name.upper()) _write_requirements("upper-constraints.txt", our_uc) def main(): sync_requirements() update_upper_constraints() if __name__ == "__main__": sys.exit(main())
true
true
f717c8b4305af7242c263a306f933192f7a5b976
491
py
Python
route/api_raw.py
susemeee/openNAMU
0f3d8acb5f0fe179cc8dbbfea1846da3ca0cd4e1
[ "BSD-3-Clause" ]
null
null
null
route/api_raw.py
susemeee/openNAMU
0f3d8acb5f0fe179cc8dbbfea1846da3ca0cd4e1
[ "BSD-3-Clause" ]
null
null
null
route/api_raw.py
susemeee/openNAMU
0f3d8acb5f0fe179cc8dbbfea1846da3ca0cd4e1
[ "BSD-3-Clause" ]
1
2020-01-04T09:43:35.000Z
2020-01-04T09:43:35.000Z
from .tool.func import * def api_raw_2(conn, name): curs = conn.cursor() if acl_check(name, 'render') != 1: curs.execute("select data from data where title = ?", [name]) data = curs.fetchall() if data: json_data = { "title" : name, "data" : render_set(title = name, data = data[0][0], s_data = 1) } return flask.jsonify(json_data) else: return flask.jsonify({}) else: return flask.jsonify({})
30.6875
108
0.545825
from .tool.func import * def api_raw_2(conn, name): curs = conn.cursor() if acl_check(name, 'render') != 1: curs.execute("select data from data where title = ?", [name]) data = curs.fetchall() if data: json_data = { "title" : name, "data" : render_set(title = name, data = data[0][0], s_data = 1) } return flask.jsonify(json_data) else: return flask.jsonify({}) else: return flask.jsonify({})
true
true
f717ca0d2a58ad1a206f65fb4972fcfb0f68141c
634
py
Python
rates/migrations/0003_rating.py
Gichimu/irater
2da90230368b2aa5b97b9ab84455703e510e51ef
[ "MIT" ]
null
null
null
rates/migrations/0003_rating.py
Gichimu/irater
2da90230368b2aa5b97b9ab84455703e510e51ef
[ "MIT" ]
16
2020-01-11T08:20:30.000Z
2022-02-10T09:18:48.000Z
rates/migrations/0003_rating.py
Gichimu/irater
2da90230368b2aa5b97b9ab84455703e510e51ef
[ "MIT" ]
null
null
null
# Generated by Django 2.2 on 2020-01-15 06:05 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('rates', '0002_auto_20200113_0757'), ] operations = [ migrations.CreateModel( name='Rating', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('usability', models.IntegerField(default=0)), ('design', models.IntegerField(default=0)), ('content', models.IntegerField(default=0)), ], ), ]
27.565217
114
0.572555
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('rates', '0002_auto_20200113_0757'), ] operations = [ migrations.CreateModel( name='Rating', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('usability', models.IntegerField(default=0)), ('design', models.IntegerField(default=0)), ('content', models.IntegerField(default=0)), ], ), ]
true
true
f717cc90445df76a8ce5da7e005a9d1637cd561b
857
py
Python
setup.py
treamology/sphinx-variations
1f02e3bf32610ef32cf24748d4f91bab0263c173
[ "MIT" ]
null
null
null
setup.py
treamology/sphinx-variations
1f02e3bf32610ef32cf24748d4f91bab0263c173
[ "MIT" ]
2
2019-10-14T12:17:54.000Z
2019-11-29T09:06:54.000Z
setup.py
treamology/sphinx-variations
1f02e3bf32610ef32cf24748d4f91bab0263c173
[ "MIT" ]
1
2019-10-16T10:45:39.000Z
2019-10-16T10:45:39.000Z
import setuptools from variations import __version__ with open('README.md', 'r') as fh: long_description = fh.read() setuptools.setup( name='sphinx-variations', version=__version__, author='D. Lawrence', author_email='trea@treamous.com', description='Create multiple variations of your Sphinx HTML documentation.', long_description=long_description, long_description_content_type='text/markdown', url='https://github.com/treamology/sphinx-variations', packages=['variations'], classifiers=[ 'Programming Language :: Python :: 3', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Framework :: Sphinx', 'Topic :: Documentation', 'Topic :: Software Development :: Documentation', ], install_requires=[ 'sphinx' ], )
30.607143
80
0.662777
import setuptools from variations import __version__ with open('README.md', 'r') as fh: long_description = fh.read() setuptools.setup( name='sphinx-variations', version=__version__, author='D. Lawrence', author_email='trea@treamous.com', description='Create multiple variations of your Sphinx HTML documentation.', long_description=long_description, long_description_content_type='text/markdown', url='https://github.com/treamology/sphinx-variations', packages=['variations'], classifiers=[ 'Programming Language :: Python :: 3', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Framework :: Sphinx', 'Topic :: Documentation', 'Topic :: Software Development :: Documentation', ], install_requires=[ 'sphinx' ], )
true
true
f717ce0bca4aa3ca6519610187210bdcf31b9d6a
2,934
py
Python
musicplayer/buttons.py
Gabe-Corral/Music_Player
9352266aa86e5927e4a603b6238cea4745cc6b26
[ "MIT" ]
null
null
null
musicplayer/buttons.py
Gabe-Corral/Music_Player
9352266aa86e5927e4a603b6238cea4745cc6b26
[ "MIT" ]
null
null
null
musicplayer/buttons.py
Gabe-Corral/Music_Player
9352266aa86e5927e4a603b6238cea4745cc6b26
[ "MIT" ]
null
null
null
import tkinter as tk from PIL import ImageTk, Image from file_import import FileImport class Buttons: def __init__(self, parent, player): self.player = player self.parent = parent #clean these up unskip_img = ImageTk.PhotoImage(Image.open("assets/unskip.png").resize((25,25))) unskip_btn = tk.Button(parent, image=unskip_img, command=self.player.play_previous) unskip_btn.image = unskip_img unskip_btn.config(highlightbackground="#282828", highlightcolor="#282828", bg='#282828', borderwidth=0) unskip_btn.grid(column=0, row=0) self.pause_img = ImageTk.PhotoImage(Image.open("assets/pause.png").resize((25,25))) self.play_img = ImageTk.PhotoImage(Image.open("assets/play.png").resize((25,25))) self.play_btn = tk.Button(parent, image=self.pause_img, borderwidth=0, bg='#282828', command=self.pause_play) self.play_btn.image = self.pause_img self.play_btn.config(highlightbackground="#282828", highlightcolor="#282828", bg='#282828', borderwidth=0) self.play_btn.grid(column=1, row=0) skip_img = ImageTk.PhotoImage(Image.open("assets/skip.png").resize((25,25))) skip_btn = tk.Button(parent, image=skip_img, command=self.player.play_next) skip_btn.image = skip_img skip_btn.config(highlightbackground="#282828", highlightcolor="#282828", bg='#282828', borderwidth=0) skip_btn.grid(column=2, row=0) volume_down_img = ImageTk.PhotoImage(Image.open("assets/volume_down.png").resize((25,25))) volume_up_btn = tk.Button(parent, image=volume_down_img, command=self.player.volume_control) volume_up_btn.image = volume_down_img volume_up_btn.config(highlightbackground="#282828", highlightcolor="#282828", bg='#282828', borderwidth=0) volume_up_btn.grid(column=3, row=0) volume_up_img = ImageTk.PhotoImage(Image.open("assets/volume_up.png").resize((25,25))) volume_down_btn = tk.Button(parent, image=volume_up_img, command=lambda: self.player.volume_control(True)) volume_down_btn.image = volume_up_img volume_down_btn.config(highlightbackground="#282828", highlightcolor="#282828", bg='#282828', borderwidth=0) volume_down_btn.grid(column=4, row=0) import_btn = tk.Button(parent, text="Import", command=self.import_new_files) import_btn.config(highlightbackground="#282828", highlightcolor="#282828", bg='#282828', borderwidth=0) import_btn.place(x=970, y=0) def import_new_files(self): importer = FileImport(self.parent, tk.Toplevel(self.parent)) def pause_play(self): if self.player.is_playing: self.play_btn.config(image=self.play_img) else: self.play_btn.config(image=self.pause_img) self.player.pause_resume()
44.454545
98
0.673142
import tkinter as tk from PIL import ImageTk, Image from file_import import FileImport class Buttons: def __init__(self, parent, player): self.player = player self.parent = parent unskip_img = ImageTk.PhotoImage(Image.open("assets/unskip.png").resize((25,25))) unskip_btn = tk.Button(parent, image=unskip_img, command=self.player.play_previous) unskip_btn.image = unskip_img unskip_btn.config(highlightbackground="#282828", highlightcolor="#282828", bg='#282828', borderwidth=0) unskip_btn.grid(column=0, row=0) self.pause_img = ImageTk.PhotoImage(Image.open("assets/pause.png").resize((25,25))) self.play_img = ImageTk.PhotoImage(Image.open("assets/play.png").resize((25,25))) self.play_btn = tk.Button(parent, image=self.pause_img, borderwidth=0, bg='#282828', command=self.pause_play) self.play_btn.image = self.pause_img self.play_btn.config(highlightbackground="#282828", highlightcolor="#282828", bg='#282828', borderwidth=0) self.play_btn.grid(column=1, row=0) skip_img = ImageTk.PhotoImage(Image.open("assets/skip.png").resize((25,25))) skip_btn = tk.Button(parent, image=skip_img, command=self.player.play_next) skip_btn.image = skip_img skip_btn.config(highlightbackground="#282828", highlightcolor="#282828", bg='#282828', borderwidth=0) skip_btn.grid(column=2, row=0) volume_down_img = ImageTk.PhotoImage(Image.open("assets/volume_down.png").resize((25,25))) volume_up_btn = tk.Button(parent, image=volume_down_img, command=self.player.volume_control) volume_up_btn.image = volume_down_img volume_up_btn.config(highlightbackground="#282828", highlightcolor="#282828", bg='#282828', borderwidth=0) volume_up_btn.grid(column=3, row=0) volume_up_img = ImageTk.PhotoImage(Image.open("assets/volume_up.png").resize((25,25))) volume_down_btn = tk.Button(parent, image=volume_up_img, command=lambda: self.player.volume_control(True)) volume_down_btn.image = volume_up_img volume_down_btn.config(highlightbackground="#282828", highlightcolor="#282828", bg='#282828', borderwidth=0) volume_down_btn.grid(column=4, row=0) import_btn = tk.Button(parent, text="Import", command=self.import_new_files) import_btn.config(highlightbackground="#282828", highlightcolor="#282828", bg='#282828', borderwidth=0) import_btn.place(x=970, y=0) def import_new_files(self): importer = FileImport(self.parent, tk.Toplevel(self.parent)) def pause_play(self): if self.player.is_playing: self.play_btn.config(image=self.play_img) else: self.play_btn.config(image=self.pause_img) self.player.pause_resume()
true
true
f717ce9240361f4597c503f589f1095a203484a7
20,067
py
Python
tests/wallet/did_wallet/test_did.py
Starcoder0x/chia-blockchain
5b2f5772780d0370f76b0134db6a7fdc7af42862
[ "Apache-2.0" ]
1
2022-03-04T13:12:39.000Z
2022-03-04T13:12:39.000Z
tests/wallet/did_wallet/test_did.py
zcomputerwiz/experiments-blockchain
841754b44494451a9e3e537575eeec431fe533d1
[ "Apache-2.0" ]
null
null
null
tests/wallet/did_wallet/test_did.py
zcomputerwiz/experiments-blockchain
841754b44494451a9e3e537575eeec431fe533d1
[ "Apache-2.0" ]
null
null
null
import asyncio import pytest import pytest_asyncio from chia.simulator.simulator_protocol import FarmNewBlockProtocol from chia.types.peer_info import PeerInfo from chia.util.ints import uint16, uint32, uint64 from tests.setup_nodes import self_hostname, setup_simulators_and_wallets from chia.wallet.did_wallet.did_wallet import DIDWallet from chia.types.blockchain_format.program import Program from blspy import AugSchemeMPL from chia.types.spend_bundle import SpendBundle from chia.consensus.block_rewards import calculate_pool_reward, calculate_base_farmer_reward from tests.time_out_assert import time_out_assert, time_out_assert_not_none pytestmark = pytest.mark.skip("TODO: Fix tests") @pytest.fixture(scope="module") def event_loop(): loop = asyncio.get_event_loop() yield loop class TestDIDWallet: @pytest_asyncio.fixture(scope="function") async def wallet_node(self): async for _ in setup_simulators_and_wallets(1, 1, {}): yield _ @pytest_asyncio.fixture(scope="function") async def two_wallet_nodes(self): async for _ in setup_simulators_and_wallets(1, 2, {}): yield _ @pytest_asyncio.fixture(scope="function") async def three_wallet_nodes(self): async for _ in setup_simulators_and_wallets(1, 3, {}): yield _ @pytest_asyncio.fixture(scope="function") async def two_wallet_nodes_five_freeze(self): async for _ in setup_simulators_and_wallets(1, 2, {}): yield _ @pytest_asyncio.fixture(scope="function") async def three_sim_two_wallets(self): async for _ in setup_simulators_and_wallets(3, 2, {}): yield _ @pytest.mark.asyncio async def test_creation_from_backup_file(self, three_wallet_nodes): num_blocks = 5 full_nodes, wallets = three_wallet_nodes full_node_api = full_nodes[0] full_node_server = full_node_api.server wallet_node_0, server_0 = wallets[0] wallet_node_1, server_1 = wallets[1] wallet_node_2, server_2 = wallets[2] wallet_0 = wallet_node_0.wallet_state_manager.main_wallet wallet_1 = wallet_node_1.wallet_state_manager.main_wallet wallet_2 = wallet_node_2.wallet_state_manager.main_wallet ph = await wallet_0.get_new_puzzlehash() ph1 = await wallet_1.get_new_puzzlehash() ph2 = await wallet_2.get_new_puzzlehash() await server_0.start_client(PeerInfo(self_hostname, uint16(full_node_server._port)), None) await server_1.start_client(PeerInfo(self_hostname, uint16(full_node_server._port)), None) await server_2.start_client(PeerInfo(self_hostname, uint16(full_node_server._port)), None) for i in range(1, num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph)) funds = sum( [ calculate_pool_reward(uint32(i)) + calculate_base_farmer_reward(uint32(i)) for i in range(1, num_blocks - 1) ] ) await time_out_assert(10, wallet_0.get_unconfirmed_balance, funds) await time_out_assert(10, wallet_0.get_confirmed_balance, funds) for i in range(1, num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph1)) for i in range(1, num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph2)) # Wallet1 sets up DIDWallet1 without any backup set async with wallet_node_0.wallet_state_manager.lock: did_wallet_0: DIDWallet = await DIDWallet.create_new_did_wallet( wallet_node_0.wallet_state_manager, wallet_0, uint64(101) ) for i in range(1, num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph)) await time_out_assert(15, did_wallet_0.get_confirmed_balance, 101) await time_out_assert(15, did_wallet_0.get_unconfirmed_balance, 101) await time_out_assert(15, did_wallet_0.get_pending_change_balance, 0) # Wallet1 sets up DIDWallet_1 with DIDWallet_0 as backup backup_ids = [bytes.fromhex(did_wallet_0.get_my_DID())] async with wallet_node_1.wallet_state_manager.lock: did_wallet_1: DIDWallet = await DIDWallet.create_new_did_wallet( wallet_node_1.wallet_state_manager, wallet_1, uint64(201), backup_ids ) for i in range(1, num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph)) await time_out_assert(15, did_wallet_1.get_confirmed_balance, 201) await time_out_assert(15, did_wallet_1.get_unconfirmed_balance, 201) await time_out_assert(15, did_wallet_1.get_pending_change_balance, 0) filename = "test.backup" did_wallet_1.create_backup(filename) # Wallet2 recovers DIDWallet2 to a new set of keys async with wallet_node_2.wallet_state_manager.lock: did_wallet_2 = await DIDWallet.create_new_did_wallet_from_recovery( wallet_node_2.wallet_state_manager, wallet_2, filename ) coins = await did_wallet_1.select_coins(1) coin = coins.copy().pop() assert did_wallet_2.did_info.temp_coin == coin newpuzhash = await did_wallet_2.get_new_inner_hash() pubkey = bytes( (await did_wallet_2.wallet_state_manager.get_unused_derivation_record(did_wallet_2.wallet_info.id)).pubkey ) message_spend_bundle = await did_wallet_0.create_attestment( did_wallet_2.did_info.temp_coin.name(), newpuzhash, pubkey, "test.attest" ) print(f"pubkey: {pubkey}") for i in range(1, num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph)) ( test_info_list, test_message_spend_bundle, ) = await did_wallet_2.load_attest_files_for_recovery_spend(["test.attest"]) assert message_spend_bundle == test_message_spend_bundle await did_wallet_2.recovery_spend( did_wallet_2.did_info.temp_coin, newpuzhash, test_info_list, pubkey, test_message_spend_bundle, ) print(f"pubkey: {did_wallet_2}") for i in range(1, num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph)) await time_out_assert(45, did_wallet_2.get_confirmed_balance, 201) await time_out_assert(45, did_wallet_2.get_unconfirmed_balance, 201) some_ph = 32 * b"\2" await did_wallet_2.create_exit_spend(some_ph) for i in range(1, num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph)) async def get_coins_with_ph(): coins = await full_node_api.full_node.coin_store.get_coin_records_by_puzzle_hash(True, some_ph) if len(coins) == 1: return True return False await time_out_assert(15, get_coins_with_ph, True) await time_out_assert(45, did_wallet_2.get_confirmed_balance, 0) await time_out_assert(45, did_wallet_2.get_unconfirmed_balance, 0) @pytest.mark.asyncio async def test_did_recovery_with_multiple_backup_dids(self, two_wallet_nodes): num_blocks = 5 full_nodes, wallets = two_wallet_nodes full_node_1 = full_nodes[0] server_1 = full_node_1.server wallet_node, server_2 = wallets[0] wallet_node_2, server_3 = wallets[1] wallet = wallet_node.wallet_state_manager.main_wallet wallet2 = wallet_node_2.wallet_state_manager.main_wallet ph = await wallet.get_new_puzzlehash() await server_2.start_client(PeerInfo(self_hostname, uint16(server_1._port)), None) await server_3.start_client(PeerInfo(self_hostname, uint16(server_1._port)), None) for i in range(1, num_blocks): await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph)) funds = sum( [ calculate_pool_reward(uint32(i)) + calculate_base_farmer_reward(uint32(i)) for i in range(1, num_blocks - 1) ] ) await time_out_assert(15, wallet.get_confirmed_balance, funds) async with wallet_node.wallet_state_manager.lock: did_wallet: DIDWallet = await DIDWallet.create_new_did_wallet( wallet_node.wallet_state_manager, wallet, uint64(101) ) ph = await wallet2.get_new_puzzlehash() for i in range(1, num_blocks): await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph)) await time_out_assert(15, did_wallet.get_confirmed_balance, 101) await time_out_assert(15, did_wallet.get_unconfirmed_balance, 101) recovery_list = [bytes.fromhex(did_wallet.get_my_DID())] async with wallet_node_2.wallet_state_manager.lock: did_wallet_2: DIDWallet = await DIDWallet.create_new_did_wallet( wallet_node_2.wallet_state_manager, wallet2, uint64(101), recovery_list ) for i in range(1, num_blocks): await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph)) await time_out_assert(15, did_wallet_2.get_confirmed_balance, 101) await time_out_assert(15, did_wallet_2.get_unconfirmed_balance, 101) assert did_wallet_2.did_info.backup_ids == recovery_list recovery_list.append(bytes.fromhex(did_wallet_2.get_my_DID())) async with wallet_node_2.wallet_state_manager.lock: did_wallet_3: DIDWallet = await DIDWallet.create_new_did_wallet( wallet_node_2.wallet_state_manager, wallet2, uint64(201), recovery_list ) ph2 = await wallet.get_new_puzzlehash() for i in range(1, num_blocks): await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph2)) assert did_wallet_3.did_info.backup_ids == recovery_list await time_out_assert(15, did_wallet_3.get_confirmed_balance, 201) await time_out_assert(15, did_wallet_3.get_unconfirmed_balance, 201) coins = await did_wallet_3.select_coins(1) coin = coins.pop() filename = "test.backup" did_wallet_3.create_backup(filename) async with wallet_node.wallet_state_manager.lock: did_wallet_4 = await DIDWallet.create_new_did_wallet_from_recovery( wallet_node.wallet_state_manager, wallet, filename, ) pubkey = ( await did_wallet_4.wallet_state_manager.get_unused_derivation_record(did_wallet_2.wallet_info.id) ).pubkey new_ph = await did_wallet_4.get_new_inner_hash() message_spend_bundle = await did_wallet.create_attestment(coin.name(), new_ph, pubkey, "test1.attest") message_spend_bundle2 = await did_wallet_2.create_attestment(coin.name(), new_ph, pubkey, "test2.attest") message_spend_bundle = message_spend_bundle.aggregate([message_spend_bundle, message_spend_bundle2]) ( test_info_list, test_message_spend_bundle, ) = await did_wallet_4.load_attest_files_for_recovery_spend(["test1.attest", "test2.attest"]) assert message_spend_bundle == test_message_spend_bundle for i in range(1, num_blocks): await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph2)) await did_wallet_4.recovery_spend(coin, new_ph, test_info_list, pubkey, message_spend_bundle) for i in range(1, num_blocks): await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph2)) await time_out_assert(15, did_wallet_4.get_confirmed_balance, 201) await time_out_assert(15, did_wallet_4.get_unconfirmed_balance, 201) await time_out_assert(15, did_wallet_3.get_confirmed_balance, 0) await time_out_assert(15, did_wallet_3.get_unconfirmed_balance, 0) @pytest.mark.asyncio async def test_did_recovery_with_empty_set(self, two_wallet_nodes): num_blocks = 5 full_nodes, wallets = two_wallet_nodes full_node_1 = full_nodes[0] server_1 = full_node_1.server wallet_node, server_2 = wallets[0] wallet_node_2, server_3 = wallets[1] wallet = wallet_node.wallet_state_manager.main_wallet ph = await wallet.get_new_puzzlehash() await server_2.start_client(PeerInfo(self_hostname, uint16(server_1._port)), None) await server_3.start_client(PeerInfo(self_hostname, uint16(server_1._port)), None) for i in range(1, num_blocks): await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph)) funds = sum( [ calculate_pool_reward(uint32(i)) + calculate_base_farmer_reward(uint32(i)) for i in range(1, num_blocks - 1) ] ) await time_out_assert(15, wallet.get_confirmed_balance, funds) async with wallet_node.wallet_state_manager.lock: did_wallet: DIDWallet = await DIDWallet.create_new_did_wallet( wallet_node.wallet_state_manager, wallet, uint64(101) ) for i in range(1, num_blocks): await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph)) await time_out_assert(15, did_wallet.get_confirmed_balance, 101) await time_out_assert(15, did_wallet.get_unconfirmed_balance, 101) coins = await did_wallet.select_coins(1) coin = coins.pop() info = Program.to([]) pubkey = (await did_wallet.wallet_state_manager.get_unused_derivation_record(did_wallet.wallet_info.id)).pubkey spend_bundle = await did_wallet.recovery_spend( coin, ph, info, pubkey, SpendBundle([], AugSchemeMPL.aggregate([])) ) additions = spend_bundle.additions() assert additions == [] @pytest.mark.asyncio async def test_did_attest_after_recovery(self, two_wallet_nodes): num_blocks = 5 full_nodes, wallets = two_wallet_nodes full_node_1 = full_nodes[0] server_1 = full_node_1.server wallet_node, server_2 = wallets[0] wallet_node_2, server_3 = wallets[1] wallet = wallet_node.wallet_state_manager.main_wallet wallet2 = wallet_node_2.wallet_state_manager.main_wallet ph = await wallet.get_new_puzzlehash() await server_2.start_client(PeerInfo(self_hostname, uint16(server_1._port)), None) await server_3.start_client(PeerInfo(self_hostname, uint16(server_1._port)), None) for i in range(1, num_blocks): await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph)) funds = sum( [ calculate_pool_reward(uint32(i)) + calculate_base_farmer_reward(uint32(i)) for i in range(1, num_blocks - 1) ] ) await time_out_assert(15, wallet.get_confirmed_balance, funds) async with wallet_node.wallet_state_manager.lock: did_wallet: DIDWallet = await DIDWallet.create_new_did_wallet( wallet_node.wallet_state_manager, wallet, uint64(101) ) ph2 = await wallet2.get_new_puzzlehash() for i in range(1, num_blocks): await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph2)) await time_out_assert(15, did_wallet.get_confirmed_balance, 101) await time_out_assert(15, did_wallet.get_unconfirmed_balance, 101) recovery_list = [bytes.fromhex(did_wallet.get_my_DID())] async with wallet_node_2.wallet_state_manager.lock: did_wallet_2: DIDWallet = await DIDWallet.create_new_did_wallet( wallet_node_2.wallet_state_manager, wallet2, uint64(101), recovery_list ) ph = await wallet.get_new_puzzlehash() for i in range(1, num_blocks): await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph)) await time_out_assert(15, did_wallet_2.get_confirmed_balance, 101) await time_out_assert(15, did_wallet_2.get_unconfirmed_balance, 101) assert did_wallet_2.did_info.backup_ids == recovery_list # Update coin with new ID info recovery_list = [bytes.fromhex(did_wallet_2.get_my_DID())] await did_wallet.update_recovery_list(recovery_list, uint64(1)) assert did_wallet.did_info.backup_ids == recovery_list await did_wallet.create_update_spend() for i in range(1, num_blocks): await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph2)) await time_out_assert(15, did_wallet.get_confirmed_balance, 101) await time_out_assert(15, did_wallet.get_unconfirmed_balance, 101) # DID Wallet 2 recovers into DID Wallet 3 with new innerpuz filename = "test.backup" did_wallet_2.create_backup(filename) async with wallet_node.wallet_state_manager.lock: did_wallet_3 = await DIDWallet.create_new_did_wallet_from_recovery( wallet_node.wallet_state_manager, wallet, filename, ) new_ph = await did_wallet_3.get_new_inner_hash() coins = await did_wallet_2.select_coins(1) coin = coins.pop() pubkey = ( await did_wallet_3.wallet_state_manager.get_unused_derivation_record(did_wallet_3.wallet_info.id) ).pubkey message_spend_bundle = await did_wallet.create_attestment(coin.name(), new_ph, pubkey, "test.attest") for i in range(1, num_blocks): await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph2)) ( info, message_spend_bundle, ) = await did_wallet_3.load_attest_files_for_recovery_spend(["test.attest"]) await did_wallet_3.recovery_spend(coin, new_ph, info, pubkey, message_spend_bundle) for i in range(1, num_blocks): await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph)) await time_out_assert(15, did_wallet_3.get_confirmed_balance, 101) await time_out_assert(15, did_wallet_3.get_unconfirmed_balance, 101) # DID Wallet 1 recovery spends into DID Wallet 4 filename = "test.backup" did_wallet.create_backup(filename) async with wallet_node_2.wallet_state_manager.lock: did_wallet_4 = await DIDWallet.create_new_did_wallet_from_recovery( wallet_node_2.wallet_state_manager, wallet2, filename, ) coins = await did_wallet.select_coins(1) coin = coins.pop() new_ph = await did_wallet_4.get_new_inner_hash() pubkey = ( await did_wallet_4.wallet_state_manager.get_unused_derivation_record(did_wallet_4.wallet_info.id) ).pubkey await did_wallet_3.create_attestment(coin.name(), new_ph, pubkey, "test.attest") for i in range(1, num_blocks): await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph2)) ( test_info_list, test_message_spend_bundle, ) = await did_wallet_4.load_attest_files_for_recovery_spend(["test.attest"]) spend_bundle = await did_wallet_4.recovery_spend( coin, new_ph, test_info_list, pubkey, test_message_spend_bundle ) await time_out_assert_not_none(15, full_node_1.full_node.mempool_manager.get_spendbundle, spend_bundle.name()) for i in range(1, num_blocks): await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph)) await time_out_assert(15, did_wallet_4.get_confirmed_balance, 101) await time_out_assert(15, did_wallet_4.get_unconfirmed_balance, 101) await time_out_assert(15, did_wallet.get_confirmed_balance, 0) await time_out_assert(15, did_wallet.get_unconfirmed_balance, 0)
43.623913
119
0.695819
import asyncio import pytest import pytest_asyncio from chia.simulator.simulator_protocol import FarmNewBlockProtocol from chia.types.peer_info import PeerInfo from chia.util.ints import uint16, uint32, uint64 from tests.setup_nodes import self_hostname, setup_simulators_and_wallets from chia.wallet.did_wallet.did_wallet import DIDWallet from chia.types.blockchain_format.program import Program from blspy import AugSchemeMPL from chia.types.spend_bundle import SpendBundle from chia.consensus.block_rewards import calculate_pool_reward, calculate_base_farmer_reward from tests.time_out_assert import time_out_assert, time_out_assert_not_none pytestmark = pytest.mark.skip("TODO: Fix tests") @pytest.fixture(scope="module") def event_loop(): loop = asyncio.get_event_loop() yield loop class TestDIDWallet: @pytest_asyncio.fixture(scope="function") async def wallet_node(self): async for _ in setup_simulators_and_wallets(1, 1, {}): yield _ @pytest_asyncio.fixture(scope="function") async def two_wallet_nodes(self): async for _ in setup_simulators_and_wallets(1, 2, {}): yield _ @pytest_asyncio.fixture(scope="function") async def three_wallet_nodes(self): async for _ in setup_simulators_and_wallets(1, 3, {}): yield _ @pytest_asyncio.fixture(scope="function") async def two_wallet_nodes_five_freeze(self): async for _ in setup_simulators_and_wallets(1, 2, {}): yield _ @pytest_asyncio.fixture(scope="function") async def three_sim_two_wallets(self): async for _ in setup_simulators_and_wallets(3, 2, {}): yield _ @pytest.mark.asyncio async def test_creation_from_backup_file(self, three_wallet_nodes): num_blocks = 5 full_nodes, wallets = three_wallet_nodes full_node_api = full_nodes[0] full_node_server = full_node_api.server wallet_node_0, server_0 = wallets[0] wallet_node_1, server_1 = wallets[1] wallet_node_2, server_2 = wallets[2] wallet_0 = wallet_node_0.wallet_state_manager.main_wallet wallet_1 = wallet_node_1.wallet_state_manager.main_wallet wallet_2 = wallet_node_2.wallet_state_manager.main_wallet ph = await wallet_0.get_new_puzzlehash() ph1 = await wallet_1.get_new_puzzlehash() ph2 = await wallet_2.get_new_puzzlehash() await server_0.start_client(PeerInfo(self_hostname, uint16(full_node_server._port)), None) await server_1.start_client(PeerInfo(self_hostname, uint16(full_node_server._port)), None) await server_2.start_client(PeerInfo(self_hostname, uint16(full_node_server._port)), None) for i in range(1, num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph)) funds = sum( [ calculate_pool_reward(uint32(i)) + calculate_base_farmer_reward(uint32(i)) for i in range(1, num_blocks - 1) ] ) await time_out_assert(10, wallet_0.get_unconfirmed_balance, funds) await time_out_assert(10, wallet_0.get_confirmed_balance, funds) for i in range(1, num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph1)) for i in range(1, num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph2)) async with wallet_node_0.wallet_state_manager.lock: did_wallet_0: DIDWallet = await DIDWallet.create_new_did_wallet( wallet_node_0.wallet_state_manager, wallet_0, uint64(101) ) for i in range(1, num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph)) await time_out_assert(15, did_wallet_0.get_confirmed_balance, 101) await time_out_assert(15, did_wallet_0.get_unconfirmed_balance, 101) await time_out_assert(15, did_wallet_0.get_pending_change_balance, 0) backup_ids = [bytes.fromhex(did_wallet_0.get_my_DID())] async with wallet_node_1.wallet_state_manager.lock: did_wallet_1: DIDWallet = await DIDWallet.create_new_did_wallet( wallet_node_1.wallet_state_manager, wallet_1, uint64(201), backup_ids ) for i in range(1, num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph)) await time_out_assert(15, did_wallet_1.get_confirmed_balance, 201) await time_out_assert(15, did_wallet_1.get_unconfirmed_balance, 201) await time_out_assert(15, did_wallet_1.get_pending_change_balance, 0) filename = "test.backup" did_wallet_1.create_backup(filename) async with wallet_node_2.wallet_state_manager.lock: did_wallet_2 = await DIDWallet.create_new_did_wallet_from_recovery( wallet_node_2.wallet_state_manager, wallet_2, filename ) coins = await did_wallet_1.select_coins(1) coin = coins.copy().pop() assert did_wallet_2.did_info.temp_coin == coin newpuzhash = await did_wallet_2.get_new_inner_hash() pubkey = bytes( (await did_wallet_2.wallet_state_manager.get_unused_derivation_record(did_wallet_2.wallet_info.id)).pubkey ) message_spend_bundle = await did_wallet_0.create_attestment( did_wallet_2.did_info.temp_coin.name(), newpuzhash, pubkey, "test.attest" ) print(f"pubkey: {pubkey}") for i in range(1, num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph)) ( test_info_list, test_message_spend_bundle, ) = await did_wallet_2.load_attest_files_for_recovery_spend(["test.attest"]) assert message_spend_bundle == test_message_spend_bundle await did_wallet_2.recovery_spend( did_wallet_2.did_info.temp_coin, newpuzhash, test_info_list, pubkey, test_message_spend_bundle, ) print(f"pubkey: {did_wallet_2}") for i in range(1, num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph)) await time_out_assert(45, did_wallet_2.get_confirmed_balance, 201) await time_out_assert(45, did_wallet_2.get_unconfirmed_balance, 201) some_ph = 32 * b"\2" await did_wallet_2.create_exit_spend(some_ph) for i in range(1, num_blocks): await full_node_api.farm_new_transaction_block(FarmNewBlockProtocol(ph)) async def get_coins_with_ph(): coins = await full_node_api.full_node.coin_store.get_coin_records_by_puzzle_hash(True, some_ph) if len(coins) == 1: return True return False await time_out_assert(15, get_coins_with_ph, True) await time_out_assert(45, did_wallet_2.get_confirmed_balance, 0) await time_out_assert(45, did_wallet_2.get_unconfirmed_balance, 0) @pytest.mark.asyncio async def test_did_recovery_with_multiple_backup_dids(self, two_wallet_nodes): num_blocks = 5 full_nodes, wallets = two_wallet_nodes full_node_1 = full_nodes[0] server_1 = full_node_1.server wallet_node, server_2 = wallets[0] wallet_node_2, server_3 = wallets[1] wallet = wallet_node.wallet_state_manager.main_wallet wallet2 = wallet_node_2.wallet_state_manager.main_wallet ph = await wallet.get_new_puzzlehash() await server_2.start_client(PeerInfo(self_hostname, uint16(server_1._port)), None) await server_3.start_client(PeerInfo(self_hostname, uint16(server_1._port)), None) for i in range(1, num_blocks): await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph)) funds = sum( [ calculate_pool_reward(uint32(i)) + calculate_base_farmer_reward(uint32(i)) for i in range(1, num_blocks - 1) ] ) await time_out_assert(15, wallet.get_confirmed_balance, funds) async with wallet_node.wallet_state_manager.lock: did_wallet: DIDWallet = await DIDWallet.create_new_did_wallet( wallet_node.wallet_state_manager, wallet, uint64(101) ) ph = await wallet2.get_new_puzzlehash() for i in range(1, num_blocks): await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph)) await time_out_assert(15, did_wallet.get_confirmed_balance, 101) await time_out_assert(15, did_wallet.get_unconfirmed_balance, 101) recovery_list = [bytes.fromhex(did_wallet.get_my_DID())] async with wallet_node_2.wallet_state_manager.lock: did_wallet_2: DIDWallet = await DIDWallet.create_new_did_wallet( wallet_node_2.wallet_state_manager, wallet2, uint64(101), recovery_list ) for i in range(1, num_blocks): await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph)) await time_out_assert(15, did_wallet_2.get_confirmed_balance, 101) await time_out_assert(15, did_wallet_2.get_unconfirmed_balance, 101) assert did_wallet_2.did_info.backup_ids == recovery_list recovery_list.append(bytes.fromhex(did_wallet_2.get_my_DID())) async with wallet_node_2.wallet_state_manager.lock: did_wallet_3: DIDWallet = await DIDWallet.create_new_did_wallet( wallet_node_2.wallet_state_manager, wallet2, uint64(201), recovery_list ) ph2 = await wallet.get_new_puzzlehash() for i in range(1, num_blocks): await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph2)) assert did_wallet_3.did_info.backup_ids == recovery_list await time_out_assert(15, did_wallet_3.get_confirmed_balance, 201) await time_out_assert(15, did_wallet_3.get_unconfirmed_balance, 201) coins = await did_wallet_3.select_coins(1) coin = coins.pop() filename = "test.backup" did_wallet_3.create_backup(filename) async with wallet_node.wallet_state_manager.lock: did_wallet_4 = await DIDWallet.create_new_did_wallet_from_recovery( wallet_node.wallet_state_manager, wallet, filename, ) pubkey = ( await did_wallet_4.wallet_state_manager.get_unused_derivation_record(did_wallet_2.wallet_info.id) ).pubkey new_ph = await did_wallet_4.get_new_inner_hash() message_spend_bundle = await did_wallet.create_attestment(coin.name(), new_ph, pubkey, "test1.attest") message_spend_bundle2 = await did_wallet_2.create_attestment(coin.name(), new_ph, pubkey, "test2.attest") message_spend_bundle = message_spend_bundle.aggregate([message_spend_bundle, message_spend_bundle2]) ( test_info_list, test_message_spend_bundle, ) = await did_wallet_4.load_attest_files_for_recovery_spend(["test1.attest", "test2.attest"]) assert message_spend_bundle == test_message_spend_bundle for i in range(1, num_blocks): await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph2)) await did_wallet_4.recovery_spend(coin, new_ph, test_info_list, pubkey, message_spend_bundle) for i in range(1, num_blocks): await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph2)) await time_out_assert(15, did_wallet_4.get_confirmed_balance, 201) await time_out_assert(15, did_wallet_4.get_unconfirmed_balance, 201) await time_out_assert(15, did_wallet_3.get_confirmed_balance, 0) await time_out_assert(15, did_wallet_3.get_unconfirmed_balance, 0) @pytest.mark.asyncio async def test_did_recovery_with_empty_set(self, two_wallet_nodes): num_blocks = 5 full_nodes, wallets = two_wallet_nodes full_node_1 = full_nodes[0] server_1 = full_node_1.server wallet_node, server_2 = wallets[0] wallet_node_2, server_3 = wallets[1] wallet = wallet_node.wallet_state_manager.main_wallet ph = await wallet.get_new_puzzlehash() await server_2.start_client(PeerInfo(self_hostname, uint16(server_1._port)), None) await server_3.start_client(PeerInfo(self_hostname, uint16(server_1._port)), None) for i in range(1, num_blocks): await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph)) funds = sum( [ calculate_pool_reward(uint32(i)) + calculate_base_farmer_reward(uint32(i)) for i in range(1, num_blocks - 1) ] ) await time_out_assert(15, wallet.get_confirmed_balance, funds) async with wallet_node.wallet_state_manager.lock: did_wallet: DIDWallet = await DIDWallet.create_new_did_wallet( wallet_node.wallet_state_manager, wallet, uint64(101) ) for i in range(1, num_blocks): await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph)) await time_out_assert(15, did_wallet.get_confirmed_balance, 101) await time_out_assert(15, did_wallet.get_unconfirmed_balance, 101) coins = await did_wallet.select_coins(1) coin = coins.pop() info = Program.to([]) pubkey = (await did_wallet.wallet_state_manager.get_unused_derivation_record(did_wallet.wallet_info.id)).pubkey spend_bundle = await did_wallet.recovery_spend( coin, ph, info, pubkey, SpendBundle([], AugSchemeMPL.aggregate([])) ) additions = spend_bundle.additions() assert additions == [] @pytest.mark.asyncio async def test_did_attest_after_recovery(self, two_wallet_nodes): num_blocks = 5 full_nodes, wallets = two_wallet_nodes full_node_1 = full_nodes[0] server_1 = full_node_1.server wallet_node, server_2 = wallets[0] wallet_node_2, server_3 = wallets[1] wallet = wallet_node.wallet_state_manager.main_wallet wallet2 = wallet_node_2.wallet_state_manager.main_wallet ph = await wallet.get_new_puzzlehash() await server_2.start_client(PeerInfo(self_hostname, uint16(server_1._port)), None) await server_3.start_client(PeerInfo(self_hostname, uint16(server_1._port)), None) for i in range(1, num_blocks): await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph)) funds = sum( [ calculate_pool_reward(uint32(i)) + calculate_base_farmer_reward(uint32(i)) for i in range(1, num_blocks - 1) ] ) await time_out_assert(15, wallet.get_confirmed_balance, funds) async with wallet_node.wallet_state_manager.lock: did_wallet: DIDWallet = await DIDWallet.create_new_did_wallet( wallet_node.wallet_state_manager, wallet, uint64(101) ) ph2 = await wallet2.get_new_puzzlehash() for i in range(1, num_blocks): await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph2)) await time_out_assert(15, did_wallet.get_confirmed_balance, 101) await time_out_assert(15, did_wallet.get_unconfirmed_balance, 101) recovery_list = [bytes.fromhex(did_wallet.get_my_DID())] async with wallet_node_2.wallet_state_manager.lock: did_wallet_2: DIDWallet = await DIDWallet.create_new_did_wallet( wallet_node_2.wallet_state_manager, wallet2, uint64(101), recovery_list ) ph = await wallet.get_new_puzzlehash() for i in range(1, num_blocks): await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph)) await time_out_assert(15, did_wallet_2.get_confirmed_balance, 101) await time_out_assert(15, did_wallet_2.get_unconfirmed_balance, 101) assert did_wallet_2.did_info.backup_ids == recovery_list recovery_list = [bytes.fromhex(did_wallet_2.get_my_DID())] await did_wallet.update_recovery_list(recovery_list, uint64(1)) assert did_wallet.did_info.backup_ids == recovery_list await did_wallet.create_update_spend() for i in range(1, num_blocks): await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph2)) await time_out_assert(15, did_wallet.get_confirmed_balance, 101) await time_out_assert(15, did_wallet.get_unconfirmed_balance, 101) filename = "test.backup" did_wallet_2.create_backup(filename) async with wallet_node.wallet_state_manager.lock: did_wallet_3 = await DIDWallet.create_new_did_wallet_from_recovery( wallet_node.wallet_state_manager, wallet, filename, ) new_ph = await did_wallet_3.get_new_inner_hash() coins = await did_wallet_2.select_coins(1) coin = coins.pop() pubkey = ( await did_wallet_3.wallet_state_manager.get_unused_derivation_record(did_wallet_3.wallet_info.id) ).pubkey message_spend_bundle = await did_wallet.create_attestment(coin.name(), new_ph, pubkey, "test.attest") for i in range(1, num_blocks): await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph2)) ( info, message_spend_bundle, ) = await did_wallet_3.load_attest_files_for_recovery_spend(["test.attest"]) await did_wallet_3.recovery_spend(coin, new_ph, info, pubkey, message_spend_bundle) for i in range(1, num_blocks): await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph)) await time_out_assert(15, did_wallet_3.get_confirmed_balance, 101) await time_out_assert(15, did_wallet_3.get_unconfirmed_balance, 101) filename = "test.backup" did_wallet.create_backup(filename) async with wallet_node_2.wallet_state_manager.lock: did_wallet_4 = await DIDWallet.create_new_did_wallet_from_recovery( wallet_node_2.wallet_state_manager, wallet2, filename, ) coins = await did_wallet.select_coins(1) coin = coins.pop() new_ph = await did_wallet_4.get_new_inner_hash() pubkey = ( await did_wallet_4.wallet_state_manager.get_unused_derivation_record(did_wallet_4.wallet_info.id) ).pubkey await did_wallet_3.create_attestment(coin.name(), new_ph, pubkey, "test.attest") for i in range(1, num_blocks): await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph2)) ( test_info_list, test_message_spend_bundle, ) = await did_wallet_4.load_attest_files_for_recovery_spend(["test.attest"]) spend_bundle = await did_wallet_4.recovery_spend( coin, new_ph, test_info_list, pubkey, test_message_spend_bundle ) await time_out_assert_not_none(15, full_node_1.full_node.mempool_manager.get_spendbundle, spend_bundle.name()) for i in range(1, num_blocks): await full_node_1.farm_new_transaction_block(FarmNewBlockProtocol(ph)) await time_out_assert(15, did_wallet_4.get_confirmed_balance, 101) await time_out_assert(15, did_wallet_4.get_unconfirmed_balance, 101) await time_out_assert(15, did_wallet.get_confirmed_balance, 0) await time_out_assert(15, did_wallet.get_unconfirmed_balance, 0)
true
true
f717cec2bb576f4d7ab0e2542c02f2f63a1c8e21
582
py
Python
src/models/gender.py
evdhout/learn_students
4fe10df13065ae7c46930cb69fa46851c1dca9e6
[ "MIT" ]
null
null
null
src/models/gender.py
evdhout/learn_students
4fe10df13065ae7c46930cb69fa46851c1dca9e6
[ "MIT" ]
null
null
null
src/models/gender.py
evdhout/learn_students
4fe10df13065ae7c46930cb69fa46851c1dca9e6
[ "MIT" ]
null
null
null
class Gender: NEUTRAL = 1 FEMALE = 2 MALE = 3 GENDER_STRINGS = {NEUTRAL: "neutral", FEMALE: "female", MALE: "male" } def __init__(self, gender: int = 1): self.gender: int = gender def __str__(self): return self.GENDER_STRINGS[_(self.gender)] def __eq__(self, other): if isinstance(other, Gender): return self.gender == other.gender elif isinstance(other, int): return self.gender == other else: return False
24.25
50
0.512027
class Gender: NEUTRAL = 1 FEMALE = 2 MALE = 3 GENDER_STRINGS = {NEUTRAL: "neutral", FEMALE: "female", MALE: "male" } def __init__(self, gender: int = 1): self.gender: int = gender def __str__(self): return self.GENDER_STRINGS[_(self.gender)] def __eq__(self, other): if isinstance(other, Gender): return self.gender == other.gender elif isinstance(other, int): return self.gender == other else: return False
true
true
f717cfc7cab0f458b15996bf3bf047fcffdef11f
3,950
py
Python
test/functional/feature_minchainwork.py
bontecoin/bontecoin-core
a7c368cf25339b9495e94651ee2a036e4f3068ae
[ "MIT" ]
null
null
null
test/functional/feature_minchainwork.py
bontecoin/bontecoin-core
a7c368cf25339b9495e94651ee2a036e4f3068ae
[ "MIT" ]
null
null
null
test/functional/feature_minchainwork.py
bontecoin/bontecoin-core
a7c368cf25339b9495e94651ee2a036e4f3068ae
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # Copyright (c) 2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test logic for setting nMinimumChainWork on command line. Nodes don't consider themselves out of "initial block download" until their active chain has more work than nMinimumChainWork. Nodes don't download blocks from a peer unless the peer's best known block has more work than nMinimumChainWork. While in initial block download, nodes won't relay blocks to their peers, so test that this parameter functions as intended by verifying that block relay only succeeds past a given node once its nMinimumChainWork has been exceeded. """ import time from test_framework.test_framework import BontecoinTestFramework from test_framework.util import connect_nodes, assert_equal # 2 hashes required per regtest block (with no difficulty adjustment) REGTEST_WORK_PER_BLOCK = 2 class MinimumChainWorkTest(BontecoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 3 self.extra_args = [[], ["-minimumchainwork=0x65"], ["-minimumchainwork=0x65"]] self.node_min_work = [0, 101, 101] def setup_network(self): # This test relies on the chain setup being: # node0 <- node1 <- node2 # Before leaving IBD, nodes prefer to download blocks from outbound # peers, so ensure that we're mining on an outbound peer and testing # block relay to inbound peers. self.setup_nodes() for i in range(self.num_nodes-1): connect_nodes(self.nodes[i+1], i) def run_test(self): # Start building a chain on node0. node2 shouldn't be able to sync until node1's # minchainwork is exceeded starting_chain_work = REGTEST_WORK_PER_BLOCK # Genesis block's work self.log.info("Testing relay across node %d (minChainWork = %d)", 1, self.node_min_work[1]) starting_blockcount = self.nodes[2].getblockcount() num_blocks_to_generate = int((self.node_min_work[1] - starting_chain_work) / REGTEST_WORK_PER_BLOCK) self.log.info("Generating %d blocks on node0", num_blocks_to_generate) hashes = self.nodes[0].generate(num_blocks_to_generate) self.log.info("Node0 current chain work: %s", self.nodes[0].getblockheader(hashes[-1])['chainwork']) # Sleep a few seconds and verify that node2 didn't get any new blocks # or headers. We sleep, rather than sync_blocks(node0, node1) because # it's reasonable either way for node1 to get the blocks, or not get # them (since they're below node1's minchainwork). time.sleep(3) self.log.info("Verifying node 2 has no more blocks than before") self.log.info("Blockcounts: %s", [n.getblockcount() for n in self.nodes]) # Node2 shouldn't have any new headers yet, because node1 should not # have relayed anything. assert_equal(len(self.nodes[2].getchaintips()), 1) assert_equal(self.nodes[2].getchaintips()[0]['height'], 0) assert self.nodes[1].getbestblockhash() != self.nodes[0].getbestblockhash() assert_equal(self.nodes[2].getblockcount(), starting_blockcount) self.log.info("Generating one more block") self.nodes[0].generate(1) self.log.info("Verifying nodes are all synced") # Because nodes in regtest are all manual connections (eg using # addnode), node1 should not have disconnected node0. If not for that, # we'd expect node1 to have disconnected node0 for serving an # insufficient work chain, in which case we'd need to reconnect them to # continue the test. self.sync_all() self.log.info("Blockcounts: %s", [n.getblockcount() for n in self.nodes]) if __name__ == '__main__': MinimumChainWorkTest().main()
43.888889
108
0.702278
import time from test_framework.test_framework import BontecoinTestFramework from test_framework.util import connect_nodes, assert_equal REGTEST_WORK_PER_BLOCK = 2 class MinimumChainWorkTest(BontecoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 3 self.extra_args = [[], ["-minimumchainwork=0x65"], ["-minimumchainwork=0x65"]] self.node_min_work = [0, 101, 101] def setup_network(self): # block relay to inbound peers. self.setup_nodes() for i in range(self.num_nodes-1): connect_nodes(self.nodes[i+1], i) def run_test(self): # Start building a chain on node0. node2 shouldn't be able to sync until node1's # minchainwork is exceeded starting_chain_work = REGTEST_WORK_PER_BLOCK # Genesis block's work self.log.info("Testing relay across node %d (minChainWork = %d)", 1, self.node_min_work[1]) starting_blockcount = self.nodes[2].getblockcount() num_blocks_to_generate = int((self.node_min_work[1] - starting_chain_work) / REGTEST_WORK_PER_BLOCK) self.log.info("Generating %d blocks on node0", num_blocks_to_generate) hashes = self.nodes[0].generate(num_blocks_to_generate) self.log.info("Node0 current chain work: %s", self.nodes[0].getblockheader(hashes[-1])['chainwork']) # or headers. We sleep, rather than sync_blocks(node0, node1) because # it's reasonable either way for node1 to get the blocks, or not get time.sleep(3) self.log.info("Verifying node 2 has no more blocks than before") self.log.info("Blockcounts: %s", [n.getblockcount() for n in self.nodes]) # have relayed anything. assert_equal(len(self.nodes[2].getchaintips()), 1) assert_equal(self.nodes[2].getchaintips()[0]['height'], 0) assert self.nodes[1].getbestblockhash() != self.nodes[0].getbestblockhash() assert_equal(self.nodes[2].getblockcount(), starting_blockcount) self.log.info("Generating one more block") self.nodes[0].generate(1) self.log.info("Verifying nodes are all synced") # Because nodes in regtest are all manual connections (eg using # addnode), node1 should not have disconnected node0. If not for that, # we'd expect node1 to have disconnected node0 for serving an # continue the test. self.sync_all() self.log.info("Blockcounts: %s", [n.getblockcount() for n in self.nodes]) if __name__ == '__main__': MinimumChainWorkTest().main()
true
true
f717cfc9fd68c709b7614798b5f73cd888527fbd
2,681
py
Python
data/LSSVM.py
tejas-9er/SVM-vs-LSSVM
e44f63458680c39df370ddfcdf22e8c450d23128
[ "MIT" ]
5
2019-12-16T03:29:24.000Z
2022-02-14T01:26:28.000Z
data/LSSVM.py
tejas-9er/SVM-vs-LSSVM
e44f63458680c39df370ddfcdf22e8c450d23128
[ "MIT" ]
null
null
null
data/LSSVM.py
tejas-9er/SVM-vs-LSSVM
e44f63458680c39df370ddfcdf22e8c450d23128
[ "MIT" ]
5
2019-06-18T06:59:35.000Z
2020-12-19T11:10:56.000Z
import numpy as np import scipy from scipy.sparse import linalg from sklearn.metrics import accuracy_score class LSSVM: def __init__(self, kernel = 'linear', C = 1.0,gamma = 1.0, d = 2.0): kernels = { 'rbf':self.rbf, 'poly':self.polynomial, 'linear':self.linear } self.kernel = kernels[kernel] self.C = C self.gamma = 1.0 self.d = d #Build the gram matrix def build_kernel_matrix(self, X, y): instances, dimensions = X.shape gram_matrix = np.zeros((instances,instances)) #computing the gram matrix, involves going over the dataset and computing pairwise kernel function for i in range(0, instances): for j in range(0, instances): gram_matrix[i, j] = self.kernel(X[i], X[j]) return gram_matrix def fit(self, X, y): self.kernel_matrix = self.build_kernel_matrix(X,y) identity_matrix = np.identity(X.shape[0]) #We wish to solve Ax = B, so we begin by defining the matrices A, B A = np.zeros((X.shape[0]+1, X.shape[0]+1)) B = np.ones(((X.shape[0]+1,1))) A[0][0] = 0 A[0,1:X.shape[0]+1] = np.hstack((np.ones(X.shape[0]))) A[1:X.shape[0]+1,0] = np.ones(X.shape[0]) A[1:X.shape[0]+1,1:X.shape[0]+1] = self.kernel_matrix + identity_matrix / self.C #B is a column vector. B[0][0] = 0 B[1:X.shape[0]+1,0] = y solution = scipy.sparse.linalg.cg(A,B) self.bias = solution[:-1] solution = solution[:-1] self.support_vector_alphas = [] self.support_vector_labels = [] self.support_vectors = [] for index,alpha in enumerate(solution[0]): if(alpha > 1e-3): self.support_vector_alphas.append(alpha) self.support_vector_labels.append(y[index]) self.support_vectors.append(X[index]) #define kernels def linear(self, x1, x2): return np.dot(x1, x2.T) def polynomial(self, x1, x2): return (np.dot(x1, x2.T) ** self.d) def rbf(self,xi,xj): return np.exp(-self.gamma * np.linalg.norm(xi-xj)**2) def predict(self,X_test): predictions = [] for instance in X_test: for index, sv in enumerate(self.support_vectors): prediction = np.sum(self.support_vector_alphas[index] * self.support_vector_labels[index] * self.kernel(sv,instance) + self.bias) predictions.append(np.sign(prediction).astype(int)) return np.array(predictions)
33.098765
145
0.564342
import numpy as np import scipy from scipy.sparse import linalg from sklearn.metrics import accuracy_score class LSSVM: def __init__(self, kernel = 'linear', C = 1.0,gamma = 1.0, d = 2.0): kernels = { 'rbf':self.rbf, 'poly':self.polynomial, 'linear':self.linear } self.kernel = kernels[kernel] self.C = C self.gamma = 1.0 self.d = d def build_kernel_matrix(self, X, y): instances, dimensions = X.shape gram_matrix = np.zeros((instances,instances)) for i in range(0, instances): for j in range(0, instances): gram_matrix[i, j] = self.kernel(X[i], X[j]) return gram_matrix def fit(self, X, y): self.kernel_matrix = self.build_kernel_matrix(X,y) identity_matrix = np.identity(X.shape[0]) A = np.zeros((X.shape[0]+1, X.shape[0]+1)) B = np.ones(((X.shape[0]+1,1))) A[0][0] = 0 A[0,1:X.shape[0]+1] = np.hstack((np.ones(X.shape[0]))) A[1:X.shape[0]+1,0] = np.ones(X.shape[0]) A[1:X.shape[0]+1,1:X.shape[0]+1] = self.kernel_matrix + identity_matrix / self.C B[0][0] = 0 B[1:X.shape[0]+1,0] = y solution = scipy.sparse.linalg.cg(A,B) self.bias = solution[:-1] solution = solution[:-1] self.support_vector_alphas = [] self.support_vector_labels = [] self.support_vectors = [] for index,alpha in enumerate(solution[0]): if(alpha > 1e-3): self.support_vector_alphas.append(alpha) self.support_vector_labels.append(y[index]) self.support_vectors.append(X[index]) def linear(self, x1, x2): return np.dot(x1, x2.T) def polynomial(self, x1, x2): return (np.dot(x1, x2.T) ** self.d) def rbf(self,xi,xj): return np.exp(-self.gamma * np.linalg.norm(xi-xj)**2) def predict(self,X_test): predictions = [] for instance in X_test: for index, sv in enumerate(self.support_vectors): prediction = np.sum(self.support_vector_alphas[index] * self.support_vector_labels[index] * self.kernel(sv,instance) + self.bias) predictions.append(np.sign(prediction).astype(int)) return np.array(predictions)
true
true
f717cfcf1da0e79443c3060c50aa0097551bd7be
1,034
py
Python
p56_Merge_Intervals.py
bzhou26/leetcode_sol
82506521e2cc412f96cd1dfc3c8c3ab635f67f73
[ "MIT" ]
null
null
null
p56_Merge_Intervals.py
bzhou26/leetcode_sol
82506521e2cc412f96cd1dfc3c8c3ab635f67f73
[ "MIT" ]
null
null
null
p56_Merge_Intervals.py
bzhou26/leetcode_sol
82506521e2cc412f96cd1dfc3c8c3ab635f67f73
[ "MIT" ]
null
null
null
''' - Leetcode problem: 56 - Difficulty: Medium - Brief problem description: Given a collection of intervals, merge all overlapping intervals. Example 1: Input: [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. Example 2: Input: [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals [1,4] and [4,5] are considered overlapping. NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature. - Solution Summary: - Used Resources: --- Bo Zhou ''' class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: hp = [] for i in intervals: heapq.heappush(hp, i) result = [] while hp: inter = heapq.heappop(hp) if result and inter[0] <= result[-1][1]: result[-1][1] = max(inter[1], result[-1][1]) else: result.append(inter) return result
22.478261
112
0.597679
class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: hp = [] for i in intervals: heapq.heappush(hp, i) result = [] while hp: inter = heapq.heappop(hp) if result and inter[0] <= result[-1][1]: result[-1][1] = max(inter[1], result[-1][1]) else: result.append(inter) return result
true
true
f717cff9e873f6d4ee6ab179e6d452349b4cd40a
1,032
py
Python
env/Lib/site-packages/OpenGL/raw/EGL/EXT/device_query.py
5gconnectedbike/Navio2
8c3f2b5d8bbbcea1fc08739945183c12b206712c
[ "BSD-3-Clause" ]
210
2016-04-09T14:26:00.000Z
2022-03-25T18:36:19.000Z
env/Lib/site-packages/OpenGL/raw/EGL/EXT/device_query.py
5gconnectedbike/Navio2
8c3f2b5d8bbbcea1fc08739945183c12b206712c
[ "BSD-3-Clause" ]
72
2016-09-04T09:30:19.000Z
2022-03-27T17:06:53.000Z
env/Lib/site-packages/OpenGL/raw/EGL/EXT/device_query.py
5gconnectedbike/Navio2
8c3f2b5d8bbbcea1fc08739945183c12b206712c
[ "BSD-3-Clause" ]
64
2016-04-09T14:26:49.000Z
2022-03-21T11:19:47.000Z
'''Autogenerated by xml_generate script, do not edit!''' from OpenGL import platform as _p, arrays # Code generation uses this from OpenGL.raw.EGL import _types as _cs # End users want this... from OpenGL.raw.EGL._types import * from OpenGL.raw.EGL import _errors from OpenGL.constant import Constant as _C import ctypes _EXTENSION_NAME = 'EGL_EXT_device_query' def _f( function ): return _p.createFunction( function,_p.PLATFORM.EGL,'EGL_EXT_device_query',error_checker=_errors._error_checker) EGL_BAD_DEVICE_EXT=_C('EGL_BAD_DEVICE_EXT',0x322B) EGL_DEVICE_EXT=_C('EGL_DEVICE_EXT',0x322C) # EGL_NO_DEVICE_EXT=_C('EGL_NO_DEVICE_EXT',((EGLDeviceEXT)(0))) @_f @_p.types(_cs.EGLBoolean,_cs.EGLDeviceEXT,_cs.EGLint,arrays.EGLAttribArray) def eglQueryDeviceAttribEXT(device,attribute,value):pass @_f @_p.types(ctypes.c_char_p,_cs.EGLDeviceEXT,_cs.EGLint) def eglQueryDeviceStringEXT(device,name):pass @_f @_p.types(_cs.EGLBoolean,_cs.EGLDisplay,_cs.EGLint,arrays.EGLAttribArray) def eglQueryDisplayAttribEXT(dpy,attribute,value):pass
39.692308
115
0.814922
from OpenGL import platform as _p, arrays from OpenGL.raw.EGL import _types as _cs from OpenGL.raw.EGL._types import * from OpenGL.raw.EGL import _errors from OpenGL.constant import Constant as _C import ctypes _EXTENSION_NAME = 'EGL_EXT_device_query' def _f( function ): return _p.createFunction( function,_p.PLATFORM.EGL,'EGL_EXT_device_query',error_checker=_errors._error_checker) EGL_BAD_DEVICE_EXT=_C('EGL_BAD_DEVICE_EXT',0x322B) EGL_DEVICE_EXT=_C('EGL_DEVICE_EXT',0x322C) @_f @_p.types(_cs.EGLBoolean,_cs.EGLDeviceEXT,_cs.EGLint,arrays.EGLAttribArray) def eglQueryDeviceAttribEXT(device,attribute,value):pass @_f @_p.types(ctypes.c_char_p,_cs.EGLDeviceEXT,_cs.EGLint) def eglQueryDeviceStringEXT(device,name):pass @_f @_p.types(_cs.EGLBoolean,_cs.EGLDisplay,_cs.EGLint,arrays.EGLAttribArray) def eglQueryDisplayAttribEXT(dpy,attribute,value):pass
true
true
f717d0d34b30202c5d6aa299b38730b144f81368
238
py
Python
chapter1-cam.py
gcruchon/test-opencv
fdf7cb7a86f5606ca6df6170107a0264fbc43e9c
[ "CC0-1.0" ]
null
null
null
chapter1-cam.py
gcruchon/test-opencv
fdf7cb7a86f5606ca6df6170107a0264fbc43e9c
[ "CC0-1.0" ]
null
null
null
chapter1-cam.py
gcruchon/test-opencv
fdf7cb7a86f5606ca6df6170107a0264fbc43e9c
[ "CC0-1.0" ]
null
null
null
import cv2 import numpy as np cap = cv2.VideoCapture(0) kernel = np.ones((5, 5), np.uint8) while True: success, img = cap.read() cv2.imshow("Cam", cv2.Canny(img, 100, 100)) if cv2.waitKey(1) & 0xFF == ord('q'): break
21.636364
47
0.609244
import cv2 import numpy as np cap = cv2.VideoCapture(0) kernel = np.ones((5, 5), np.uint8) while True: success, img = cap.read() cv2.imshow("Cam", cv2.Canny(img, 100, 100)) if cv2.waitKey(1) & 0xFF == ord('q'): break
true
true
f717d2356d90cde15cbb3d0d6e7bc7ef270af89b
320
py
Python
Beecrowd/1187.py
Gugarauj07/Algorithms
21c0fe96c1c870a01644d398c446182ced37eb19
[ "MIT" ]
null
null
null
Beecrowd/1187.py
Gugarauj07/Algorithms
21c0fe96c1c870a01644d398c446182ced37eb19
[ "MIT" ]
null
null
null
Beecrowd/1187.py
Gugarauj07/Algorithms
21c0fe96c1c870a01644d398c446182ced37eb19
[ "MIT" ]
null
null
null
O = input() soma = count = 0 for linha in range(12): for coluna in range(12): num = float(input()) if linha <= 4 and (10 - linha) >= coluna > linha: soma += num count += 1 if O == "S": print(f"{soma:.1f}") elif O == "M": media = soma / count print(f"{media:.1f}")
22.857143
57
0.484375
O = input() soma = count = 0 for linha in range(12): for coluna in range(12): num = float(input()) if linha <= 4 and (10 - linha) >= coluna > linha: soma += num count += 1 if O == "S": print(f"{soma:.1f}") elif O == "M": media = soma / count print(f"{media:.1f}")
true
true
f717d265ddfccca7c0bcef14a21dd104634baabd
189
py
Python
Lesson/lesson-oo-415.py
v-v-tarasov/python-my-lesson
57f8985cdfe9d9439452d6d3d0f89cf4bfbf2d14
[ "MIT" ]
null
null
null
Lesson/lesson-oo-415.py
v-v-tarasov/python-my-lesson
57f8985cdfe9d9439452d6d3d0f89cf4bfbf2d14
[ "MIT" ]
null
null
null
Lesson/lesson-oo-415.py
v-v-tarasov/python-my-lesson
57f8985cdfe9d9439452d6d3d0f89cf4bfbf2d14
[ "MIT" ]
null
null
null
def isPointInSquare(x, y): return 1.0 >= x >= -1.0 and 1.0 >= y >= -1.0 x = float(input()) y = float(input()) if isPointInSquare(x, y) == True: print('YES') else: print('NO')
17.181818
48
0.544974
def isPointInSquare(x, y): return 1.0 >= x >= -1.0 and 1.0 >= y >= -1.0 x = float(input()) y = float(input()) if isPointInSquare(x, y) == True: print('YES') else: print('NO')
true
true
f717d32ab2f0db9bf60e9f86574ade09c2ab6e47
208
py
Python
3_Django/PROJECT_NAME/APP_NAME/urls.py
kevinbeirne1/CS50-course
b6247cdea50890369a5e0fd60017980643bf6e37
[ "MIT" ]
1
2021-08-31T20:52:41.000Z
2021-08-31T20:52:41.000Z
3_Django/PROJECT_NAME/APP_NAME/urls.py
kevinbeirne1/CS50-course
b6247cdea50890369a5e0fd60017980643bf6e37
[ "MIT" ]
null
null
null
3_Django/PROJECT_NAME/APP_NAME/urls.py
kevinbeirne1/CS50-course
b6247cdea50890369a5e0fd60017980643bf6e37
[ "MIT" ]
null
null
null
from django.urls import path from . import views urlpatterns = [ path('', views.index, name="index"), path('<str:name>', views.greet, name="greet"), # path('david/', views.david, name="david"), ]
26
50
0.629808
from django.urls import path from . import views urlpatterns = [ path('', views.index, name="index"), path('<str:name>', views.greet, name="greet"), ]
true
true
f717d4456b785afc6a7d4ab258496baf58e1cea9
2,004
py
Python
diary/forms.py
j3ygh/ctdb
3c4b90c5265125fc37aa9ac569b7f39ffd5b13c9
[ "MIT" ]
1
2021-12-27T02:18:19.000Z
2021-12-27T02:18:19.000Z
diary/forms.py
j3ygh/ctdb
3c4b90c5265125fc37aa9ac569b7f39ffd5b13c9
[ "MIT" ]
null
null
null
diary/forms.py
j3ygh/ctdb
3c4b90c5265125fc37aa9ac569b7f39ffd5b13c9
[ "MIT" ]
1
2022-03-14T06:52:48.000Z
2022-03-14T06:52:48.000Z
from django import forms from django.utils.translation import gettext_lazy as _ from .models import Diary class DiaryModelForm(forms.ModelForm): class Meta: widgets = { 'date': forms.DateInput(attrs={'type': 'date'}), 'daily_record': forms.Textarea(attrs={'rows': 4, 'class': 'ckeditor4'}), 'todo': forms.Textarea(attrs={'rows': 4, 'class': 'ckeditor4'}), 'remark': forms.Textarea(attrs={'rows': 4, 'class': 'ckeditor4'}), 'comment': forms.Textarea(attrs={'rows': 4, 'class': 'ckeditor4', 'readonly': ''}), # TODO: ckeditor4 or not? } model = Diary exclude = ['created_by'] def full_clean(self): super().full_clean() try: self.instance.validate_unique() except forms.ValidationError: self.add_error(field='date', error=_('The diary with this date has already existed.')) class DiaryCommentModelForm(forms.ModelForm): class Meta: widgets = { 'date': forms.DateInput(attrs={'type': 'date', 'readonly': ''}), # Attrs readonly & style="pointer-events: none" make the <select> tag work like a readonly field. 'daily_check': forms.Select(attrs={'readonly': '', 'style': 'pointer-events: none'}), 'daily_record': forms.Textarea(attrs={'rows': 4, 'class': 'ckeditor4', 'readonly': ''}), 'todo': forms.Textarea(attrs={'rows': 4, 'class': 'ckeditor4', 'readonly': ''}), 'remark': forms.Textarea(attrs={'rows': 4, 'class': 'ckeditor4', 'readonly': ''}), 'comment': forms.Textarea(attrs={'rows': 4, 'class': 'ckeditor4'}), # TODO: ckeditor4 or not? } model = Diary exclude = ['created_by'] def full_clean(self): super().full_clean() try: self.instance.validate_unique() except forms.ValidationError: self.add_error(field='date', error=_('The diary with this date has already existed.'))
42.638298
122
0.586826
from django import forms from django.utils.translation import gettext_lazy as _ from .models import Diary class DiaryModelForm(forms.ModelForm): class Meta: widgets = { 'date': forms.DateInput(attrs={'type': 'date'}), 'daily_record': forms.Textarea(attrs={'rows': 4, 'class': 'ckeditor4'}), 'todo': forms.Textarea(attrs={'rows': 4, 'class': 'ckeditor4'}), 'remark': forms.Textarea(attrs={'rows': 4, 'class': 'ckeditor4'}), 'comment': forms.Textarea(attrs={'rows': 4, 'class': 'ckeditor4', 'readonly': ''}), } model = Diary exclude = ['created_by'] def full_clean(self): super().full_clean() try: self.instance.validate_unique() except forms.ValidationError: self.add_error(field='date', error=_('The diary with this date has already existed.')) class DiaryCommentModelForm(forms.ModelForm): class Meta: widgets = { 'date': forms.DateInput(attrs={'type': 'date', 'readonly': ''}), 'daily_check': forms.Select(attrs={'readonly': '', 'style': 'pointer-events: none'}), 'daily_record': forms.Textarea(attrs={'rows': 4, 'class': 'ckeditor4', 'readonly': ''}), 'todo': forms.Textarea(attrs={'rows': 4, 'class': 'ckeditor4', 'readonly': ''}), 'remark': forms.Textarea(attrs={'rows': 4, 'class': 'ckeditor4', 'readonly': ''}), 'comment': forms.Textarea(attrs={'rows': 4, 'class': 'ckeditor4'}), } model = Diary exclude = ['created_by'] def full_clean(self): super().full_clean() try: self.instance.validate_unique() except forms.ValidationError: self.add_error(field='date', error=_('The diary with this date has already existed.'))
true
true