id
int64 0
843k
| repository_name
stringlengths 7
55
| file_path
stringlengths 9
332
| class_name
stringlengths 3
290
| human_written_code
stringlengths 12
4.36M
| class_skeleton
stringlengths 19
2.2M
| total_program_units
int64 1
9.57k
| total_doc_str
int64 0
4.2k
| AvgCountLine
float64 0
7.89k
| AvgCountLineBlank
float64 0
300
| AvgCountLineCode
float64 0
7.89k
| AvgCountLineComment
float64 0
7.89k
| AvgCyclomatic
float64 0
130
| CommentToCodeRatio
float64 0
176
| CountClassBase
float64 0
48
| CountClassCoupled
float64 0
589
| CountClassCoupledModified
float64 0
581
| CountClassDerived
float64 0
5.37k
| CountDeclInstanceMethod
float64 0
4.2k
| CountDeclInstanceVariable
float64 0
299
| CountDeclMethod
float64 0
4.2k
| CountDeclMethodAll
float64 0
4.2k
| CountLine
float64 1
115k
| CountLineBlank
float64 0
9.01k
| CountLineCode
float64 0
94.4k
| CountLineCodeDecl
float64 0
46.1k
| CountLineCodeExe
float64 0
91.3k
| CountLineComment
float64 0
27k
| CountStmt
float64 1
93.2k
| CountStmtDecl
float64 0
46.1k
| CountStmtExe
float64 0
90.2k
| MaxCyclomatic
float64 0
759
| MaxInheritanceTree
float64 0
16
| MaxNesting
float64 0
34
| SumCyclomatic
float64 0
6k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6,200 |
Aplopio/django_rip
|
Aplopio_django_rip/rip/schema/integer_field.py
|
rip.schema.integer_field.IntegerField
|
class IntegerField(BaseField):
field_type = int
|
class IntegerField(BaseField):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 4 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 2 | 0 | 0 |
6,201 |
Aplopio/django_rip
|
Aplopio_django_rip/rip/generic_steps/default_authentication.py
|
rip.generic_steps.default_authentication.DefaultAuthentication
|
class DefaultAuthentication(object):
def __init__(self, schema_cls):
self.schema_cls = schema_cls
def authenticate(self, request):
return request if request.user \
else Response(is_success=False, reason=error_types.AuthenticationFailed)
|
class DefaultAuthentication(object):
def __init__(self, schema_cls):
pass
def authenticate(self, request):
pass
| 3 | 0 | 3 | 0 | 3 | 0 | 2 | 0 | 1 | 1 | 1 | 3 | 2 | 1 | 2 | 2 | 7 | 1 | 6 | 4 | 3 | 0 | 5 | 4 | 2 | 2 | 1 | 0 | 3 |
6,202 |
Aplopio/django_rip
|
Aplopio_django_rip/rip/generic_steps/default_authorization.py
|
rip.generic_steps.default_authorization.DefaultAuthorization
|
class DefaultAuthorization(object):
"""
This class defines the interface of how an authorization class
must be written. All the functions should take a apiv2 request
as input. Each function must add to the request object and return
if successful. If authorization fails, then return a response
with is_success as false and a reason code. It is recommended that you
use authorization failed reason code. By default all actions are permitted
for all users
"""
def __init__(self, schema_cls):
self.schema_cls = schema_cls
def add_read_list_filters(self, request):
"""
This step is called before read_list entity action
Override this to add request filters to return objects accessible to the
user.
:param request:
:return: request if success, response if unauthorized
"""
return request
def authorize_read_detail(self, request):
"""
:param request:
:return: request if success, response if unauthorized
"""
return request
def authorize_update_detail(self, request):
"""
:param request:
:return: request if success, response if unauthorized
"""
return request
def authorize_delete_detail(self, request):
"""
:param request:
:return: request if success, response if unauthorized
"""
return request
def authorize_create_detail(self, request):
"""
:param request:
:return: request if success, response if unauthorized
"""
return request
|
class DefaultAuthorization(object):
'''
This class defines the interface of how an authorization class
must be written. All the functions should take a apiv2 request
as input. Each function must add to the request object and return
if successful. If authorization fails, then return a response
with is_success as false and a reason code. It is recommended that you
use authorization failed reason code. By default all actions are permitted
for all users
'''
def __init__(self, schema_cls):
pass
def add_read_list_filters(self, request):
'''
This step is called before read_list entity action
Override this to add request filters to return objects accessible to the
user.
:param request:
:return: request if success, response if unauthorized
'''
pass
def authorize_read_detail(self, request):
'''
:param request:
:return: request if success, response if unauthorized
'''
pass
def authorize_update_detail(self, request):
'''
:param request:
:return: request if success, response if unauthorized
'''
pass
def authorize_delete_detail(self, request):
'''
:param request:
:return: request if success, response if unauthorized
'''
pass
def authorize_create_detail(self, request):
'''
:param request:
:return: request if success, response if unauthorized
'''
pass
| 7 | 6 | 6 | 0 | 2 | 4 | 1 | 2.46 | 1 | 0 | 0 | 1 | 6 | 1 | 6 | 6 | 53 | 8 | 13 | 8 | 6 | 32 | 13 | 8 | 6 | 1 | 1 | 0 | 6 |
6,203 |
Aplopio/django_rip
|
Aplopio_django_rip/rip/generic_steps/default_data_cleaner.py
|
rip.generic_steps.default_data_cleaner.DefaultRequestCleaner
|
class DefaultRequestCleaner(object):
def __init__(self, schema_cls):
self.schema_cls = schema_cls
def _get_attribute_name(self, field_name):
fields = self.schema_cls._meta.fields
if field_name not in fields:
cleaned_field_name = field_name
else:
field_obj = fields[field_name]
cleaned_field_name = field_obj.entity_attribute or field_name
return cleaned_field_name
def _get_filter_value(self, request, field_name, value, filter_type):
from rip.schema.schema_field import SchemaField
from rip.schema.list_field import ListField
schema_cls = self.schema_cls
field_name_split = field_name.split(filter_operators.OPERATOR_SEPARATOR)
cleaned_field_value = value
for part in field_name_split:
fields = schema_cls._meta.fields
field_obj = fields.get(part)
if isinstance(field_obj, SchemaField):
schema_cls = field_obj.of_type
continue
if field_obj is not None:
if isinstance(value, list) and not isinstance(field_obj,
ListField):
cleaned_field_value = [field_obj.clean(request, val_item)
for val_item in value]
elif isinstance(field_obj, ListField):
cleaned_field_value = field_obj.clean(request, value) if isinstance(value, list) else [value]
else:
cleaned_field_value = field_obj.clean(request, value)
break
return cleaned_field_value
def clean_request_params(self, request):
request_params = request.request_params
request_filters = {}
for filter_name in request_params.keys():
field_name, filter_type = filter_operators. \
split_to_field_and_filter_type(filter_name)
cleaned_field_value = self._get_filter_value(
request, field_name, request_params[filter_name], filter_type)
attribute_name = self._get_attribute_name(field_name)
if filter_type is not None:
attribute_name = filter_operators.OPERATOR_SEPARATOR.join(
[attribute_name, filter_type])
request_filters[attribute_name] = cleaned_field_value
if 'order_by' in request_filters:
order_by = filter_operators.transform_to_list(request_filters[
'order_by'])
request_filters['order_by'] = \
[self._get_attribute_name(field_name)
for field_name in order_by]
if 'aggregate_by' in request_filters:
aggregate_by = filter_operators.transform_to_list(request_filters[
'aggregate_by'])
request_filters['aggregate_by'] = \
[self._get_attribute_name(field_name)
for field_name in aggregate_by]
return request_filters
def clean_data_for_read_detail(self, request):
return self.clean_data_for_read_list(request)
def clean_data_for_delete_detail(self, request):
return self.clean_data_for_read_list(request)
def clean_data_for_read_list(self, request):
request_filters = self.clean_request_params(request)
request.context_params['request_filters'] = request_filters
return request
def clean_data_for_get_aggregates(self, request):
return self.clean_data_for_read_detail(request)
def _get_fields_to_clean(self, request, data):
action = request.context_params['crud_action']
non_read_only_fields = self.schema_cls.non_readonly_fields()
if action in (CrudActions.UPDATE_DETAIL, CrudActions.CREATE_OR_UPDATE_DETAIL):
updatable_fields = self.schema_cls.updatable_fields()
field_names = set(data).intersection(set(updatable_fields))
elif action == CrudActions.CREATE_DETAIL:
field_names = set(data).intersection(set(non_read_only_fields))
else:
field_names = []
return {field_name: non_read_only_fields[field_name]
for field_name in field_names}
def clean_data_for_update_detail(self, request):
data = request.data
request.context_params['data'] = self.clean(request,
data)
return request
def clean_data_for_create_detail(self, request):
data = request.data
request.context_params['data'] = self.clean(request,
data)
request = self.clean_data_for_read_detail(request)
return request
def clean_data_for_view_read(self, request):
request_filters = self.clean_request_params(request)
request.context_params['request_filters'] = request_filters
return request
def clean(self, request, data):
clean_data = {}
fields_to_clean = self._get_fields_to_clean(request, data)
for field_name, field_obj in fields_to_clean.items():
if field_name in data:
clean_data[self._get_attribute_name(field_name)] = \
field_obj.clean(request, data[field_name])
return clean_data
|
class DefaultRequestCleaner(object):
def __init__(self, schema_cls):
pass
def _get_attribute_name(self, field_name):
pass
def _get_filter_value(self, request, field_name, value, filter_type):
pass
def clean_request_params(self, request):
pass
def clean_data_for_read_detail(self, request):
pass
def clean_data_for_delete_detail(self, request):
pass
def clean_data_for_read_list(self, request):
pass
def clean_data_for_get_aggregates(self, request):
pass
def _get_fields_to_clean(self, request, data):
pass
def clean_data_for_update_detail(self, request):
pass
def clean_data_for_create_detail(self, request):
pass
def clean_data_for_view_read(self, request):
pass
def clean_request_params(self, request):
pass
| 14 | 0 | 9 | 1 | 8 | 0 | 2 | 0 | 1 | 5 | 3 | 0 | 13 | 1 | 13 | 13 | 130 | 25 | 105 | 45 | 89 | 0 | 85 | 45 | 69 | 7 | 1 | 3 | 28 |
6,204 |
Aplopio/django_rip
|
Aplopio_django_rip/rip/generic_steps/default_post_action_hooks.py
|
rip.generic_steps.default_post_action_hooks.DefaultPostActionHooks
|
class DefaultPostActionHooks(object):
def __init__(self, schema_cls):
self.schema_cls = schema_cls
def read_list_hook(self, request):
return request
def read_detail_hook(self, request):
return request
def create_detail_hook(self, request):
return request
def update_detail_hook(self, request):
return request
def delete_detail_hook(self, request):
return request
def get_aggregates_hook(self, request):
return request
|
class DefaultPostActionHooks(object):
def __init__(self, schema_cls):
pass
def read_list_hook(self, request):
pass
def read_detail_hook(self, request):
pass
def create_detail_hook(self, request):
pass
def update_detail_hook(self, request):
pass
def delete_detail_hook(self, request):
pass
def get_aggregates_hook(self, request):
pass
| 8 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 7 | 1 | 7 | 7 | 22 | 7 | 15 | 9 | 7 | 0 | 15 | 9 | 7 | 1 | 1 | 0 | 7 |
6,205 |
Aplopio/django_rip
|
Aplopio_django_rip/rip/generic_steps/default_request_params_validation.py
|
rip.generic_steps.default_request_params_validation.DefaultRequestParamsValidation
|
class DefaultRequestParamsValidation(object):
def __init__(self, schema_cls, filter_by_fields, order_by_fields, aggregate_by_fields):
self.aggregate_by_fields = aggregate_by_fields
self.order_by_fields = order_by_fields
self.filter_by_fields = filter_by_fields
self.schema_cls = schema_cls
def validate_order_by(self, request_params):
order_by_params = request_params.get('order_by', [])
order_by_params = filter_operators.transform_to_list(order_by_params)
validation_errors = {}
for order_by_field_name in order_by_params:
field_name, order_by_type = filter_operators. \
split_to_field_and_order_type(order_by_field_name)
if field_name not in self.order_by_fields:
validation_errors.update(
{field_name: "Ordering not allowed"})
if validation_errors:
return validation_errors
return None
def validate_aggregate_by(self, request_params):
aggregate_by_params = request_params.get('aggregate_by', [])
aggregate_by_params = filter_operators.transform_to_list(
aggregate_by_params)
validation_errors = {}
for field_name in aggregate_by_params:
if field_name not in self.aggregate_by_fields:
validation_errors.update(
{field_name: "Aggregating by this field is not allowed"})
if validation_errors:
return validation_errors
return None
def validate_offset(self, request_params):
try:
offset = request_params.get('offset', 0)
if int(offset) < 0:
raise ValueError
except ValueError:
return {'limit': 'Positive integer required'}
return None
def validate_limit(self, request_params):
try:
limit = request_params.get('limit', 20)
if int(limit) < 0:
raise ValueError
except ValueError:
return {'limit': 'Positive integer required'}
return None
def validate_request_params(self, request):
request_params = request.request_params
validation_errors = self._validate_fields(request_params)
if validation_errors is None:
validation_errors = self.validate_order_by(request_params)
if validation_errors is None:
validation_errors = self.validate_aggregate_by(request_params)
if validation_errors is None:
validation_errors = self.validate_limit(request_params) or \
self.validate_offset(request_params)
if validation_errors:
return Response(is_success=False,
reason=error_types.InvalidData,
data=validation_errors)
return request
def _validate_fields(self, request_params):
allowed_filters = self.filter_by_fields
special_filters = SPECIAL_FILTERS
validation_errors = {}
for filter_name in request_params:
field_name, filter_type = filter_operators. \
split_to_field_and_filter_type(filter_name)
if field_name not in allowed_filters and \
field_name not in special_filters:
validation_errors.update(
{field_name: "Filtering not allowed"})
if validation_errors:
return validation_errors
return None
|
class DefaultRequestParamsValidation(object):
def __init__(self, schema_cls, filter_by_fields, order_by_fields, aggregate_by_fields):
pass
def validate_order_by(self, request_params):
pass
def validate_aggregate_by(self, request_params):
pass
def validate_offset(self, request_params):
pass
def validate_limit(self, request_params):
pass
def validate_request_params(self, request):
pass
def _validate_fields(self, request_params):
pass
| 8 | 0 | 12 | 1 | 11 | 0 | 3 | 0 | 1 | 3 | 1 | 0 | 7 | 4 | 7 | 7 | 92 | 16 | 76 | 28 | 68 | 0 | 66 | 28 | 58 | 5 | 1 | 2 | 24 |
6,206 |
Aplopio/django_rip
|
Aplopio_django_rip/rip/generic_steps/default_response_converter.py
|
rip.generic_steps.default_response_converter.DefaultResponseConverter
|
class DefaultResponseConverter(object):
def __init__(self, schema_cls):
self.schema_cls = schema_cls
def convert_serialized_data_to_response(self, request):
return Response(is_success=True,
data=request.context_params['serialized_data'])
def convert_to_simple_response(self, request):
return Response(is_success=True)
|
class DefaultResponseConverter(object):
def __init__(self, schema_cls):
pass
def convert_serialized_data_to_response(self, request):
pass
def convert_to_simple_response(self, request):
pass
| 4 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 1 | 1 | 0 | 3 | 1 | 3 | 3 | 11 | 3 | 8 | 5 | 4 | 0 | 7 | 5 | 3 | 1 | 1 | 0 | 3 |
6,207 |
Aplopio/django_rip
|
Aplopio_django_rip/rip/error_types.py
|
rip.error_types.MultipleObjectsFound
|
class MultipleObjectsFound(Exception):
pass
|
class MultipleObjectsFound(Exception):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 3 | 0 | 0 |
6,208 |
Aplopio/django_rip
|
Aplopio_django_rip/tests/unit_tests/test_pipeline_composer.py
|
tests.unit_tests.test_pipeline_composer.TestPipelineComposer
|
class TestPipelineComposer(unittest.TestCase):
def setUp(self):
self.get_obj = MagicMock()
self.del_obj = MagicMock()
self.get_obj.__name__ = 'get_obj'
self.del_obj.__name__ = 'del_obj'
self.get_obj.return_value = Request(user=None, request_params=None)
self.del_obj.return_value = Response()
def test_api_method_calls_handler(self):
test_api_method = PipelineComposer(pipeline=[self.get_obj])
self.get_obj.return_value = Response()
expected_request = Request(user=None,
request_params={'somearg1': 1,
'somearg2': 2})
test_api_method(expected_request)
self.get_obj.assert_called_with(request=expected_request)
def test_api_method_calls_all_functions_in_pipeline(self):
test_api_method = PipelineComposer(
pipeline=[self.get_obj, self.del_obj])
expected_request = Request(user=None,
request_params={'somearg1': 1,
'somearg2': 2})
test_api_method(expected_request)
self.get_obj.assert_called_with(
request=expected_request)
self.del_obj.assert_called_with(
request=expected_request)
def test_api_method_exits_pipeline_on_response(self):
test_method = PipelineComposer(pipeline=[self.get_obj, self.del_obj])
expected_response = Response()
expected_request = Request(user=None,
request_params={'somearg1': 1,
'somearg2': 2})
self.get_obj.return_value = expected_response
test_method(expected_request)
self.get_obj.assert_called_with(
request=expected_request)
self.assertEqual(self.del_obj.call_count, 0)
def test_api_method_throws_if_no_response_from_last_handler(self):
test_method = PipelineComposer(pipeline=[self.get_obj, self.del_obj])
expected_request = Request(
user=None, request_params={})
self.get_obj.return_value = expected_request
self.del_obj.return_value = expected_request
self.assertRaises(AssertionError, test_method,
request=expected_request)
def test_api_method_throws_for_non_standard_response(self):
test_method = PipelineComposer(pipeline=[self.get_obj])
self.get_obj.return_value = object()
request = Request(user=None, request_params=None)
self.assertRaises(AssertionError, test_method, request)
|
class TestPipelineComposer(unittest.TestCase):
def setUp(self):
pass
def test_api_method_calls_handler(self):
pass
def test_api_method_calls_all_functions_in_pipeline(self):
pass
def test_api_method_exits_pipeline_on_response(self):
pass
def test_api_method_throws_if_no_response_from_last_handler(self):
pass
def test_api_method_throws_for_non_standard_response(self):
pass
| 7 | 0 | 9 | 1 | 8 | 0 | 1 | 0 | 1 | 4 | 3 | 0 | 6 | 2 | 6 | 78 | 62 | 11 | 51 | 20 | 44 | 0 | 39 | 20 | 32 | 1 | 2 | 0 | 6 |
6,209 |
ApproxEng/approxeng.input
|
src/python/approxeng/input/dualshock4.py
|
input.dualshock4.DualShock4
|
class DualShock4(Controller):
"""
Driver for the Sony PlayStation 4 controller, the DualShock4
"""
def __init__(self, dead_zone=0.05, hot_zone=0.05, **kwargs):
"""
Create a new DualShock4 driver
:param float dead_zone:
Used to set the dead zone for each :class:`~approxeng.input.CentredAxis` in the controller.
:param float hot_zone:
Used to set the hot zone for each :class:`~approxeng.input.CentredAxis` in the controller.
"""
super(DualShock4, self).__init__(controls=[
Button("Circle", 305, sname='circle'),
Button("Cross", 304, sname='cross'),
Button("Square", 308, sname='square'),
Button("Triangle", 307, sname='triangle'),
Button("Home (PS)", 316, sname='home'),
Button("Share", 314, sname='select'),
Button("Options", 315, sname='start'),
Button("Trackpad", 'touch272', sname='ps4_pad'),
Button("L1", 310, sname='l1'),
Button("R1", 311, sname='r1'),
Button("L2", 312, sname='l2'),
Button("R2", 313, sname='r2'),
Button("Left Stick", 317, sname='ls'),
Button("Right Stick", 318, sname='rs'),
CentredAxis("Left Horizontal", 0, 255, 0, sname='lx'),
CentredAxis("Left Vertical", 255, 0, 1, sname='ly'),
CentredAxis("Right Horizontal", 0, 255, 3, sname='rx'),
CentredAxis("Right Vertical", 255, 0, 4, sname='ry'),
TriggerAxis("Left Trigger", 0, 255, 2, sname='lt'),
TriggerAxis("Right Trigger", 0, 255, 5, sname='rt'),
BinaryAxis("D-pad Horizontal", 16, b1name='dleft', b2name='dright'),
BinaryAxis("D-pad Vertical", 17, b1name='dup', b2name='ddown'),
CentredAxis("Yaw rate", 2097152, -2097152, 'motion4', sname='yaw_rate'),
CentredAxis("Roll", 8500, -8500, 'motion0', sname='roll'),
CentredAxis("Pitch", 8500, -8500, 'motion2', sname='pitch'),
CentredAxis("Touch X", 0, 1920, 'touch53', sname='tx'),
CentredAxis("Touch Y", 942, 0, 'touch54', sname='ty')
],
node_mappings={
'Sony Interactive Entertainment Wireless Controller Touchpad': 'touch',
'Sony Interactive Entertainment Wireless Controller Motion Sensors': 'motion',
'Wireless Controller Touchpad': 'touch',
'Wireless Controller Motion Sensors': 'motion'},
dead_zone=dead_zone,
hot_zone=hot_zone,
**kwargs)
self.axes['roll'].hot_zone = 0.2
self.axes['pitch'].hot_zone = 0.2
@staticmethod
def registration_ids():
"""
:return: list of (vendor_id, product_id) for this controller
"""
return [(0x54c, 0x9cc),
(0x54c, 0x5c4)]
def __repr__(self) -> str:
return 'Sony DualShock4 (Playstation 4) controller'
def set_leds(self, hue: float = 0.0, saturation: float = 1.0, value: float = 1.0):
"""
The DualShock4 has an LED bar on the front of the controller. This function allows you to set the value of this
bar. Note that the controller must be connected for this to work, if it's not the call will just be ignored.
:param hue:
The hue of the colour, defaults to 0, specified as a floating point value between 0.0 and 1.0.
:param saturation:
Saturation of the colour, defaults to 1.0, specified as a floating point value between 0.0 and 1.0.
:param value:
Value of the colour (i.e. how bright the light is overall), defaults to 1.0, specified as a floating point
value between 0.0 and 1.0
"""
r, g, b = hsv_to_rgb(hue, saturation, value)
self.write_led_value('red', r * 255.0)
self.write_led_value('green', g * 255.0)
self.write_led_value('blue', b * 255.0)
|
class DualShock4(Controller):
'''
Driver for the Sony PlayStation 4 controller, the DualShock4
'''
def __init__(self, dead_zone=0.05, hot_zone=0.05, **kwargs):
'''
Create a new DualShock4 driver
:param float dead_zone:
Used to set the dead zone for each :class:`~approxeng.input.CentredAxis` in the controller.
:param float hot_zone:
Used to set the hot zone for each :class:`~approxeng.input.CentredAxis` in the controller.
'''
pass
@staticmethod
def registration_ids():
'''
:return: list of (vendor_id, product_id) for this controller
'''
pass
def __repr__(self) -> str:
pass
def set_leds(self, hue: float = 0.0, saturation: float = 1.0, value: float = 1.0):
'''
The DualShock4 has an LED bar on the front of the controller. This function allows you to set the value of this
bar. Note that the controller must be connected for this to work, if it's not the call will just be ignored.
:param hue:
The hue of the colour, defaults to 0, specified as a floating point value between 0.0 and 1.0.
:param saturation:
Saturation of the colour, defaults to 1.0, specified as a floating point value between 0.0 and 1.0.
:param value:
Value of the colour (i.e. how bright the light is overall), defaults to 1.0, specified as a floating point
value between 0.0 and 1.0
'''
pass
| 6 | 4 | 19 | 1 | 13 | 5 | 1 | 0.46 | 1 | 7 | 4 | 0 | 3 | 0 | 4 | 45 | 83 | 7 | 52 | 7 | 46 | 24 | 14 | 6 | 9 | 1 | 5 | 0 | 4 |
6,210 |
ApproxEng/approxeng.input
|
src/python/approxeng/input/pihut.py
|
input.pihut.PiHut
|
class PiHut(Controller):
"""
Driver for the PiHut PS3-alike controller
"""
def __init__(self, dead_zone=0.05, hot_zone=0.05, **kwargs):
"""
Discover and initialise a PiHut controller connected to this computer.
:param float dead_zone:
Used to set the dead zone for each :class:`approxeng.input.CentredAxis` in the controller.
:param float hot_zone:
Used to set the hot zone for each :class:`approxeng.input.CentredAxis` in the controller.
"""
super(PiHut, self).__init__(
controls=[
Button("Select", 314, sname='select'),
Button("Left Stick", 317, sname='ls'),
Button("Right Stick", 318, sname='rs'),
Button("Start", 315, sname='start'),
Button("L1", 310, sname='l1'),
Button("L2", 312, sname='l2'),
Button("R1", 311, sname='r1'),
Button("R2", 313, sname='r2'),
Button("Triangle", 308, sname='triangle'),
Button("Circle", 305, sname='circle'),
Button("Cross", 304, sname='cross'),
Button("Square", 307, sname='square'),
Button("Analog", 316, sname='home'),
CentredAxis("Left Vertical", 255, 0, 1, sname='ly'),
CentredAxis("Right Vertical", 255, 0, 5, sname='ry'),
CentredAxis("Left Horizontal", 0, 255, 0, sname='lx'),
CentredAxis("Right Horizontal", 0, 255, 2, sname='rx'),
TriggerAxis("Left Trigger", 0, 255, 9, sname='lt'),
TriggerAxis("Right Trigger", 0, 255, 10, sname='rt'),
BinaryAxis("D-pad Horizontal", 16, b1name='dleft', b2name='dright'),
BinaryAxis("D-pad Vertical", 17, b1name='dup', b2name='ddown')
],
dead_zone=dead_zone,
hot_zone=hot_zone,
**kwargs)
@staticmethod
def registration_ids():
"""
:return: list of (vendor_id, product_id) for this controller
"""
return [(0x2563, 0x526), (0x2563, 0x575)]
def __repr__(self):
return 'PiHut PS3-alike controller'
|
class PiHut(Controller):
'''
Driver for the PiHut PS3-alike controller
'''
def __init__(self, dead_zone=0.05, hot_zone=0.05, **kwargs):
'''
Discover and initialise a PiHut controller connected to this computer.
:param float dead_zone:
Used to set the dead zone for each :class:`approxeng.input.CentredAxis` in the controller.
:param float hot_zone:
Used to set the hot zone for each :class:`approxeng.input.CentredAxis` in the controller.
'''
pass
@staticmethod
def registration_ids():
'''
:return: list of (vendor_id, product_id) for this controller
'''
pass
def __repr__(self):
pass
| 5 | 3 | 14 | 0 | 11 | 3 | 1 | 0.38 | 1 | 5 | 4 | 0 | 2 | 0 | 3 | 44 | 51 | 4 | 34 | 5 | 29 | 13 | 7 | 4 | 3 | 1 | 5 | 0 | 3 |
6,211 |
ApproxEng/approxeng.input
|
src/python/approxeng/input/profiling.py
|
input.profiling.AxisProfile
|
class AxisProfile:
"""
Details of a single axis
"""
def __init__(self, code=None, min_value=0, max_value=0, invert=False, disable=False):
# evdev code
self.code = code
# minimum reported value
self.min_value = min_value
# maximum reported value
self.max_value = max_value
# normally we assume positive = up / right, this inverts that
self.invert = invert
# allow for explicitly disabled axes
self.disable = disable
@property
def real_max(self):
return self.max_value if not self.invert else self.min_value
@property
def real_min(self):
return self.min_value if not self.invert else self.max_value
def __bool__(self):
return self.code is not None and not self.disable
def build_repr(self, control=None, axis=None, current_value=None):
"""
String representation of this axis profile
:param current_value: optionally adds the current value of the axis to the display
"""
control_string = f'[{control}] ' if control else ''
axis_string = f'{axis} : ' if axis else ''
if self.disable:
return f'{control_string}{axis_string}DISABLED'
if self.code is None:
return f'{control_string}{axis_string}---'
if current_value is not None:
return f'{control_string}{axis_string}{self.code} = {current_value} {"[invert]" if self.invert else ""}'
else:
return f'{control_string}{axis_string}{self.code} {"[invert]" if self.invert else ""}'
|
class AxisProfile:
'''
Details of a single axis
'''
def __init__(self, code=None, min_value=0, max_value=0, invert=False, disable=False):
pass
@property
def real_max(self):
pass
@property
def real_min(self):
pass
def __bool__(self):
pass
def build_repr(self, control=None, axis=None, current_value=None):
'''
String representation of this axis profile
:param current_value: optionally adds the current value of the axis to the display
'''
pass
| 8 | 2 | 7 | 0 | 5 | 2 | 3 | 0.46 | 0 | 0 | 0 | 0 | 5 | 5 | 5 | 5 | 44 | 6 | 26 | 15 | 18 | 12 | 23 | 13 | 17 | 8 | 0 | 1 | 14 |
6,212 |
ApproxEng/approxeng.input
|
src/python/approxeng/input/profiling.py
|
input.profiling.Profile
|
class Profile:
"""
Profile of a (simplified) controller, with a single input device and a standard set of controls, all of which are
optional. Can be retrieved and stored from and to a dict, and can dynamically create a Controller subclass from
this information when needed.
"""
def __init__(self, d=None):
# Note - some of these axes and button names are mutually exclusive, in particular some controllers
# don't have button events for analogue triggers, and d-pads are either buttons or binary axes
self._reset()
self.vendor_id = 0
self.product_id = 0
self.name = 'unknown controller'
if d:
self.dict = d
def _reset(self):
self.buttons = {button: None for button in BUTTON_NAMES}
self.axes = {axis: AxisProfile() for axis in AXIS_NAMES}
def set_button(self, name, code):
if name in self.buttons:
self.buttons[name] = code
else:
LOGGER.warning(f'Unknown button sname={name}, not using')
def set_axis_range(self, name, code, min_value, max_value):
if name in self.axes:
axis = self.axes[name]
axis.min_value = min_value
axis.max_value = max_value
axis.code = code
def toggle_axis_enable(self, name):
if name in self.axes:
self.axes[name].disable = not self.axes[name].disable
def toggle_axis_invert(self, name):
if name in self.axes and self.axes[name]:
self.axes[name].invert = not self.axes[name].invert
@property
def dict(self):
return {'vendor': self.vendor_id,
'product': self.product_id,
'name': self.name,
'buttons': {button: self.buttons[button] for button in self.buttons if self.buttons[button]},
'axes': {axis: {'code': self.axes[axis].code,
'min_value': self.axes[axis].min_value,
'max_value': self.axes[axis].max_value,
'invert': self.axes[axis].invert} for axis in self.axes if self.axes[axis]}}
@dict.setter
def dict(self, d):
self._reset()
for name, code in d['buttons'].items():
self.buttons[name] = code
for name, axis in d['axes'].items():
self.axes[name] = AxisProfile(code=axis['code'],
min_value=axis['min_value'],
max_value=axis['max_value'],
invert=axis['invert'])
self.vendor_id = d['vendor']
self.product_id = d['product']
self.name = d['name']
@property
def controls(self):
"""
Infers a list of control objects from the current set of known axes etc. This can be used to construct
a controller class
"""
# Get all buttons first, only picking up ones for which we've got known codes
buttons = [Button(name=name, key_code=self.buttons[name], sname=name) for name in self.buttons if
self.buttons[name]]
# Pick up trigger axes if we have them
def trigger_axis(axis_name, button_name):
if self.axes[axis_name]:
axis = self.axes[axis_name]
if self.buttons[button_name]:
# We have a trigger button defined, no need to include it in the trigger definition
return TriggerAxis(name=axis_name, min_raw_value=axis.real_min, max_raw_value=axis.real_max,
axis_event_code=axis.code, sname=axis_name)
else:
# Have an analogue trigger but no trigger button, set the trigger axis to create a
# virtual button triggered at 20% activation, this is what we use for e.g. xbox controllers
return TriggerAxis(name=axis_name, min_raw_value=axis.real_min, max_raw_value=axis.real_max,
axis_event_code=axis.code, sname=axis_name, button_sname=button_name,
button_trigger_value=0.2)
triggers = [trigger_axis(a, b) for a, b in [('lt', 'l2'), ('rt', 'r2')]]
# Binary axes - these are generally just the D-pad on some controllers (some have actual buttons, some
# have a slightly strange axis which only reports -1 and 1 when buttons are pressed
def binary_axis(axis_name, b1name, b2name):
if self.axes[axis_name] and self.buttons[b1name] is None and self.buttons[b2name] is None:
axis = self.axes[axis_name]
return BinaryAxis(name=axis_name, axis_event_code=axis.code,
b1name=b1name if not axis.invert else b2name,
b2name=b2name if not axis.invert else b1name)
dpad = [binary_axis(a, b, c) for a, b, c in [('dx', 'dleft', 'dright'), ('dy', 'dup', 'ddown')]]
# Regular centred axes
def centred_axis(axis_name):
if self.axes[axis_name]:
axis = self.axes[axis_name]
return CentredAxis(name=axis_name, min_raw_value=axis.real_min, max_raw_value=axis.real_max,
axis_event_code=axis.code, sname=axis_name)
sticks = [centred_axis(name) for name in ['lx', 'ly', 'rx', 'ry']]
return list([control for control in [*buttons, *triggers, *dpad, *sticks] if control is not None])
def build_controller_class(self):
"""
Builds a new controller subclass which should be able to drive a controller with this profile. These
controller classes are simple, they only map to a single device and they don't support any special features
of the controller such as onboard LEDs, motion sensors etc. This is, however, enough for almost all
controller types, leaving custom code only required for things like the dualshock controllers with their
fancy touchpad surfaces and similar
"""
profile = self
class ProfiledController(Controller):
def __init__(self, dead_zone=0.05, hot_zone=0.05, **kwargs):
super(ProfiledController, self).__init__(controls=profile.controls,
dead_zone=dead_zone,
hot_zone=hot_zone,
**kwargs)
@staticmethod
def registration_ids():
return [(profile.vendor_id, profile.product_id)]
def __repr__(self) -> str:
return profile.name
return ProfiledController
|
class Profile:
'''
Profile of a (simplified) controller, with a single input device and a standard set of controls, all of which are
optional. Can be retrieved and stored from and to a dict, and can dynamically create a Controller subclass from
this information when needed.
'''
def __init__(self, d=None):
pass
def _reset(self):
pass
def set_button(self, name, code):
pass
def set_axis_range(self, name, code, min_value, max_value):
pass
def toggle_axis_enable(self, name):
pass
def toggle_axis_invert(self, name):
pass
@property
def dict(self):
pass
@dict.setter
def dict(self):
pass
@property
def controls(self):
'''
Infers a list of control objects from the current set of known axes etc. This can be used to construct
a controller class
'''
pass
def trigger_axis(axis_name, button_name):
pass
def binary_axis(axis_name, b1name, b2name):
pass
def centred_axis(axis_name):
pass
def build_controller_class(self):
'''
Builds a new controller subclass which should be able to drive a controller with this profile. These
controller classes are simple, they only map to a single device and they don't support any special features
of the controller such as onboard LEDs, motion sensors etc. This is, however, enough for almost all
controller types, leaving custom code only required for things like the dualshock controllers with their
fancy touchpad surfaces and similar
'''
pass
class ProfiledController(Controller):
def __init__(self, d=None):
pass
@staticmethod
def registration_ids():
pass
def __repr__(self) -> str:
pass
| 22 | 3 | 10 | 1 | 8 | 2 | 2 | 0.28 | 0 | 7 | 6 | 0 | 10 | 5 | 10 | 10 | 142 | 22 | 94 | 38 | 72 | 26 | 68 | 34 | 50 | 4 | 0 | 2 | 29 |
6,213 |
ApproxEng/approxeng.input
|
src/python/approxeng/input/profiling.py
|
input.profiling.Profiler
|
class Profiler:
"""
Holds the observed state of a set of controller axes and buttons. The profiler thread updates this, maintaining
the highest and lowest observed values for an axis, and the last button to be pressed. We use this to guess the
most likely intentional movement or button press from the user when profiling a controller.
"""
def __init__(self, device: InputDevice):
self.last_button_pressed = None
self.axes = {}
self.device = device
def reset(self):
self.last_button_pressed = None
self.axes.clear()
def update_axis(self, code, value):
if code not in self.axes:
self.axes[code] = value, value, value
min_value, max_value, _ = self.axes[code]
self.axes[code] = min(min_value, value), max(max_value, value), value
def update_button(self, code):
self.last_button_pressed = code
@property
def axis_changes(self):
return sorted([(code, self.axes[code][0], self.axes[code][1], self.axes[code][2]) for code in self.axes],
key=lambda item: -abs(item[1] - item[2]))
@property
def binary_axis_changes(self):
return [(code, low, high, value) for code, low, high, value in self.axis_changes if low == -1 and high == 1]
|
class Profiler:
'''
Holds the observed state of a set of controller axes and buttons. The profiler thread updates this, maintaining
the highest and lowest observed values for an axis, and the last button to be pressed. We use this to guess the
most likely intentional movement or button press from the user when profiling a controller.
'''
def __init__(self, device: InputDevice):
pass
def reset(self):
pass
def update_axis(self, code, value):
pass
def update_button(self, code):
pass
@property
def axis_changes(self):
pass
@property
def binary_axis_changes(self):
pass
| 9 | 1 | 3 | 0 | 3 | 0 | 1 | 0.23 | 0 | 0 | 0 | 0 | 6 | 3 | 6 | 6 | 33 | 6 | 22 | 13 | 13 | 5 | 19 | 11 | 12 | 2 | 0 | 1 | 7 |
6,214 |
ApproxEng/approxeng.input
|
src/python/approxeng/input/profiling.py
|
input.profiling.ProfilerThread
|
class ProfilerThread(Thread):
"""
Thread that reads events from an InputDevice and uses them to update a profile object
"""
def __init__(self, profiler: Profiler):
Thread.__init__(self, name='evdev profiler thread')
self.daemon = True
self.running = True
self.profiler = profiler
def run(self):
while self.running:
try:
r, w, x = select([self.profiler.device], [], [], 0.5)
for fd in r:
for event in fd.read():
if event.type == EV_ABS or event.type == EV_REL:
self.profiler.update_axis(event.code, event.value)
elif event.type == EV_KEY:
self.profiler.update_button(event.code)
except Exception as e:
self.stop(e)
def stop(self, exception=None):
if exception:
LOGGER.error('Error when reading from device!', exc_info=exception)
self.running = False
|
class ProfilerThread(Thread):
'''
Thread that reads events from an InputDevice and uses them to update a profile object
'''
def __init__(self, profiler: Profiler):
pass
def run(self):
pass
def stop(self, exception=None):
pass
| 4 | 1 | 7 | 0 | 7 | 0 | 3 | 0.14 | 1 | 2 | 1 | 0 | 3 | 3 | 3 | 28 | 28 | 3 | 22 | 11 | 18 | 3 | 21 | 10 | 17 | 7 | 1 | 5 | 10 |
6,215 |
ApproxEng/approxeng.input
|
src/python/approxeng/input/spacemousepro.py
|
input.spacemousepro.SpaceMousePro
|
class SpaceMousePro(Controller):
"""
Driver for the wired SpaceMouse Pro from 3dConnexion. This controller has a single six-axis puck which can respond
to motion in all available axes, as well as a set of buttons. Buttons 1-4 seem to act differently to the others,
they don't generate events on presses consistently so while they do work they should be used with caution. Other
buttons respond instantly and do the right thing in terms of press detection and hold times. Details of the
hardware can be found `here <https://www.3dconnexion.co.uk/index.php?id=271>`_
I've had to largely abandon the normal snames for axes for this controller, it's sufficiently different from all
the others that there's not really any way to directly substitute it. The puck uses lx and ly for linear X and Y
movement, but it then also uses lz for up and down, and pitch, roll, and yaw for the rotational axes. As such, it
will 'just work' if your code only uses the left stick and the motion sensing axes, but there aren't any trigger
buttons or axes, and there's no right joystick x and y. On the other hand, if you've got one of these you already
know you'll need to code specifically for it!
"""
def __init__(self, dead_zone=0.05, hot_zone=0.01, **kwargs):
super(SpaceMousePro, self).__init__(controls=[
CentredAxis('X', -350, 350, 0, sname='lx'),
CentredAxis('Y', 350, -350, 1, sname='ly'),
CentredAxis('Z', 350, -350, 2, sname='lz'),
CentredAxis('Roll', -350, 350, 3, sname='pitch'),
CentredAxis('Pitch', 350, -350, 4, sname='roll'),
CentredAxis('Yaw', -350, 350, 5, sname='yaw'),
Button('Menu', 256, sname='menu'),
Button('Alt', 279, sname='alt'),
Button('Ctrl', 281, sname='ctrl'),
Button('Shift', 280, sname='shift'),
Button('Esc', 278, sname='esc'),
Button('1', 268, sname='1'),
Button('2', 269, sname='2'),
Button('3', 270, sname='3'),
Button('4', 271, sname='4'),
Button('Rotate', 264, sname='rotate'),
Button('T', 258, sname='t'),
Button('F', 261, sname='f'),
Button('R', 260, sname='r'),
Button('Lock', 282, sname='lock'),
Button('Fit', 257, sname='fit')
],
dead_zone=dead_zone,
hot_zone=hot_zone,
**kwargs)
def __repr__(self):
return '3Dconnexion SpaceMouse Pro'
@staticmethod
def registration_ids():
"""
:return: list of (vendor_id, product_id) for this controller
"""
return [(0x46d, 0xc62b)]
|
class SpaceMousePro(Controller):
'''
Driver for the wired SpaceMouse Pro from 3dConnexion. This controller has a single six-axis puck which can respond
to motion in all available axes, as well as a set of buttons. Buttons 1-4 seem to act differently to the others,
they don't generate events on presses consistently so while they do work they should be used with caution. Other
buttons respond instantly and do the right thing in terms of press detection and hold times. Details of the
hardware can be found `here <https://www.3dconnexion.co.uk/index.php?id=271>`_
I've had to largely abandon the normal snames for axes for this controller, it's sufficiently different from all
the others that there's not really any way to directly substitute it. The puck uses lx and ly for linear X and Y
movement, but it then also uses lz for up and down, and pitch, roll, and yaw for the rotational axes. As such, it
will 'just work' if your code only uses the left stick and the motion sensing axes, but there aren't any trigger
buttons or axes, and there's no right joystick x and y. On the other hand, if you've got one of these you already
know you'll need to code specifically for it!
'''
def __init__(self, dead_zone=0.05, hot_zone=0.01, **kwargs):
pass
def __repr__(self):
pass
@staticmethod
def registration_ids():
'''
:return: list of (vendor_id, product_id) for this controller
'''
pass
| 5 | 2 | 11 | 0 | 10 | 1 | 1 | 0.48 | 1 | 3 | 2 | 0 | 2 | 0 | 3 | 44 | 53 | 4 | 33 | 5 | 28 | 16 | 7 | 4 | 3 | 1 | 5 | 0 | 3 |
6,216 |
ApproxEng/approxeng.input
|
src/python/approxeng/input/sf30pro.py
|
input.sf30pro.SF30Pro
|
class SF30Pro(Controller):
"""
Driver for the 8BitDo SF30 Pro, courtesy of Tom Brougthon (tabroughton on github)
"""
def __init__(self, dead_zone=0.05, hot_zone=0.05, **kwargs):
"""
Create a new SF30 Pro driver
:param float dead_zone:
Used to set the dead zone for each :class:`approxeng.input.CentredAxis` in the controller.
:param float hot_zone:
Used to set the hot zone for each :class:`approxeng.input.CentredAxis` in the controller.
"""
super(SF30Pro, self).__init__(
controls=[
TriggerAxis("Right Trigger", 0, 255, 9, sname='rt'),
TriggerAxis("Left Trigger", 0, 255, 10, sname='lt'),
CentredAxis("Right Vertical", 255, 0, 5, sname='ry'),
CentredAxis("Left Horizontal", 0, 255, 0, sname='lx'),
CentredAxis("Left Vertical", 255, 0, 1, sname='ly'),
CentredAxis("Right Horizontal", 0, 255, 2, sname='rx'),
BinaryAxis("D-pad Horizontal", 16, b1name='dleft', b2name='dright'),
BinaryAxis("D-pad Vertical", 17, b1name='ddown', b2name='dup'),
Button("B", 304, sname='circle'),
Button("A", 305, sname='cross'),
Button("Mode", 306, sname='home'),
Button("X", 307, sname='triangle'),
Button("Y", 308, sname='square'),
Button("L1", 310, sname='l1'),
Button("R1", 311, sname='r1'),
Button("L2", 312, sname='l2'),
Button("R2", 313, sname='r2'),
Button("Select", 314, sname='select'),
Button("Start", 315, sname='start'),
Button("Left Stick", 317, sname='ls'),
Button("Right Stick", 318, sname='rs')
],
dead_zone=dead_zone,
hot_zone=hot_zone,
**kwargs)
@staticmethod
def registration_ids():
"""
:return: list of (vendor_id, product_id) for this controller
"""
return [(0x2dc8, 0x6100)]
def __repr__(self):
return '8Bitdo SF30 Pro'
|
class SF30Pro(Controller):
'''
Driver for the 8BitDo SF30 Pro, courtesy of Tom Brougthon (tabroughton on github)
'''
def __init__(self, dead_zone=0.05, hot_zone=0.05, **kwargs):
'''
Create a new SF30 Pro driver
:param float dead_zone:
Used to set the dead zone for each :class:`approxeng.input.CentredAxis` in the controller.
:param float hot_zone:
Used to set the hot zone for each :class:`approxeng.input.CentredAxis` in the controller.
'''
pass
@staticmethod
def registration_ids():
'''
:return: list of (vendor_id, product_id) for this controller
'''
pass
def __repr__(self):
pass
| 5 | 3 | 14 | 0 | 11 | 3 | 1 | 0.38 | 1 | 5 | 4 | 0 | 2 | 0 | 3 | 44 | 51 | 4 | 34 | 5 | 29 | 13 | 7 | 4 | 3 | 1 | 5 | 0 | 3 |
6,217 |
ApproxEng/approxeng.input
|
src/python/approxeng/input/dualshock3.py
|
input.dualshock3.DualShock3
|
class DualShock3(Controller):
"""
Driver for the Sony PlayStation 3 controller, the DualShock3
"""
def __init__(self, dead_zone=0.05, hot_zone=0.0, **kwargs):
"""
Discover and initialise a PS3 SixAxis controller connected to this computer.
:param float dead_zone:
Used to set the dead zone for each :class:`approxeng.input.CentredAxis` in the controller.
:param float hot_zone:
Used to set the hot zone for each :class:`approxeng.input.CentredAxis` in the controller.
"""
super(DualShock3, self).__init__(controls=[
Button("Select", 314, sname='select'),
Button("Left Stick", 317, sname='ls'),
Button("Right Stick", 318, sname='rs'),
Button("Start", 315, sname='start'),
Button("D Up", 544, sname='dup'),
Button("D Right", 547, sname='dright'),
Button("D Down", 545, sname='ddown'),
Button("D Left", 546, sname='dleft'),
Button("L2", 312, sname='l2'),
Button("R2", 313, sname='r2'),
Button("L1", 310, sname='l1'),
Button("R1", 311, sname='r1'),
Button("Triangle", 307, sname='triangle'),
Button("Circle", 305, sname='circle'),
Button("Cross", 304, sname='cross'),
Button("Square", 308, sname='square'),
Button("Home (PS)", 316, sname='home'),
TriggerAxis("Left Trigger", 0, 255, 2, sname='lt'),
TriggerAxis("Right Trigger", 0, 255, 5, sname='rt'),
CentredAxis("Left Vertical", 255, 0, 1, sname='ly'),
CentredAxis("Right Vertical", 255, 0, 4, sname='ry'),
CentredAxis("Left Horizontal", 0, 255, 0, sname='lx'),
CentredAxis("Right Horizontal", 0, 255, 3, sname='rx'),
CentredAxis("Motion 0", 127, -128, 'motion0', sname='roll'),
CentredAxis("Motion 2", 127, -128, 'motion2', sname='pitch'),
],
node_mappings={'Sony PLAYSTATION(R)3 Controller Motion Sensors': 'motion'},
dead_zone=dead_zone,
hot_zone=hot_zone,
**kwargs)
self.axes['roll'].hot_zone = 0.2
self.axes['pitch'].hot_zone = 0.2
@staticmethod
def registration_ids():
"""
:return: list of (vendor_id, product_id) for this controller
"""
return [(0x54c, 0x268)]
def __repr__(self):
return 'Sony DualShock3 (Playstation 3) controller'
def set_led(self, led_number, led_value):
"""
Set front-panel controller LEDs. The DS3 controller has four, labelled, LEDs on the front panel that can
be either on or off.
:param led_number:
Integer between 1 and 4
:param led_value:
Value, set to 0 to turn the LED off, 1 to turn it on
"""
if 1 > led_number > 4:
return
self.write_led_value(led_name='sony{}'.format(led_number), value=led_value)
|
class DualShock3(Controller):
'''
Driver for the Sony PlayStation 3 controller, the DualShock3
'''
def __init__(self, dead_zone=0.05, hot_zone=0.0, **kwargs):
'''
Discover and initialise a PS3 SixAxis controller connected to this computer.
:param float dead_zone:
Used to set the dead zone for each :class:`approxeng.input.CentredAxis` in the controller.
:param float hot_zone:
Used to set the hot zone for each :class:`approxeng.input.CentredAxis` in the controller.
'''
pass
@staticmethod
def registration_ids():
'''
:return: list of (vendor_id, product_id) for this controller
'''
pass
def __repr__(self):
pass
def set_led(self, led_number, led_value):
'''
Set front-panel controller LEDs. The DS3 controller has four, labelled, LEDs on the front panel that can
be either on or off.
:param led_number:
Integer between 1 and 4
:param led_value:
Value, set to 0 to turn the LED off, 1 to turn it on
'''
pass
| 6 | 4 | 16 | 1 | 11 | 5 | 1 | 0.48 | 1 | 4 | 3 | 0 | 3 | 0 | 4 | 45 | 71 | 6 | 44 | 6 | 38 | 21 | 13 | 5 | 8 | 2 | 5 | 1 | 5 |
6,218 |
ApproxEng/approxeng.input
|
src/python/approxeng/input/steamcontroller.py
|
input.steamcontroller.SteamController
|
class SteamController(Controller):
"""
Wireless steam controller. As of Jan 2021 this works with modern linux installations without
any messing around, and supports a lot of extra controls as a result!
The unusual controls are as follows, firstly buttons. Note that both the trackpads have
touch buttons as well as the click (on the right trackpad) and the d-pad 'buttons' on the
left one. The controller doesn't have a true d-pad, but you can use the left trackpad in
place of one (although it's heavy to activate)
============= ================
Standard name Steam Controller
------------- ----------------
square X
triangle Y
circle B
cross A
ls Left stick click
rs Right trackpad click
rtouch Right trackpad touch
select Left arrow
start Right arrow
home Steam button
dleft DPad left click
dup DPad up click
dright DPad right click
ddown DPad down click
dtouch DPad (left trackpad) touch
l1 Top left trigger
l2 Middle left trigger
l3 Base left trigger
r1 Top right trigger
r2 Middle right trigger
r3 Base right trigger
============= ================
The controller has three xy axes with corresponding circular axes as well as analogue
triggers on the middle trigger buttons:
============= ================
Standard name Steam Controller
------------- ----------------
lx Stick horizontal
ly Stick vertical
rx Right trackpad horizontal
ry Right trackpad vertical
dx Left trackpad horizontal
dy Left trackpad vertical
lt Middle left trigger
rt Middle right trigger
============= ================
"""
def __init__(self, dead_zone=0.1, hot_zone=0.05, **kwargs):
super(SteamController, self).__init__(
controls=[
Button("X", 307, sname='square'),
Button("Y", 308, sname='triangle'),
Button("B", 305, sname='circle'),
Button("A", 304, sname='cross'),
Button("Left", 314, sname='select'),
Button("Right", 315, sname='start'),
Button("Steam", 316, sname='home'),
Button("Left Stick Click", 317, sname='ls'),
Button("Right Trackpad Click", 318, sname='rs'),
Button("Right Trackpad Touch", 290, sname='rtouch'),
Button("Left Trackpad Touch", 289, sname='dtouch'),
Button('Top Left Trigger', 310, sname='l1'),
Button('Mid Left Trigger', 312, sname='l2'),
Button('Bottom Left Trigger', 336, sname='l3'),
Button('Top Right Trigger', 311, sname='r1'),
Button('Mid Right Trigger', 313, sname='r2'),
Button('Bottom Right Trigger', 337, sname='r3'),
Button('D-pad left', 546, sname='dleft'),
Button('D-pad right', 547, sname='dright'),
Button('D-pad up', 544, sname='dup'),
Button('D-pad down', 545, sname='ddown'),
CentredAxis("Left Stick Horizontal", -32768, 32768, 0, sname='lx'),
CentredAxis("Left Stick Vertical", 32768, -32768, 1, sname='ly'),
CentredAxis("Right Trackpad Horizontal", -32768, 32768, 3, sname='rx'),
CentredAxis("Right Trackpad Vertical", 32768, -32768, 4, sname='ry'),
CentredAxis("Left Trackpad Horizontal", -32768, 32768, 16, sname='dx'),
CentredAxis("Left Trackpad Vertical", 32768, -32768, 17, sname='dy'),
TriggerAxis("Left Trigger", 0, 255, 21, sname='lt'),
TriggerAxis("Right Trigger", 0, 255, 20, sname='rt')
],
dead_zone=dead_zone,
hot_zone=hot_zone,
**kwargs)
@staticmethod
def registration_ids():
return [(10462, 4418)]
def __repr__(self):
return 'Valve Steam Controller'
|
class SteamController(Controller):
'''
Wireless steam controller. As of Jan 2021 this works with modern linux installations without
any messing around, and supports a lot of extra controls as a result!
The unusual controls are as follows, firstly buttons. Note that both the trackpads have
touch buttons as well as the click (on the right trackpad) and the d-pad 'buttons' on the
left one. The controller doesn't have a true d-pad, but you can use the left trackpad in
place of one (although it's heavy to activate)
============= ================
Standard name Steam Controller
------------- ----------------
square X
triangle Y
circle B
cross A
ls Left stick click
rs Right trackpad click
rtouch Right trackpad touch
select Left arrow
start Right arrow
home Steam button
dleft DPad left click
dup DPad up click
dright DPad right click
ddown DPad down click
dtouch DPad (left trackpad) touch
l1 Top left trigger
l2 Middle left trigger
l3 Base left trigger
r1 Top right trigger
r2 Middle right trigger
r3 Base right trigger
============= ================
The controller has three xy axes with corresponding circular axes as well as analogue
triggers on the middle trigger buttons:
============= ================
Standard name Steam Controller
------------- ----------------
lx Stick horizontal
ly Stick vertical
rx Right trackpad horizontal
ry Right trackpad vertical
dx Left trackpad horizontal
dy Left trackpad vertical
lt Middle left trigger
rt Middle right trigger
============= ================
'''
def __init__(self, dead_zone=0.1, hot_zone=0.05, **kwargs):
pass
@staticmethod
def registration_ids():
pass
def __repr__(self):
pass
| 5 | 1 | 13 | 0 | 13 | 0 | 1 | 1.12 | 1 | 4 | 3 | 0 | 2 | 0 | 3 | 44 | 96 | 7 | 42 | 5 | 37 | 47 | 7 | 4 | 3 | 1 | 5 | 0 | 3 |
6,219 |
ApproxEng/approxeng.input
|
src/python/approxeng/input/switch.py
|
input.switch.SwitchJoyConLeft
|
class SwitchJoyConLeft(Controller):
"""
Nintendo Switch Joycon controller, curently only the Left Controller
being used in horizontal mote, i.e. a single controller and not paired
with the righthand controller.
"""
def __init__(self, dead_zone=0.05, hot_zone=0.05, **kwargs):
"""
Create a new Nintendo Switch Joycon controller instance
Left hand controller only
:param float dead_zone:
Used to set the dead zone for each :class:`approxeng.input.CentredAxis` and
:class:`approxeng.input.TriggerAxis` in the controller.
:param float hot_zone:
Used to set the hot zone for each :class:`approxeng.input.CentredAxis` and
:class:`approxeng.input.TriggerAxis` in the controller.
"""
super(SwitchJoyConLeft, self).__init__(
controls=[
Button("Right", 305, sname="circle"),
Button("Up", 307, sname="triangle"),
Button("Left", 306, sname="square"),
Button("Down", 304, sname="cross"),
Button("Left Stick", 314, sname="ls"),
Button("Home", 317, sname="home"),
Button("Minus", 312, sname="start"),
Button("SL", 308, sname="l1"),
Button("SR", 309, sname="r1"),
CentredAxis("Left Horizontal", -1, 1, 16, sname="lx"),
CentredAxis("Left Vertical", 1, -1, 17, sname="ly")
],
dead_zone=dead_zone,
hot_zone=hot_zone,
**kwargs)
@staticmethod
def registration_ids():
"""
:return: list of (vendor_id, product_id) for this controller
"""
return [(0x57e, 0x2006)]
def __repr__(self):
return 'Nintendo Switch JoyCon controller (Left)'
|
class SwitchJoyConLeft(Controller):
'''
Nintendo Switch Joycon controller, curently only the Left Controller
being used in horizontal mote, i.e. a single controller and not paired
with the righthand controller.
'''
def __init__(self, dead_zone=0.05, hot_zone=0.05, **kwargs):
'''
Create a new Nintendo Switch Joycon controller instance
Left hand controller only
:param float dead_zone:
Used to set the dead zone for each :class:`approxeng.input.CentredAxis` and
:class:`approxeng.input.TriggerAxis` in the controller.
:param float hot_zone:
Used to set the hot zone for each :class:`approxeng.input.CentredAxis` and
:class:`approxeng.input.TriggerAxis` in the controller.
'''
pass
@staticmethod
def registration_ids():
'''
:return: list of (vendor_id, product_id) for this controller
'''
pass
def __repr__(self):
pass
| 5 | 3 | 13 | 1 | 7 | 4 | 1 | 0.75 | 1 | 3 | 2 | 0 | 2 | 0 | 3 | 44 | 48 | 6 | 24 | 5 | 19 | 18 | 7 | 4 | 3 | 1 | 5 | 0 | 3 |
6,220 |
ApproxEng/approxeng.input
|
scripts/tiny4wd_drive.py
|
tiny4wd_drive.RobotStopException
|
class RobotStopException(Exception):
"""
The simplest possible subclass of Exception, we'll raise this if we want to stop the robot
for any reason. Creating a custom exception like this makes the code more readable later.
"""
pass
|
class RobotStopException(Exception):
'''
The simplest possible subclass of Exception, we'll raise this if we want to stop the robot
for any reason. Creating a custom exception like this makes the code more readable later.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 2 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 6 | 0 | 2 | 1 | 1 | 4 | 2 | 1 | 1 | 0 | 3 | 0 | 0 |
6,221 |
ApproxEng/approxeng.input
|
src/python/approxeng/input/gui/profiler.py
|
profiler.DisplayState
|
class DisplayState:
def __init__(self, screen, profile, profiler, axis_keys, button_keys):
self.screen = screen
self.profile = profile
self.profiler = profiler
self.axis_keys = axis_keys
self.button_keys = button_keys
self.line = 0
self.all_controls = [*BUTTON_NAMES, *AXIS_NAMES]
self.control = self.all_controls[0]
# Disable echo to terminal
curses.noecho()
# Hide the cursor
curses.curs_set(0)
# Contrast colour for UI
curses.init_pair(1, curses.COLOR_YELLOW, curses.COLOR_BLACK)
# Highlight
curses.init_pair(2, curses.COLOR_BLACK, curses.COLOR_WHITE)
# Enable colour
curses.start_color()
# Clear the screen
screen.clear()
# Enable key events for special keys i.e. arrows, backspace
screen.keypad(True)
def start(self):
self.screen.clear()
self.line = 0
def println(self, string, contrast=False):
try:
if contrast:
self.screen.addstr(self.line, 0, string, curses.color_pair(1))
else:
self.screen.addstr(self.line, 0, string)
except curses.error:
pass
self.line += 1
def newline(self):
self.line += 1
def print_header(self, string):
s = '——' + string
s += '—' * (80 - len(s))
self.println(s, True)
@property
def control_is_button(self):
return self.control in BUTTON_NAMES
@property
def control_is_axis(self):
return self.control in AXIS_NAMES
def select_next_control(self):
control_index = self.all_controls.index(self.control)
self.control = self.all_controls[(control_index + 1) % len(self.all_controls)]
def select_previous_control(self):
control_index = self.all_controls.index(self.control)
self.control = self.all_controls[(control_index - 1) % len(self.all_controls)]
def select_next_row(self):
pass
def select_previous_row(self):
pass
def show_axis(self, row, col, axis):
control = self.axis_keys[AXIS_NAMES.index(axis)]
try:
if self.control == axis:
# Pick up either all changes, or binary changes only if the axis starts with 'd'
changes = self.profiler.axis_changes if axis[0] != 'd' else self.profiler.binary_axis_changes
if changes:
# Currently editing this axis, show live information if available
code, min_value, max_value, current_value = changes[0]
self.profile.set_axis_range(axis, code, min_value, max_value)
rep = self.profile.axes[axis].build_repr(axis=axis, control=control, current_value=current_value)
else:
rep = self.profile.axes[axis].build_repr(axis=axis, control=control)
self.screen.addstr(row, col, rep, curses.color_pair(2))
else:
self.screen.addstr(row, col, self.profile.axes[axis].build_repr(axis=axis, control=control))
except curses.error:
pass
def show_button(self, row, col, button):
control = self.button_keys[BUTTON_NAMES.index(button)]
try:
if self.control == button:
if self.profiler.last_button_pressed:
self.profile.set_button(button, self.profiler.last_button_pressed)
rep = f'[{control}] {button} : {self.profile.buttons[button] or "---"}'
self.screen.addstr(row, col, rep, curses.color_pair(2))
else:
rep = f'[{control}] {button} : {self.profile.buttons[button] or "---"}'
self.screen.addstr(row, col, rep)
except curses.error:
pass
|
class DisplayState:
def __init__(self, screen, profile, profiler, axis_keys, button_keys):
pass
def start(self):
pass
def println(self, string, contrast=False):
pass
def newline(self):
pass
def print_header(self, string):
pass
@property
def control_is_button(self):
pass
@property
def control_is_axis(self):
pass
def select_next_control(self):
pass
def select_previous_control(self):
pass
def select_next_row(self):
pass
def select_previous_row(self):
pass
def show_axis(self, row, col, axis):
pass
def show_button(self, row, col, button):
pass
| 16 | 0 | 7 | 0 | 6 | 1 | 2 | 0.11 | 0 | 0 | 0 | 0 | 13 | 8 | 13 | 13 | 103 | 14 | 80 | 33 | 64 | 9 | 74 | 31 | 60 | 5 | 0 | 3 | 22 |
6,222 |
ApproxEng/approxeng.input
|
src/python/approxeng/input/selectbinder.py
|
input.selectbinder.ControllerResource
|
class ControllerResource:
"""
General resource which binds one or more controllers on entry and unbinds the event listening thread on exit.
"""
def __init__(self, *requirements, print_events=False, **kwargs):
"""
Create a new resource to bind and access one or more controllers. If no additional arguments are supplied this
will find the first controller of any kind enabled by the library. Otherwise the requirements must be provided
as a list of ControllerRequirement
:param ControllerRequirement requirements:
ControllerRequirement instances used, in order, to find and bind controllers. If empty this will
be equivalent to supplying a single unfiltered requirement and will match the first specified controller.
:param bool print_events:
Defaults to False, if set to True then all events picked up by the binder will be printed to stdout. Use
this when you're trying to figure out what events correspond to what axes and buttons!
:param kwargs:
Any addition keyword arguments are passed to the constructors for the controller classes. This is useful
particularly to specify e.g. dead and hot zone ranges on discovery.
:raises ControllerNotFoundError:
If the requirement can't be satisfied, or no requirements are specified but there aren't any controllers.
"""
self.discoveries = find_matching_controllers(*requirements, **kwargs)
self.unbind = None
self.print_events = print_events
def __enter__(self):
"""
Called on entering the resource block, returns the controller passed into the constructor.
"""
self.unbind = bind_controllers(*self.discoveries, print_events=self.print_events)
if len(self.discoveries) == 1:
return self.discoveries[0].controller
else:
return tuple(discovery.controller for discovery in self.discoveries)
def __exit__(self, exc_type, exc_value, traceback):
"""
Called on resource exit, unbinds the controller, removing the listening thread.
"""
self.unbind()
|
class ControllerResource:
'''
General resource which binds one or more controllers on entry and unbinds the event listening thread on exit.
'''
def __init__(self, *requirements, print_events=False, **kwargs):
'''
Create a new resource to bind and access one or more controllers. If no additional arguments are supplied this
will find the first controller of any kind enabled by the library. Otherwise the requirements must be provided
as a list of ControllerRequirement
:param ControllerRequirement requirements:
ControllerRequirement instances used, in order, to find and bind controllers. If empty this will
be equivalent to supplying a single unfiltered requirement and will match the first specified controller.
:param bool print_events:
Defaults to False, if set to True then all events picked up by the binder will be printed to stdout. Use
this when you're trying to figure out what events correspond to what axes and buttons!
:param kwargs:
Any addition keyword arguments are passed to the constructors for the controller classes. This is useful
particularly to specify e.g. dead and hot zone ranges on discovery.
:raises ControllerNotFoundError:
If the requirement can't be satisfied, or no requirements are specified but there aren't any controllers.
'''
pass
def __enter__(self):
'''
Called on entering the resource block, returns the controller passed into the constructor.
'''
pass
def __exit__(self, exc_type, exc_value, traceback):
'''
Called on resource exit, unbinds the controller, removing the listening thread.
'''
pass
| 4 | 4 | 12 | 1 | 4 | 7 | 1 | 1.92 | 0 | 1 | 0 | 0 | 3 | 3 | 3 | 3 | 43 | 5 | 13 | 7 | 9 | 25 | 12 | 7 | 8 | 2 | 0 | 1 | 4 |
6,223 |
ApproxEng/approxeng.input
|
src/python/approxeng/input/controllers.py
|
input.controllers.ControllerRequirement
|
class ControllerRequirement:
"""
Represents a requirement for a single controller, allowing restriction on type. We might add more filtering options
later, such as requiring a minimum number of axes, or the presence of a particular control. If you want that now,
you can subclass this and pass it into the find_matching_controllers and similar functions.
"""
def __init__(self, require_class=None, require_snames=None, require_ff=False):
"""
Create a new requirement
:param require_class:
If specified, this should be a subclass of :class:`approxeng.input.Controller`, only controllers which match
this class will be accepted. Defaults to None, accepting any available controller class.
:param require_snames:
If specified, this should be a list of strings containing snames of controls (buttons or axes) that must be
present in the controller. Use this when you know what controls you need but don't mind which controller
actually implements them.
:param require_ff:
If true, requires controllers with at least one force-feedback compatible device node
"""
self.require_class = require_class
self.snames = require_snames
self.require_ff = require_ff
def accept(self, discovery: ControllerDiscovery):
"""
Returns True if the supplied ControllerDiscovery matches this requirement, False otherwise
"""
if self.require_class is not None and not isinstance(discovery.controller, self.require_class):
return False
if self.snames is not None:
all_controls = discovery.controller.buttons.names + discovery.controller.axes.names
for sname in self.snames:
if sname not in all_controls:
return False
if self.require_ff and discovery.has_ff is False:
return False
return True
|
class ControllerRequirement:
'''
Represents a requirement for a single controller, allowing restriction on type. We might add more filtering options
later, such as requiring a minimum number of axes, or the presence of a particular control. If you want that now,
you can subclass this and pass it into the find_matching_controllers and similar functions.
'''
def __init__(self, require_class=None, require_snames=None, require_ff=False):
'''
Create a new requirement
:param require_class:
If specified, this should be a subclass of :class:`approxeng.input.Controller`, only controllers which match
this class will be accepted. Defaults to None, accepting any available controller class.
:param require_snames:
If specified, this should be a list of strings containing snames of controls (buttons or axes) that must be
present in the controller. Use this when you know what controls you need but don't mind which controller
actually implements them.
:param require_ff:
If true, requires controllers with at least one force-feedback compatible device node
'''
pass
def accept(self, discovery: ControllerDiscovery):
'''
Returns True if the supplied ControllerDiscovery matches this requirement, False otherwise
'''
pass
| 3 | 3 | 16 | 1 | 8 | 8 | 4 | 1.25 | 0 | 1 | 1 | 0 | 2 | 3 | 2 | 2 | 39 | 3 | 16 | 8 | 13 | 20 | 16 | 8 | 13 | 6 | 0 | 3 | 7 |
6,224 |
ApproxEng/approxeng.input
|
src/python/approxeng/input/__init__.py
|
input.TriggerAxis
|
class TriggerAxis(Axis):
"""
A single analogue axis where the expected output range is 0.0 to 1.0. Typically this is used for triggers, where the
resting position is 0.0 and any interaction causes higher values. Whether a particular controller exposes triggers
as axes or as buttons depends on the hardware - the PS3 front triggers appear as buttons, the XBox One triggers as
axes.
"""
def __init__(self, name: str, min_raw_value: int, max_raw_value: int, axis_event_code: int, dead_zone=0.0,
hot_zone=0.0, sname: Optional[str] = None, button_sname: Optional[str] = None,
button_trigger_value=0.5):
"""
Create a new TriggerAxis - this will be done internally within the :class:`~approxeng.input.Controller`
sub-class.
:param name:
A friendly name for the axis
:param min_raw_value:
The value read from the event system when the trigger is not pressed
:param max_raw_value:
The value read from the event system when the trigger is fully pressed
:param axis_event_code:
The evdev code for this axis, used when dispatching events to it from an Axes object
:param dead_zone:
The proportion of the trigger range which will be treated as equivalent to no press
:param hot_zone:
The proportion of the trigger range which will be treated as equivalent to fully depressing the trigger
:param sname:
The standard name for this trigger, if specified
:param button_sname:
If provided, this creates a new Button internally which will be triggered by changes to the axis value. This
is useful for triggers which have axis representations but no corresponding button presses such as the XBox1
controller front triggers. If this is set to None then no button is created
:param button_trigger_value:
Defaulting to 0.5, this value determines the point in the trigger axis' range at which point the button is
regarded as being pressed or released.
"""
self.name = name
self.max = 0.9
self.min = 0.1
self.__value = self.min
self.dead_zone = dead_zone
self.hot_zone = hot_zone
self.min_raw_value = min_raw_value
self.max_raw_value = max_raw_value
self.axis_event_code = axis_event_code
self.sname = sname
self.buttons = None
self.button_trigger_value = button_trigger_value
if button_sname is not None:
self.button = Button(name='{}_trigger_button'.format(name),
key_code='{}_trigger_button'.format(axis_event_code),
sname=button_sname)
else:
self.button = None
def _input_to_raw_value(self, value: int) -> float:
"""
Convert the value read from evdev to a 0.0 to 1.0 range.
:internal:
:param value:
a value ranging from the defined minimum to the defined maximum value.
:return:
0.0 at minimum, 1.0 at maximum, linearly interpolating between those two points.
"""
return (float(value) - self.min_raw_value) / self.max_raw_value
@property
def raw_value(self) -> float:
"""
Get an uncorrected value for this trigger
:return: a float value, 0.0 when not pressed, to 1.0 when fully pressed
"""
return self.__value
@property
def value(self) -> float:
"""
Get a centre-compensated, scaled, value for the axis, taking any dead-zone into account. The value will
scale from 0.0 at the edge of the dead-zone to 1.0 (positive) at the extreme position of
the trigger or the edge of the hot zone, if defined as other than 1.0.
:return:
a float value, 0.0 when not pressed or within the dead zone, to 1.0 when fully pressed or in the hot zone
"""
return map_single_axis(self.min, self.max, self.dead_zone, self.hot_zone, self.__value)
def reset(self):
"""
Reset calibration (max, min and centre values) for this axis specifically.
:internal:
"""
self.max = 0.9
self.min = 0.1
def receive_device_value(self, raw_value: int):
"""
Set a new value, called from within the joystick implementation class when parsing the event queue.
:param raw_value: the raw value from the joystick hardware
:internal:
"""
new_value = self._input_to_raw_value(raw_value)
if self.button is not None:
if new_value > (self.button_trigger_value + 0.05) > self.__value:
self.buttons.button_pressed(self.button.key_code)
elif new_value < (self.button_trigger_value - 0.05) < self.__value:
self.buttons.button_released(self.button.key_code)
self.__value = new_value
if new_value > self.max:
self.max = new_value
elif new_value < self.min:
self.min = new_value
def __str__(self):
return "TriggerAxis name={}, sname={}, corrected_value={}".format(self.name, self.sname, self.value)
|
class TriggerAxis(Axis):
'''
A single analogue axis where the expected output range is 0.0 to 1.0. Typically this is used for triggers, where the
resting position is 0.0 and any interaction causes higher values. Whether a particular controller exposes triggers
as axes or as buttons depends on the hardware - the PS3 front triggers appear as buttons, the XBox One triggers as
axes.
'''
def __init__(self, name: str, min_raw_value: int, max_raw_value: int, axis_event_code: int, dead_zone=0.0,
hot_zone=0.0, sname: Optional[str] = None, button_sname: Optional[str] = None,
button_trigger_value=0.5):
'''
Create a new TriggerAxis - this will be done internally within the :class:`~approxeng.input.Controller`
sub-class.
:param name:
A friendly name for the axis
:param min_raw_value:
The value read from the event system when the trigger is not pressed
:param max_raw_value:
The value read from the event system when the trigger is fully pressed
:param axis_event_code:
The evdev code for this axis, used when dispatching events to it from an Axes object
:param dead_zone:
The proportion of the trigger range which will be treated as equivalent to no press
:param hot_zone:
The proportion of the trigger range which will be treated as equivalent to fully depressing the trigger
:param sname:
The standard name for this trigger, if specified
:param button_sname:
If provided, this creates a new Button internally which will be triggered by changes to the axis value. This
is useful for triggers which have axis representations but no corresponding button presses such as the XBox1
controller front triggers. If this is set to None then no button is created
:param button_trigger_value:
Defaulting to 0.5, this value determines the point in the trigger axis' range at which point the button is
regarded as being pressed or released.
'''
pass
def _input_to_raw_value(self, value: int) -> float:
'''
Convert the value read from evdev to a 0.0 to 1.0 range.
:internal:
:param value:
a value ranging from the defined minimum to the defined maximum value.
:return:
0.0 at minimum, 1.0 at maximum, linearly interpolating between those two points.
'''
pass
@property
def raw_value(self) -> float:
'''
Get an uncorrected value for this trigger
:return: a float value, 0.0 when not pressed, to 1.0 when fully pressed
'''
pass
@property
def value(self) -> float:
'''
Get a centre-compensated, scaled, value for the axis, taking any dead-zone into account. The value will
scale from 0.0 at the edge of the dead-zone to 1.0 (positive) at the extreme position of
the trigger or the edge of the hot zone, if defined as other than 1.0.
:return:
a float value, 0.0 when not pressed or within the dead zone, to 1.0 when fully pressed or in the hot zone
'''
pass
def reset(self):
'''
Reset calibration (max, min and centre values) for this axis specifically.
:internal:
'''
pass
def receive_device_value(self, raw_value: int):
'''
Set a new value, called from within the joystick implementation class when parsing the event queue.
:param raw_value: the raw value from the joystick hardware
:internal:
'''
pass
def __str__(self):
pass
| 10 | 7 | 15 | 1 | 6 | 8 | 2 | 1.26 | 1 | 4 | 1 | 0 | 7 | 13 | 7 | 29 | 121 | 15 | 47 | 26 | 35 | 59 | 38 | 22 | 30 | 6 | 5 | 2 | 13 |
6,225 |
ApproxEng/approxeng.input
|
src/python/approxeng/input/controllers.py
|
input.controllers.ControllerDiscovery
|
class ControllerDiscovery:
"""
Represents a single discovered controller attached to the host. Ordered, with controllers with more axes and buttons
being given a higher ordering, and controllers with force feedback higher than those without, then falling back to
the assigned name.
"""
def __init__(self, controller_class, controller_constructor_args, devices, name):
if not isinstance(devices, list):
self.devices = [devices]
else:
self.devices = devices
self.name = name
self.ff_device = None
for device in self.devices:
if ecodes.EV_FF in device.capabilities():
self.ff_device = device
break
self.controller = controller_class(ff_device=self.ff_device, **controller_constructor_args)
@property
def has_ff(self):
"""
True if there's a force feedback compatible device in this discovery's device list, False otherwise
"""
return self.ff_device is not None
def __repr__(self):
return '{}(devices=[{}], ff={})'.format(self.controller.__class__.__name__,
','.join(device.fn for device in self.devices), self.has_ff)
def __eq__(self, other):
return self.controller.__class__.__name__ == other.controller.__class__.__name__ and self.name == other.name
def __lt__(self, other):
self_axes = len(self.controller.axes.names)
other_axes = len(other.controller.axes.names)
self_buttons = len(self.controller.buttons.names)
other_buttons = len(other.controller.buttons.names)
if self_axes != other_axes:
return self_axes < other_axes
elif self_buttons != other_buttons:
return self_buttons < other_buttons
if self.has_ff != other.has_ff:
return (1 if self.has_ff else 0) < (1 if other.has_ff else 0)
return self.name < other.name
|
class ControllerDiscovery:
'''
Represents a single discovered controller attached to the host. Ordered, with controllers with more axes and buttons
being given a higher ordering, and controllers with force feedback higher than those without, then falling back to
the assigned name.
'''
def __init__(self, controller_class, controller_constructor_args, devices, name):
pass
@property
def has_ff(self):
'''
True if there's a force feedback compatible device in this discovery's device list, False otherwise
'''
pass
def __repr__(self):
pass
def __eq__(self, other):
pass
def __lt__(self, other):
pass
| 7 | 2 | 7 | 0 | 6 | 1 | 3 | 0.24 | 0 | 1 | 0 | 0 | 5 | 4 | 5 | 5 | 46 | 5 | 33 | 16 | 26 | 8 | 29 | 15 | 23 | 6 | 0 | 2 | 13 |
6,226 |
ApproxEng/approxeng.input
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ApproxEng_approxeng.input/src/python/approxeng/input/gui/controllerclasses.py
|
controllerclasses.show_controller_classes.ControllerMeta
|
class ControllerMeta:
vendor: int
product: int
name: str
class_name: str
|
class ControllerMeta:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 5 | 0 | 5 | 1 | 4 | 0 | 5 | 1 | 4 | 0 | 0 | 0 | 0 |
6,227 |
ApproxEng/approxeng.input
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ApproxEng_approxeng.input/src/python/approxeng/input/__init__.py
|
input.Buttons.ButtonState
|
class ButtonState:
"""
Per-button state, including any handlers registered, whether the button was pressed since the last call to
check, whether it is currently pressed, and the timestamp of the last button press. From this we can handle all
possible forms of interaction required.
"""
def __init__(self, button):
self.button_handlers = []
self.is_pressed = False
self.was_pressed_since_last_check = False
self.was_released_since_last_check = False
self.last_pressed = None
self.button = button
|
class ButtonState:
'''
Per-button state, including any handlers registered, whether the button was pressed since the last call to
check, whether it is currently pressed, and the timestamp of the last button press. From this we can handle all
possible forms of interaction required.
'''
def __init__(self, button):
pass
| 2 | 1 | 7 | 0 | 7 | 0 | 1 | 0.63 | 0 | 0 | 0 | 0 | 1 | 6 | 1 | 1 | 14 | 1 | 8 | 8 | 6 | 5 | 8 | 8 | 6 | 1 | 0 | 0 | 1 |
6,228 |
ApproxEng/approxeng.input
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ApproxEng_approxeng.input/src/python/approxeng/input/__init__.py
|
input.Controller.__init__.ControllerStream
|
class ControllerStream(object):
"""
Class to produce streams for values from the parent controller on demand.
"""
def __init__(self, controller):
self.controller = controller
def __getitem__(self, item):
"""
:param item:
Name of an item or items to fetch, referring to them by sname, so either axes or
buttons.
:return:
A generator which will emit the value of that item or items every time it's called, in effect
creating an infinite stream of values for the given item or items.
"""
def generator():
while self.controller.connected:
yield self.controller.__getitem__(item)
return generator()
|
class ControllerStream(object):
'''
Class to produce streams for values from the parent controller on demand.
'''
def __init__(self, controller):
pass
def __getitem__(self, item):
'''
:param item:
Name of an item or items to fetch, referring to them by sname, so either axes or
buttons.
:return:
A generator which will emit the value of that item or items every time it's called, in effect
creating an infinite stream of values for the given item or items.
'''
pass
def generator():
pass
| 4 | 2 | 7 | 1 | 3 | 3 | 1 | 1.38 | 1 | 0 | 0 | 0 | 2 | 1 | 2 | 2 | 23 | 4 | 8 | 5 | 4 | 11 | 8 | 5 | 4 | 2 | 1 | 1 | 4 |
6,229 |
ApproxEng/approxeng.input
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ApproxEng_approxeng.input/src/python/approxeng/input/controllers.py
|
input.controllers.print_devices.MyPrettyPrinter
|
class MyPrettyPrinter(pprint.PrettyPrinter):
def format(self, object, context, maxlevels, level):
if isinstance(object, int):
return '0x{:X}'.format(object), True, False
return super().format(object, context, maxlevels, level)
|
class MyPrettyPrinter(pprint.PrettyPrinter):
def format(self, object, context, maxlevels, level):
pass
| 2 | 0 | 4 | 0 | 4 | 0 | 2 | 0 | 1 | 2 | 0 | 0 | 1 | 0 | 1 | 31 | 5 | 0 | 5 | 2 | 3 | 0 | 5 | 2 | 3 | 2 | 1 | 1 | 2 |
6,230 |
ApproxEng/approxeng.input
|
src/python/approxeng/input/__init__.py
|
input.Axes
|
class Axes(object):
"""
A set of TriggerAxis or CentredAxis instances to which events should be routed based on event code. Contains methods
to reset calibration on all axes, or to centre all axes for which this is meaningful.
"""
def __init__(self, axes):
"""
Create a new Axes instance, this will be done within the controller classes, you never have to explicitly
instantiate this yourself.
:param axes:
a sequence of :class:`approxeng.input.TriggerAxis` or :class:`approxeng.input.CentredAxis` or
:class:`approxeng.input.BinaryAxis` containing all the axes the controller supports.
"""
self.axes = axes
self.axes_by_code = {axis.axis_event_code: axis for axis in axes}
self.axes_by_sname = {axis.sname: axis for axis in axes}
# Look to see whether we've got pairs of lx,ly and / or rx,ry and create corresponding circular axes
def add_circular_axis(rootname):
xname = rootname + 'x'
yname = rootname + 'y'
if xname in self.axes_by_sname and yname in self.axes_by_sname:
self.axes_by_sname[rootname] = CircularCentredAxis(x=self.axes_by_sname[xname],
y=self.axes_by_sname[yname])
for prefix in ['l', 'r', 'd']:
add_circular_axis(prefix)
def axis_updated(self, event: InputEvent, prefix=None):
"""
Called to process an absolute axis event from evdev, this is called internally by the controller implementations
:internal:
:param event:
The evdev event to process
:param prefix:
If present, a named prefix that should be applied to the event code when searching for the axis
"""
if prefix is not None:
axis = self.axes_by_code.get(prefix + str(event.code))
else:
axis = self.axes_by_code.get(event.code)
if axis is not None:
axis.receive_device_value(event.value)
else:
logger.debug('Unknown axis code {} ({}), value {}'.format(event.code, prefix, event.value))
def set_axis_centres(self, *args):
"""
Sets the centre points for each axis to the current value for that axis. This centre value is used when
computing the value for the axis and is subtracted before applying any scaling. This will only be applied
to CentredAxis instances
"""
for axis in self.axes_by_code.values():
if isinstance(axis, CentredAxis):
axis.centre = axis.value
def reset_axis_calibration(self, *args):
"""
Resets any previously defined axis calibration to 0.0 for all axes
"""
for axis in self.axes:
axis.reset()
def __str__(self):
return list("{}={}".format(axis.name, axis.value) for axis in self.axes_by_code.values()).__str__()
@property
def names(self) -> list[str]:
"""
The snames of all axis objects
"""
return sorted([name for name in self.axes_by_sname.keys() if name != ''])
@property
def active_axes(self) -> ['Axis']:
"""
Return a sequence of all Axis objects which are not in their resting positions
"""
return [axis for axis in self.axes if axis.value != 0]
def __getitem__(self, sname: str) -> Optional['Axis']:
"""
Get an axis by sname, if present
:param sname:
The standard name to search
:return:
An axis object, or None if no such axis exists
"""
return self.axes_by_sname.get(sname)
def __getattr__(self, item) -> 'Axis':
"""
Called when an unresolved attribute is requested, retrieves the Axis object for the given sname
:param item:
the standard name of the axis to query
:return:
the corrected value of the axis, or raise AttributeError if no such axis is present
:raise:
AttributeError if there's no axis with this name
"""
if item in self.axes_by_sname:
return self.get(item)
raise AttributeError
def __contains__(self, item: str) -> bool:
"""
Check whether a given axis, referenced by sname, exists
:param item:
The sname of the axis to search
:return:
True if the axis exists, false otherwise
"""
return item in self.axes_by_sname
|
class Axes(object):
'''
A set of TriggerAxis or CentredAxis instances to which events should be routed based on event code. Contains methods
to reset calibration on all axes, or to centre all axes for which this is meaningful.
'''
def __init__(self, axes):
'''
Create a new Axes instance, this will be done within the controller classes, you never have to explicitly
instantiate this yourself.
:param axes:
a sequence of :class:`approxeng.input.TriggerAxis` or :class:`approxeng.input.CentredAxis` or
:class:`approxeng.input.BinaryAxis` containing all the axes the controller supports.
'''
pass
def add_circular_axis(rootname):
pass
def axis_updated(self, event: InputEvent, prefix=None):
'''
Called to process an absolute axis event from evdev, this is called internally by the controller implementations
:internal:
:param event:
The evdev event to process
:param prefix:
If present, a named prefix that should be applied to the event code when searching for the axis
'''
pass
def set_axis_centres(self, *args):
'''
Sets the centre points for each axis to the current value for that axis. This centre value is used when
computing the value for the axis and is subtracted before applying any scaling. This will only be applied
to CentredAxis instances
'''
pass
def reset_axis_calibration(self, *args):
'''
Resets any previously defined axis calibration to 0.0 for all axes
'''
pass
def __str__(self):
pass
@property
def names(self) -> list[str]:
'''
The snames of all axis objects
'''
pass
@property
def active_axes(self) -> ['Axis']:
'''
Return a sequence of all Axis objects which are not in their resting positions
'''
pass
def __getitem__(self, sname: str) -> Optional['Axis']:
'''
Get an axis by sname, if present
:param sname:
The standard name to search
:return:
An axis object, or None if no such axis exists
'''
pass
def __getattr__(self, item) -> 'Axis':
'''
Called when an unresolved attribute is requested, retrieves the Axis object for the given sname
:param item:
the standard name of the axis to query
:return:
the corrected value of the axis, or raise AttributeError if no such axis is present
:raise:
AttributeError if there's no axis with this name
'''
pass
def __contains__(self, item: str) -> bool:
'''
Check whether a given axis, referenced by sname, exists
:param item:
The sname of the axis to search
:return:
True if the axis exists, false otherwise
'''
pass
| 14 | 10 | 10 | 1 | 4 | 5 | 2 | 1.27 | 1 | 6 | 2 | 0 | 10 | 3 | 10 | 10 | 120 | 18 | 45 | 23 | 31 | 57 | 40 | 21 | 28 | 3 | 1 | 2 | 19 |
6,231 |
ApproxEng/approxeng.input
|
src/python/approxeng/input/__init__.py
|
input.BinaryAxis
|
class BinaryAxis(Axis):
"""
A fake 'analogue' axis which actually corresponds to a pair of buttons. Once associated with a Buttons instance
it routes events through to the Buttons instance to create button presses corresponding to axis movements. This is
necessary as some controllers expose buttons, especially D-pad buttons, as a pair of axes rather than four buttons,
but we almost certainly want to treat them as buttons the way most controllers do.
"""
def __init__(self, name, axis_event_code, b1name=None, b2name=None):
"""
Create a new binary axis, used to route axis events through to a pair of buttons, which are created as
part of this constructor
:param name:
Name for the axis, use this to describe the axis, it's not used for anything else
:param axis_event_code:
The evdev event code for changes to this axis
:param b1name:
The sname of the button corresponding to negative values of the axis.
:param b2name:
The sname of the button corresponding to positive values of the axis
"""
self.name = name
self.axis_event_code = axis_event_code
self.b1 = Button('{}_left_button'.format(name), key_code='{}_left'.format(axis_event_code), sname=b1name)
self.b2 = Button('{}_right_button'.format(name), key_code='{}_right'.format(axis_event_code), sname=b2name)
self.buttons = None
self.last_value = 0
self.sname = ''
self.__value = 0
def receive_device_value(self, raw_value: int):
self.__value = raw_value
if self.buttons is not None:
if self.last_value < 0:
self.buttons.button_released(self.b1.key_code)
elif self.last_value > 0:
self.buttons.button_released(self.b2.key_code)
self.last_value = raw_value
if raw_value < 0:
self.buttons.button_pressed(self.b1.key_code)
elif raw_value > 0:
self.buttons.button_pressed(self.b2.key_code)
@property
def value(self):
"""
You probably don't want to actually get the value of this axis, use the generated buttons instead.
:returns int:
The raw value from the evdev events driving this axis.
"""
return self.__value
def __str__(self):
return "BinaryAxis name={}, sname={}, corrected_value={}".format(self.name, self.sname, self.value)
|
class BinaryAxis(Axis):
'''
A fake 'analogue' axis which actually corresponds to a pair of buttons. Once associated with a Buttons instance
it routes events through to the Buttons instance to create button presses corresponding to axis movements. This is
necessary as some controllers expose buttons, especially D-pad buttons, as a pair of axes rather than four buttons,
but we almost certainly want to treat them as buttons the way most controllers do.
'''
def __init__(self, name, axis_event_code, b1name=None, b2name=None):
'''
Create a new binary axis, used to route axis events through to a pair of buttons, which are created as
part of this constructor
:param name:
Name for the axis, use this to describe the axis, it's not used for anything else
:param axis_event_code:
The evdev event code for changes to this axis
:param b1name:
The sname of the button corresponding to negative values of the axis.
:param b2name:
The sname of the button corresponding to positive values of the axis
'''
pass
def receive_device_value(self, raw_value: int):
pass
@property
def value(self):
'''
You probably don't want to actually get the value of this axis, use the generated buttons instead.
:returns int:
The raw value from the evdev events driving this axis.
'''
pass
def __str__(self):
pass
| 6 | 3 | 11 | 1 | 6 | 4 | 2 | 0.85 | 1 | 2 | 1 | 0 | 4 | 8 | 4 | 26 | 57 | 7 | 27 | 14 | 21 | 23 | 24 | 13 | 19 | 6 | 5 | 2 | 9 |
6,232 |
ApproxEng/approxeng.input
|
src/python/approxeng/input/__init__.py
|
input.Button
|
class Button(object):
"""
A single button on a controller
"""
def __init__(self, name, key_code=None, sname=None):
"""
Create a new Button - this will be done by the controller implementation classes, you shouldn't create your own
unless you're writing such a class.
:param name:
A friendly name for the button
:param key_code:
The key code for the button, typically an integer used within the button press and release events. Defaults
to None if not used.
:param sname:
The standard name for the button, if available.
"""
self.name = name
self.key_code = key_code
self.sname = sname
def __repr__(self):
return "Button(name={}, code={}, sname={})".format(self.name, self.key_code, self.sname)
|
class Button(object):
'''
A single button on a controller
'''
def __init__(self, name, key_code=None, sname=None):
'''
Create a new Button - this will be done by the controller implementation classes, you shouldn't create your own
unless you're writing such a class.
:param name:
A friendly name for the button
:param key_code:
The key code for the button, typically an integer used within the button press and release events. Defaults
to None if not used.
:param sname:
The standard name for the button, if available.
'''
pass
def __repr__(self):
pass
| 3 | 2 | 9 | 1 | 3 | 6 | 1 | 2 | 1 | 0 | 0 | 0 | 2 | 3 | 2 | 2 | 24 | 3 | 7 | 6 | 4 | 14 | 7 | 6 | 4 | 1 | 1 | 0 | 2 |
6,233 |
ApproxEng/approxeng.input
|
src/python/approxeng/input/switch.py
|
input.switch.SwitchJoyConRight
|
class SwitchJoyConRight(Controller):
"""
Nintendo Switch Joycon controller, curently only the Right controller
being used in horizontal mode, i.e. a single controller and not paired
with the lefthand controller.
"""
def __init__(self, dead_zone=0.05, hot_zone=0.05, **kwargs):
"""
Create a new Nintendo Switch Joycon controller instance
:param float dead_zone:
Used to set the dead zone for each :class:`approxeng.input.CentredAxis` and
:class:`approxeng.input.TriggerAxis` in the controller.
:param float hot_zone:
Used to set the hot zone for each :class:`approxeng.input.CentredAxis` and
:class:`approxeng.input.TriggerAxis` in the controller.
"""
super(SwitchJoyConRight, self).__init__(
controls=[
Button("X", 305, sname="circle"),
Button("Y", 307, sname="triangle"),
Button("B", 306, sname="square"),
Button("A", 304, sname="cross"),
Button("Left Stick", 315, sname="ls"),
Button("Home", 316, sname="home"),
Button("Plus", 313, sname="start"),
Button("SL", 308, sname="l1"),
Button("SR", 309, sname="r1"),
CentredAxis("Left Horizontal", -1, 1, 16, sname="lx"),
CentredAxis("Left Vertical", 1, -1, 17, sname="ly")
],
dead_zone=dead_zone,
hot_zone=hot_zone,
**kwargs)
@staticmethod
def registration_ids():
"""
:return: list of (vendor_id, product_id) for this controller
"""
return [(0x57e, 0x2007)]
def __repr__(self):
return 'Nintendo Switch JoyCon controller (Right)'
|
class SwitchJoyConRight(Controller):
'''
Nintendo Switch Joycon controller, curently only the Right controller
being used in horizontal mode, i.e. a single controller and not paired
with the lefthand controller.
'''
def __init__(self, dead_zone=0.05, hot_zone=0.05, **kwargs):
'''
Create a new Nintendo Switch Joycon controller instance
:param float dead_zone:
Used to set the dead zone for each :class:`approxeng.input.CentredAxis` and
:class:`approxeng.input.TriggerAxis` in the controller.
:param float hot_zone:
Used to set the hot zone for each :class:`approxeng.input.CentredAxis` and
:class:`approxeng.input.TriggerAxis` in the controller.
'''
pass
@staticmethod
def registration_ids():
'''
:return: list of (vendor_id, product_id) for this controller
'''
pass
def __repr__(self):
pass
| 5 | 3 | 12 | 0 | 7 | 4 | 1 | 0.71 | 1 | 3 | 2 | 0 | 2 | 0 | 3 | 44 | 45 | 4 | 24 | 5 | 19 | 17 | 7 | 4 | 3 | 1 | 5 | 0 | 3 |
6,234 |
ApproxEng/approxeng.input
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ApproxEng_approxeng.input/src/python/approxeng/input/selectbinder.py
|
input.selectbinder.bind_controllers.SelectThread
|
class SelectThread(Thread):
def __init__(self):
Thread.__init__(self, name='evdev select thread')
self.daemon = True
self.running = True
self.device_to_controller_discovery = {}
for discovery in discoveries:
for d in discovery.devices:
self.device_to_controller_discovery[d.fn] = discovery
self.all_devices = reduce(
lambda x, y: x + y, [discovery.devices for discovery in discoveries])
def run(self):
for discovery in discoveries:
discovery.controller.device_unique_name = discovery.name
while self.running:
try:
r, w, x = select(self.all_devices, [], [], 0.5)
for fd in r:
active_device = fd
controller_discovery = self.device_to_controller_discovery[active_device.fn]
controller = controller_discovery.controller
controller_devices = controller_discovery.devices
prefix = None
if controller.node_mappings is not None and len(controller_devices) > 1:
try:
prefix = controller.node_mappings[active_device.name]
except KeyError:
pass
for event in active_device.read():
if print_events:
print(event)
if event.type == EV_ABS or event.type == EV_REL:
controller.axes.axis_updated(
event, prefix=prefix)
elif event.type == EV_KEY:
# Button event
if event.value == 1:
# Button down
controller.buttons.button_pressed(
event.code, prefix=prefix)
elif event.value == 0:
# Button up
controller.buttons.button_released(
event.code, prefix=prefix)
except Exception as e:
self.stop(e)
def stop(self, exception=None):
for discovery in discoveries:
discovery.controller.device_unique_name = None
discovery.controller.exception = exception
self.running = False
|
class SelectThread(Thread):
def __init__(self):
pass
def run(self):
pass
def stop(self, exception=None):
pass
| 4 | 0 | 17 | 2 | 14 | 1 | 6 | 0.07 | 1 | 2 | 0 | 0 | 3 | 4 | 3 | 28 | 54 | 7 | 44 | 21 | 40 | 3 | 42 | 20 | 38 | 13 | 1 | 6 | 18 |
6,235 |
ApproxEng/approxeng.input
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ApproxEng_approxeng.input/src/python/approxeng/input/profiling.py
|
input.profiling.Profile.build_controller_class.ProfiledController
|
class ProfiledController(Controller):
def __init__(self, dead_zone=0.05, hot_zone=0.05, **kwargs):
super(ProfiledController, self).__init__(controls=profile.controls,
dead_zone=dead_zone,
hot_zone=hot_zone,
**kwargs)
@staticmethod
def registration_ids():
return [(profile.vendor_id, profile.product_id)]
def __repr__(self) -> str:
return profile.name
|
class ProfiledController(Controller):
def __init__(self, dead_zone=0.05, hot_zone=0.05, **kwargs):
pass
@staticmethod
def registration_ids():
pass
def __repr__(self) -> str:
pass
| 5 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 3 | 1 | 0 | 2 | 0 | 3 | 44 | 14 | 3 | 11 | 5 | 6 | 0 | 7 | 4 | 3 | 1 | 5 | 0 | 3 |
6,236 |
ApproxEng/approxeng.input
|
src/python/approxeng/input/__init__.py
|
input.ButtonPresses
|
class ButtonPresses(object):
"""
Stores the set of buttons pressed within a given time interval
"""
def __init__(self, buttons):
self.buttons = buttons
self.names = list([button.sname for button in buttons])
def __getitem__(self, item):
"""
Return true if a button was pressed, referencing by standard name
:param item: the name to check
:return: true if contained within the press set, false otherwise
"""
if isinstance(item, tuple):
return [(single_item in self.names) for single_item in item]
return item in self.names
def __getattr__(self, item):
"""
Simpler way to query whether a button was pressed by overriding the __getattr__ method
:param item:
sname of the button
:return:
true if the button was pressed, false if it either wasn't pressed or wasn't included in the controller
"""
return item in self.names
def __contains__(self, item):
"""
Contains check for a button sname
:param item:
The sname of the button to check
:return:
True if the button is in the set of pressed buttons, false otherwise
"""
return item in self.names
def __iter__(self):
for name in self.names:
yield name
@property
def has_presses(self):
return len(self.names) > 0
def __repr__(self):
return str(self.names)
|
class ButtonPresses(object):
'''
Stores the set of buttons pressed within a given time interval
'''
def __init__(self, buttons):
pass
def __getitem__(self, item):
'''
Return true if a button was pressed, referencing by standard name
:param item: the name to check
:return: true if contained within the press set, false otherwise
'''
pass
def __getattr__(self, item):
'''
Simpler way to query whether a button was pressed by overriding the __getattr__ method
:param item:
sname of the button
:return:
true if the button was pressed, false if it either wasn't pressed or wasn't included in the controller
'''
pass
def __contains__(self, item):
'''
Contains check for a button sname
:param item:
The sname of the button to check
:return:
True if the button is in the set of pressed buttons, false otherwise
'''
pass
def __iter__(self):
pass
@property
def has_presses(self):
pass
def __repr__(self):
pass
| 9 | 4 | 6 | 0 | 3 | 3 | 1 | 1.1 | 1 | 3 | 0 | 0 | 7 | 2 | 7 | 7 | 52 | 10 | 20 | 12 | 11 | 22 | 19 | 11 | 11 | 2 | 1 | 1 | 9 |
6,237 |
ApproxEng/approxeng.input
|
src/python/approxeng/input/__init__.py
|
input.Buttons
|
class Buttons(object):
"""
A set of buttons on a controller. This class manages event binding and triggering, as well as monitoring button
states and tracking whether buttons are held down, and how long if so. Controller implementations instantiate and
configure an instance of this class when they want to provide button information, the controller is responsible for
translating button events from the underlying operating system frameworks and updating this object appropriately,
user code (i.e. your code if you're reading this) uses the methods on this object to react to button presses.
"""
def __init__(self, buttons_and_axes, ):
"""
Instantiate a new button manager
:param buttons_and_axes:
a list of :class:`approxeng.input.Button` instances which will be managed by this class
"""
buttons = []
for thing in buttons_and_axes:
if isinstance(thing, Button):
buttons.append(thing)
elif isinstance(thing, BinaryAxis):
buttons.append(thing.b1)
buttons.append(thing.b2)
thing.buttons = self
elif isinstance(thing, TriggerAxis):
if thing.button is not None:
buttons.append(thing.button)
thing.buttons = self
self.buttons = {button: Buttons.ButtonState(button) for button in buttons}
self.buttons_by_code = {button.key_code: state for button, state in self.buttons.items()}
self.buttons_by_sname = {button.sname: state for button, state in self.buttons.items()}
self.__presses = None
self.__releases = None
class ButtonState:
"""
Per-button state, including any handlers registered, whether the button was pressed since the last call to
check, whether it is currently pressed, and the timestamp of the last button press. From this we can handle all
possible forms of interaction required.
"""
def __init__(self, button):
self.button_handlers = []
self.is_pressed = False
self.was_pressed_since_last_check = False
self.was_released_since_last_check = False
self.last_pressed = None
self.button = button
def button_pressed(self, key_code, prefix=None):
"""
Called from the controller classes to update the state of this button manager when a button is pressed.
:internal:
:param key_code:
The code specified when populating Button instances
:param prefix:
Applied to key code if present
"""
if prefix is not None:
state = self.buttons_by_code.get(prefix + str(key_code))
else:
state = self.buttons_by_code.get(key_code)
if state is not None:
for handler in state.button_handlers:
handler(state.button)
state.is_pressed = True
state.last_pressed = time()
state.was_pressed_since_last_check = True
else:
logger.debug('button_pressed : Unknown button code {} ({})'.format(key_code, prefix))
def button_released(self, key_code, prefix=None):
"""
Called from the controller classes to update the state of this button manager when a button is released.
:internal:
:param key_code:
The code specified when populating Button instance
:param prefix:
Applied to key code if present
"""
if prefix is not None:
state = self.buttons_by_code.get(prefix + str(key_code))
else:
state = self.buttons_by_code.get(key_code)
if state is not None:
state.is_pressed = False
state.last_pressed = None
state.was_released_since_last_check = True
else:
logger.debug('button_released : Unknown button code {} ({})'.format(key_code, prefix))
@property
def names(self):
"""
The snames of all button objects
"""
return sorted([name for name in self.buttons_by_sname.keys() if name != ''])
@property
def presses(self):
"""
Get the ButtonPresses containing buttons pressed between the most recent two calls to check_presses. This will
call the check_presses method if it has never been called before, and is therefore always safe even if your code
has never called the update function. To make this property actually do something useful, however, you do need
to call check_presses, preferably once immediately before you then want to handle any button presses that may
have happened.
:return:
a ButtonPresses object containing information about which buttons were pressed
"""
if self.__presses is None:
self.check_presses()
return self.__presses
@property
def releases(self):
"""
Analogous to presses, but returns the set of buttons which were released
:return:
a ButtonPresses object containing information about which buttons were released
"""
if self.__releases is None:
self.check_presses()
return self.__releases
def check_presses(self):
"""
Return the set of Buttons which have been pressed since this call was last made, clearing it as we do.
:return:
A ButtonPresses instance which contains buttons which were pressed since this call was last made.
"""
pressed = []
released = []
for button, state in self.buttons.items():
if state.was_pressed_since_last_check:
pressed.append(button)
state.was_pressed_since_last_check = False
if state.was_released_since_last_check:
released.append(button)
state.was_released_since_last_check = False
self.__presses = ButtonPresses(pressed)
self.__releases = ButtonPresses(released)
return self.__presses
def held(self, sname):
"""
Determines whether a button is currently held, identifying it by standard name
:param sname:
The standard name of the button
:return:
None if the button is not held down, or is not available, otherwise the number of seconds as a floating
point value since it was pressed
"""
state = self.buttons_by_sname.get(sname)
if state is not None:
last_pressed = state.last_pressed
if state.is_pressed and last_pressed is not None:
return time() - last_pressed
return None
def __getitem__(self, item):
"""
Get a button by sname, if present
:param item:
The standard name to search
:return:
A Button, or None if no such button exists
"""
return self.buttons_by_sname.get(item).button
def __getattr__(self, item):
"""
Property access to Button instances
:param item:
the sname of the button
:return:
the Button instance, or raise AttributeError if no such button
"""
if item in self.buttons_by_sname:
return self.get(item)
raise AttributeError
def __contains__(self, item):
"""
Check whether a given button, referenced by sname, exists
:param item:
The sname of the button to search
:return:
True if the axis exists, false otherwise
"""
return item in self.buttons_by_sname
def register_button_handler(self, button_handler, buttons):
"""
Register a handler function which will be called when a button is pressed
:param button_handler:
A function which will be called when any of the specified buttons are pressed. The
function is called with the Button that was pressed as the sole argument.
:param [Button] buttons:
A list or one or more buttons which should trigger the handler when pressed. Buttons
are specified as :class:`approxeng.input.Button` instances, in general controller implementations will
expose these as constants such as SixAxis.BUTTON_CIRCLE. A single Button can be specified if only one button
binding is required.
:return:
A no-arg function which can be used to remove this registration
"""
if not isinstance(buttons, list):
buttons = [buttons]
for button in buttons:
state = self.buttons.get(button)
if state is not None:
state.button_handlers.append(button_handler)
def remove():
for button_to_remove in buttons:
state_to_remove = self.buttons.get(button_to_remove)
if state_to_remove is not None:
state_to_remove.button_handlers.remove(button_handler)
return remove
|
class Buttons(object):
'''
A set of buttons on a controller. This class manages event binding and triggering, as well as monitoring button
states and tracking whether buttons are held down, and how long if so. Controller implementations instantiate and
configure an instance of this class when they want to provide button information, the controller is responsible for
translating button events from the underlying operating system frameworks and updating this object appropriately,
user code (i.e. your code if you're reading this) uses the methods on this object to react to button presses.
'''
def __init__(self, buttons_and_axes, ):
'''
Instantiate a new button manager
:param buttons_and_axes:
a list of :class:`approxeng.input.Button` instances which will be managed by this class
'''
pass
class ButtonState:
'''
Per-button state, including any handlers registered, whether the button was pressed since the last call to
check, whether it is currently pressed, and the timestamp of the last button press. From this we can handle all
possible forms of interaction required.
'''
def __init__(self, buttons_and_axes, ):
pass
def button_pressed(self, key_code, prefix=None):
'''
Called from the controller classes to update the state of this button manager when a button is pressed.
:internal:
:param key_code:
The code specified when populating Button instances
:param prefix:
Applied to key code if present
'''
pass
def button_released(self, key_code, prefix=None):
'''
Called from the controller classes to update the state of this button manager when a button is released.
:internal:
:param key_code:
The code specified when populating Button instance
:param prefix:
Applied to key code if present
'''
pass
@property
def names(self):
'''
The snames of all button objects
'''
pass
@property
def presses(self):
'''
Get the ButtonPresses containing buttons pressed between the most recent two calls to check_presses. This will
call the check_presses method if it has never been called before, and is therefore always safe even if your code
has never called the update function. To make this property actually do something useful, however, you do need
to call check_presses, preferably once immediately before you then want to handle any button presses that may
have happened.
:return:
a ButtonPresses object containing information about which buttons were pressed
'''
pass
@property
def releases(self):
'''
Analogous to presses, but returns the set of buttons which were released
:return:
a ButtonPresses object containing information about which buttons were released
'''
pass
def check_presses(self):
'''
Return the set of Buttons which have been pressed since this call was last made, clearing it as we do.
:return:
A ButtonPresses instance which contains buttons which were pressed since this call was last made.
'''
pass
def held(self, sname):
'''
Determines whether a button is currently held, identifying it by standard name
:param sname:
The standard name of the button
:return:
None if the button is not held down, or is not available, otherwise the number of seconds as a floating
point value since it was pressed
'''
pass
def __getitem__(self, item):
'''
Get a button by sname, if present
:param item:
The standard name to search
:return:
A Button, or None if no such button exists
'''
pass
def __getattr__(self, item):
'''
Property access to Button instances
:param item:
the sname of the button
:return:
the Button instance, or raise AttributeError if no such button
'''
pass
def __contains__(self, item):
'''
Check whether a given button, referenced by sname, exists
:param item:
The sname of the button to search
:return:
True if the axis exists, false otherwise
'''
pass
def register_button_handler(self, button_handler, buttons):
'''
Register a handler function which will be called when a button is pressed
:param button_handler:
A function which will be called when any of the specified buttons are pressed. The
function is called with the Button that was pressed as the sole argument.
:param [Button] buttons:
A list or one or more buttons which should trigger the handler when pressed. Buttons
are specified as :class:`approxeng.input.Button` instances, in general controller implementations will
expose these as constants such as SixAxis.BUTTON_CIRCLE. A single Button can be specified if only one button
binding is required.
:return:
A no-arg function which can be used to remove this registration
'''
pass
def remove():
pass
| 19 | 14 | 15 | 1 | 8 | 6 | 3 | 0.92 | 1 | 8 | 5 | 0 | 12 | 5 | 12 | 12 | 231 | 29 | 105 | 44 | 86 | 97 | 96 | 41 | 80 | 6 | 1 | 3 | 37 |
6,238 |
ApproxEng/approxeng.input
|
src/python/approxeng/input/__init__.py
|
input.CentredAxis
|
class CentredAxis(Axis):
"""
A single analogue axis on a controller where the expected output range is -1.0 to 1.0 and the resting position of
the control is at 0.0, at least in principle.
"""
def __init__(self, name, min_raw_value, max_raw_value, axis_event_code, dead_zone=0.0, hot_zone=0.0,
sname=None):
"""
Create a new CentredAxis - this will be done internally within the :class:`~approxeng.input.Controller`
sub-class.
:param name:
A friendly name for the axis
:param min_raw_value:
The value read from the event system when the axis is at its minimum value
:param max_raw_value:
The value read from the event system when the axis is at its maximum value
:param axis_event_code:
The evdev code for this axis, used to dispatch events to the axis from the event system
:param dead_zone:
Size of the dead zone in the centre of the axis, within which all values will be mapped to 0.0
:param hot_zone:
Size of the hot zones at the ends of the axis, where values will be mapped to -1.0 or 1.0
:param sname:
The standard name for this axis, if specified
"""
self.name = name
self.centre = 0.0
self.max = 0.9
self.min = -0.9
self.__value = 0.0
self.invert = min_raw_value > max_raw_value
self.dead_zone = dead_zone
self.hot_zone = hot_zone
self.min_raw_value = float(min(min_raw_value, max_raw_value))
self.max_raw_value = float(max(min_raw_value, max_raw_value))
self.axis_event_code = axis_event_code
self.sname = sname
def _input_to_raw_value(self, value: int):
"""
Convert the value read from evdev to a -1.0 to 1.0 range.
:internal:
:param value:
a value ranging from the defined minimum to the defined maximum value.
:return:
-1.0 at minumum, 1.0 at maximum, linearly interpolating between those two points.
"""
return (float(value) - self.min_raw_value) * (2 / (self.max_raw_value - self.min_raw_value)) - 1.0
@property
def raw_value(self) -> float:
"""
Get an uncorrected value for this axis
:return: a float value, negative to the left or down, and ranging from -1.0 to 1.0
"""
return self.__value
@property
def value(self) -> float:
"""
Get a centre-compensated, scaled, value for the axis, taking any dead-zone into account. The value will
scale from 0.0 at the edge of the dead-zone to 1.0 (positive) or -1.0 (negative) at the extreme position of
the controller or the edge of the hot zone, if defined as other than 1.0. The axis will auto-calibrate for
maximum value, initially it will behave as if the highest possible value from the hardware is 0.9 in each
direction, and will expand this as higher values are observed. This is scaled by this function and should
always return 1.0 or -1.0 at the extreme ends of the axis.
:return: a float value, negative to the left or down and ranging from -1.0 to 1.0
"""
mapped_value = map_dual_axis(self.min, self.max, self.centre, self.dead_zone, self.hot_zone, self.__value)
if self.invert:
return -mapped_value
else:
return mapped_value
def reset(self):
"""
Reset calibration (max, min and centre values) for this axis specifically. Not generally needed, you can just
call the reset method on the SixAxis instance.
:internal:
"""
self.centre = 0.0
self.max = 0.9
self.min = -0.9
def receive_device_value(self, raw_value: int):
"""
Set a new value, called from within the joystick implementation class when parsing the event queue.
:param raw_value: the raw value from the joystick hardware
:internal:
"""
new_value = self._input_to_raw_value(raw_value)
self.__value = new_value
if new_value > self.max:
self.max = new_value
elif new_value < self.min:
self.min = new_value
def __str__(self) -> str:
return "CentredAxis name={}, sname={}, corrected_value={}".format(self.name, self.sname, self.value)
|
class CentredAxis(Axis):
'''
A single analogue axis on a controller where the expected output range is -1.0 to 1.0 and the resting position of
the control is at 0.0, at least in principle.
'''
def __init__(self, name, min_raw_value, max_raw_value, axis_event_code, dead_zone=0.0, hot_zone=0.0,
sname=None):
'''
Create a new CentredAxis - this will be done internally within the :class:`~approxeng.input.Controller`
sub-class.
:param name:
A friendly name for the axis
:param min_raw_value:
The value read from the event system when the axis is at its minimum value
:param max_raw_value:
The value read from the event system when the axis is at its maximum value
:param axis_event_code:
The evdev code for this axis, used to dispatch events to the axis from the event system
:param dead_zone:
Size of the dead zone in the centre of the axis, within which all values will be mapped to 0.0
:param hot_zone:
Size of the hot zones at the ends of the axis, where values will be mapped to -1.0 or 1.0
:param sname:
The standard name for this axis, if specified
'''
pass
def _input_to_raw_value(self, value: int):
'''
Convert the value read from evdev to a -1.0 to 1.0 range.
:internal:
:param value:
a value ranging from the defined minimum to the defined maximum value.
:return:
-1.0 at minumum, 1.0 at maximum, linearly interpolating between those two points.
'''
pass
@property
def raw_value(self) -> float:
'''
Get an uncorrected value for this axis
:return: a float value, negative to the left or down, and ranging from -1.0 to 1.0
'''
pass
@property
def value(self) -> float:
'''
Get a centre-compensated, scaled, value for the axis, taking any dead-zone into account. The value will
scale from 0.0 at the edge of the dead-zone to 1.0 (positive) or -1.0 (negative) at the extreme position of
the controller or the edge of the hot zone, if defined as other than 1.0. The axis will auto-calibrate for
maximum value, initially it will behave as if the highest possible value from the hardware is 0.9 in each
direction, and will expand this as higher values are observed. This is scaled by this function and should
always return 1.0 or -1.0 at the extreme ends of the axis.
:return: a float value, negative to the left or down and ranging from -1.0 to 1.0
'''
pass
def reset(self):
'''
Reset calibration (max, min and centre values) for this axis specifically. Not generally needed, you can just
call the reset method on the SixAxis instance.
:internal:
'''
pass
def receive_device_value(self, raw_value: int):
'''
Set a new value, called from within the joystick implementation class when parsing the event queue.
:param raw_value: the raw value from the joystick hardware
:internal:
'''
pass
def __str__(self) -> str:
pass
| 10 | 7 | 14 | 1 | 5 | 7 | 1 | 1.32 | 1 | 3 | 0 | 0 | 7 | 12 | 7 | 29 | 109 | 16 | 40 | 25 | 29 | 53 | 35 | 22 | 27 | 3 | 5 | 1 | 10 |
6,239 |
ApproxEng/approxeng.input
|
src/python/approxeng/input/__init__.py
|
input.CircularCentredAxis
|
class CircularCentredAxis:
"""
An aggregation of a pair of :class:`~approxeng.input.CentredAxis` instances.
When using a pair of centred axes to model a single joystick there are some unexpected and probably undesirable
issues with dead zones. As each axis is treated independently, the dead zones are also applied independently - this
means that, for example, with the joystick fully pushed forwards you still have the dead zone behaviour between left
and right. You may prefer a behaviour where both axes are zero if the stick is within a certain distance of its
centre position in any direction. This class provides that, and is created from a pair of centred axes, i.e. 'lx'
and 'ly'. The value is returns is a tuple of (x,y) positions. Use of this class will constrain the overall motion
of the paired axes into the unit circle - in many controllers this is true because of the physical layout of the
controller, but it may not always be in hardware terms.
"""
def __init__(self, x: "CentredAxis", y: "CentredAxis", dead_zone=0.1, hot_zone=0.1):
"""
Create a new circular centred axis
:param CentredAxis x:
Axis to use for x value
:param CentredAxis y:
Axis to use for y value
:param float dead_zone:
Specifies the distance from the centre prior to which both x and y will return 0.0, defaults to 0.1
:param float hot_zone:
Specifies the distance from the 1.0 distance beyond which both x and y will return +-1.0, i.e. if the hot
zone is set to 0.1 then all positions where the distance is greater than 0.9 will return magnitude 1 total
distances. Defaults to 0.1
"""
self.x = x
self.y = y
self.dead_zone = dead_zone
self.hot_zone = hot_zone
def _calculate_position(self, raw_x: float, raw_y: float):
"""
Map x and y to a corrected x,y tuple based on the configured dead and hot zones.
:param raw_x:
Raw x axis position, -1.0 to 1.0
:param raw_y:
Raw y axis position, -1.0 to 1.0
:return:
x,y corrected position
"""
# Avoid trying to take sqrt(0) in pathological case
if raw_x != 0 or raw_y != 0:
distance = sqrt(raw_x * raw_x + raw_y * raw_y)
else:
return 0.0, 0.0
if distance >= 1.0 - self.hot_zone:
# Return normalised value, which corresponds to the unit vector in that direction
return raw_x / distance, raw_y / distance
elif distance <= self.dead_zone:
# Return zero vector
return 0.0, 0.0
# Guarantee distance to be between dead_zone and 1.0-hot_zone at this point, scale it and return
effective_distance = (distance - self.dead_zone) / (1.0 - (self.dead_zone + self.hot_zone))
scale = effective_distance / distance
return raw_x * scale, raw_y * scale
@property
def value(self) -> (float, float):
return self._calculate_position(raw_x=self.x.raw_value if not self.x.invert else -self.x.raw_value,
raw_y=self.y.raw_value if not self.y.invert else -self.y.raw_value)
|
class CircularCentredAxis:
'''
An aggregation of a pair of :class:`~approxeng.input.CentredAxis` instances.
When using a pair of centred axes to model a single joystick there are some unexpected and probably undesirable
issues with dead zones. As each axis is treated independently, the dead zones are also applied independently - this
means that, for example, with the joystick fully pushed forwards you still have the dead zone behaviour between left
and right. You may prefer a behaviour where both axes are zero if the stick is within a certain distance of its
centre position in any direction. This class provides that, and is created from a pair of centred axes, i.e. 'lx'
and 'ly'. The value is returns is a tuple of (x,y) positions. Use of this class will constrain the overall motion
of the paired axes into the unit circle - in many controllers this is true because of the physical layout of the
controller, but it may not always be in hardware terms.
'''
def __init__(self, x: "CentredAxis", y: "CentredAxis", dead_zone=0.1, hot_zone=0.1):
'''
Create a new circular centred axis
:param CentredAxis x:
Axis to use for x value
:param CentredAxis y:
Axis to use for y value
:param float dead_zone:
Specifies the distance from the centre prior to which both x and y will return 0.0, defaults to 0.1
:param float hot_zone:
Specifies the distance from the 1.0 distance beyond which both x and y will return +-1.0, i.e. if the hot
zone is set to 0.1 then all positions where the distance is greater than 0.9 will return magnitude 1 total
distances. Defaults to 0.1
'''
pass
def _calculate_position(self, raw_x: float, raw_y: float):
'''
Map x and y to a corrected x,y tuple based on the configured dead and hot zones.
:param raw_x:
Raw x axis position, -1.0 to 1.0
:param raw_y:
Raw y axis position, -1.0 to 1.0
:return:
x,y corrected position
'''
pass
@property
def value(self) -> (float, float):
pass
| 5 | 3 | 16 | 1 | 7 | 9 | 3 | 1.68 | 0 | 1 | 0 | 0 | 3 | 4 | 3 | 3 | 65 | 6 | 22 | 12 | 17 | 37 | 18 | 11 | 14 | 4 | 0 | 1 | 8 |
6,240 |
ApproxEng/approxeng.input
|
src/python/approxeng/input/wiimote.py
|
input.wiimote.WiiMote
|
class WiiMote(Controller):
"""
Driver for the Nintendo WiiMote controller, the WiiMote
"""
def __init__(self, dead_zone=0.05, hot_zone=0.05, **kwargs):
"""
Create a new WiiMote driver
:param float dead_zone:
Used to set the dead zone for each :class:`approxeng.input.CentredAxis` in the controller.
:param float hot_zone:
Used to set the hot zone for each :class:`approxeng.input.CentredAxis` in the controller.
"""
super(WiiMote, self).__init__(
controls=[
Button("Nunchuck Z", 309, sname="r1"),
Button("Nunchuck C", 306, sname="r2"),
Button("Wiimote A", 304, sname="cross"),
Button("Wiimote B", 305, sname="circle"),
Button("Wiimote DUp", 103, sname="dup"),
Button("Wiimote DDown", 108, sname="ddown"),
Button("Wiimote DLeft", 105, sname="dleft"),
Button("Wiimote DRight", 106, sname="dright"),
Button("Wiimote -", 412, sname="select"),
Button("Wiimote +", 407, sname="start"),
Button("Wiimote home", 316, sname="home"),
Button("Wiimote 1", 257, sname="cross"),
Button("Wiimote 2", 258, sname="circle"),
CentredAxis("Wiimote Roll", -100, 100, 3, sname="roll"),
CentredAxis("Wiimote Pitch", -90, 125, 4, sname="pitch"),
CentredAxis("Wiimote ???", -90, 125, 5, sname="???"),
CentredAxis("Nunchuck Y", -100, 100, 17, sname="ry"),
CentredAxis("Nunchuck X", -100, 100, 16, sname="rx"),
CentredAxis("Classic lx", -32, 32, 18, sname="lx"),
CentredAxis("Classic ly", -32, 32, 19, sname="ly"),
CentredAxis("Classic rx", -32, 32, 20, sname="rx"),
CentredAxis("Classic ry", -32, 32, 21, sname="ly"),
Button("Classic x", 307, sname="square"),
Button("Classic y", 308, sname="triangle"),
Button("Classic zr", 313, sname="r2"),
Button("Classic zl", 312, sname="l2"),
],
dead_zone=dead_zone,
hot_zone=hot_zone,
**kwargs)
@staticmethod
def registration_ids():
"""
:return: list of (vendor_id, product_id) for this controller
"""
return [(0x57e, 0x306)]
def __repr__(self):
return 'Nintendo WiiMote controller'
|
class WiiMote(Controller):
'''
Driver for the Nintendo WiiMote controller, the WiiMote
'''
def __init__(self, dead_zone=0.05, hot_zone=0.05, **kwargs):
'''
Create a new WiiMote driver
:param float dead_zone:
Used to set the dead zone for each :class:`approxeng.input.CentredAxis` in the controller.
:param float hot_zone:
Used to set the hot zone for each :class:`approxeng.input.CentredAxis` in the controller.
'''
pass
@staticmethod
def registration_ids():
'''
:return: list of (vendor_id, product_id) for this controller
'''
pass
def __repr__(self):
pass
| 5 | 3 | 16 | 0 | 12 | 3 | 1 | 0.33 | 1 | 3 | 2 | 0 | 2 | 0 | 3 | 44 | 56 | 4 | 39 | 5 | 34 | 13 | 7 | 4 | 3 | 1 | 5 | 0 | 3 |
6,241 |
ApproxEng/approxeng.input
|
src/python/approxeng/input/controllers.py
|
input.controllers.ControllerNotFoundError
|
class ControllerNotFoundError(IOError):
"""
Raised during controller discovery if the specified set of controller requirements cannot be satisfied
"""
pass
|
class ControllerNotFoundError(IOError):
'''
Raised during controller discovery if the specified set of controller requirements cannot be satisfied
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 5 | 0 | 2 | 1 | 1 | 3 | 2 | 1 | 1 | 0 | 1 | 0 | 0 |
6,242 |
Apstra/aeon-venos
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Apstra_aeon-venos/pylib/aeon/utils/stdargs.py
|
pylib.aeon.utils.stdargs.ArgumentParser.ParserError
|
class ParserError(Exception):
pass
|
class ParserError(Exception):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 3 | 0 | 0 |
6,243 |
Apstra/aeon-venos
|
Apstra_aeon-venos/pylib/aeon/cumulus/connector.py
|
pylib.aeon.cumulus.connector.Connector
|
class Connector(object):
DEFAULT_PROTOCOL = 'ssh'
def __init__(self, hostname, **kwargs):
self.hostname = hostname
self.proto = kwargs.get('proto') or self.DEFAULT_PROTOCOL
self.port = kwargs.get('port') or socket.getservbyname('ssh')
self.user = kwargs.get('user', 'admin')
self.passwd = kwargs.get('passwd', 'admin')
self._client = paramiko.SSHClient()
self._client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.open()
def open(self):
try:
self._client.connect(
self.hostname, port=self.port,
username=self.user, password=self.passwd)
except Exception as exc:
raise LoginNotReadyError(exc=exc, message='Unable to connect.')
def close(self):
self._client.close()
def execute(self, commands, stop_on_error=True):
results = []
exit_code_collector = 0
for cmd in commands:
stdin, stdout, stderr = self._client.exec_command(cmd)
exit_code = stdout.channel.recv_exit_status()
exit_code_collector |= exit_code
results.append(dict(cmd=cmd, exit_code=exit_code,
stdout=stdout.read(),
stderr=stderr.read()))
if stop_on_error is True and exit_code != 0:
return False, results
return bool(0 == exit_code_collector), results
|
class Connector(object):
def __init__(self, hostname, **kwargs):
pass
def open(self):
pass
def close(self):
pass
def execute(self, commands, stop_on_error=True):
pass
| 5 | 0 | 10 | 2 | 8 | 0 | 2 | 0 | 1 | 4 | 1 | 0 | 4 | 6 | 4 | 4 | 44 | 11 | 33 | 18 | 28 | 0 | 29 | 17 | 24 | 3 | 1 | 2 | 7 |
6,244 |
Apstra/aeon-venos
|
Apstra_aeon-venos/pylib/aeon/centos/device.py
|
pylib.aeon.centos.device.Device
|
class Device(BaseDevice):
OS_NAME = 'centos'
def __init__(self, target, **kwargs):
"""
:param target: hostname or ipaddr of target device
:param kwargs:
'user' : login user-name, defaults to "admin"
'passwd': login password, defaults to "admin
"""
BaseDevice.__init__(self, target, Connector, **kwargs)
def get_mac_address(self, link_name):
good, got = self.api.execute(['/sbin/ip link show dev %s' % link_name])
data = got[0]['stdout']
macaddr = data.partition('link/ether ')[-1].split()[0]
return macaddr.upper()
def gather_facts(self):
facts = self.facts
facts['os_name'] = self.OS_NAME
good, got = self.api.execute([
'hostname',
'cat /etc/centos-release | cut -d" " -f3'
])
facts['fqdn'] = got[0]['stdout'].strip()
facts['hostname'] = facts['fqdn']
facts['os_version'] = got[1]['stdout'].strip()
facts['virtual'] = None
facts['vendor'] = 'CentOS'
facts['serial_number'] = None
facts['mac_address'] = self.get_mac_address("eth0")
facts['hw_model'] = 'Server'
facts['hw_part_number'] = None
facts['hw_version'] = None
facts['service_tag'] = None
|
class Device(BaseDevice):
def __init__(self, target, **kwargs):
'''
:param target: hostname or ipaddr of target device
:param kwargs:
'user' : login user-name, defaults to "admin"
'passwd': login password, defaults to "admin
'''
pass
def get_mac_address(self, link_name):
pass
def gather_facts(self):
pass
| 4 | 1 | 11 | 1 | 8 | 2 | 1 | 0.22 | 1 | 1 | 1 | 0 | 3 | 0 | 3 | 8 | 38 | 5 | 27 | 10 | 23 | 6 | 24 | 10 | 20 | 1 | 2 | 0 | 3 |
6,245 |
Apstra/aeon-venos
|
Apstra_aeon-venos/pylib/aeon/utils/stdargs.py
|
pylib.aeon.utils.stdargs.Stdargs
|
class Stdargs(object):
_ENV = {
'TARGET_USER': 'AEON_TUSER',
'TARGET_PASSWD': 'AEON_TPASSWD',
'TARGET': 'AEON_TARGET',
'LOGFILE': 'AEON_LOGFILE'
}
def __init__(self, **kwargs):
self.progname = kwargs.get('name', 'aeon-nxos')
self.psr = ArgumentParser(**kwargs)
self.args = None
self.target = None
self.user = None
self.passwd = None
self.log = None
self._setup_stdargs()
def _setup_stdargs(self):
self.psr.add_argument(
'-t', '--target',
default=os.getenv(Stdargs._ENV['TARGET']),
help='Target hostname or ip-addr')
self.psr.add_argument(
'--logfile',
default=os.getenv(Stdargs._ENV['LOGFILE']),
help='name of log file')
self.psr.add_argument(
'--json',
action='store_true', default=True,
help='output in JSON')
group = self.psr.add_argument_group('authentication')
group.add_argument(
'-u', '--user',
help='Target username')
group.add_argument(
'-U', dest='env_user',
default=Stdargs._ENV['TARGET_USER'],
help='Target username environment variable')
group.add_argument(
'-P', dest='env_passwd',
default=Stdargs._ENV['TARGET_PASSWD'],
help='Target password environment variable')
def parse_args(self):
self.args = self.psr.parse_args()
self.target = self.args.target
self.user = self.args.user or os.getenv(self.args.env_user)
self.passwd = os.getenv(self.args.env_passwd)
if not self.target:
raise exceptions.TargetError('missing target value')
if not self.user:
raise exceptions.TargetError('missing username value')
if not self.passwd:
raise exceptions.TargetError('missing password value')
self.log = logging.getLogger(name=self.progname)
if self.args.logfile:
self._setup_logging()
return self.args
def _setup_logging(self, level=logging.INFO):
self.log.setLevel(level)
fh = logging.FileHandler(self.args.logfile)
fmt = logging.Formatter(
'%(asctime)s:%(levelname)s: {target}:%(message)s'
.format(target=self.args.target))
fh.setFormatter(fmt)
self.log.addHandler(fh)
|
class Stdargs(object):
def __init__(self, **kwargs):
pass
def _setup_stdargs(self):
pass
def parse_args(self):
pass
def _setup_logging(self, level=logging.INFO):
pass
| 5 | 0 | 18 | 4 | 14 | 0 | 2 | 0 | 1 | 4 | 2 | 0 | 4 | 7 | 4 | 4 | 82 | 18 | 64 | 16 | 59 | 0 | 40 | 16 | 35 | 5 | 1 | 1 | 8 |
6,246 |
Apstra/aeon-venos
|
Apstra_aeon-venos/pylib/aeon/utils/stdargs.py
|
pylib.aeon.utils.stdargs.ArgumentParser
|
class ArgumentParser(argparse.ArgumentParser):
class ParserError(Exception):
pass
def error(self, message):
raise ArgumentParser.ParserError(message)
|
class ArgumentParser(argparse.ArgumentParser):
class ParserError(Exception):
def error(self, message):
pass
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 51 | 6 | 1 | 5 | 3 | 2 | 0 | 5 | 3 | 2 | 1 | 3 | 0 | 1 |
6,247 |
Apstra/aeon-venos
|
Apstra_aeon-venos/pylib/aeon/ubuntu/device.py
|
pylib.aeon.ubuntu.device.Device
|
class Device(BaseDevice):
OS_NAME = 'ubuntu'
def __init__(self, target, **kwargs):
"""
:param target: hostname or ipaddr of target device
:param kwargs:
'user' : login user-name, defaults to "admin"
'passwd': login password, defaults to "admin
"""
BaseDevice.__init__(self, target, Connector, **kwargs)
def get_mac_address(self):
good, got = self.api.execute(['ip link show'])
data = got[0]['stdout']
macaddr = data.partition('link/ether ')[-1].split()[0]
return macaddr.upper()
def gather_facts(self):
facts = self.facts
facts['os_name'] = self.OS_NAME
good, got = self.api.execute([
'hostname',
'cat /etc/lsb-release | grep RELEASE | cut -d= -f2'
])
facts['fqdn'] = got[0]['stdout'].strip()
facts['hostname'] = facts['fqdn']
facts['os_version'] = got[1]['stdout'].strip()
facts['virtual'] = None
facts['vendor'] = 'Canonical'
facts['serial_number'] = None
facts['mac_address'] = self.get_mac_address()
facts['hw_model'] = 'Server'
facts['hw_part_number'] = None
facts['hw_version'] = None
facts['service_tag'] = None
|
class Device(BaseDevice):
def __init__(self, target, **kwargs):
'''
:param target: hostname or ipaddr of target device
:param kwargs:
'user' : login user-name, defaults to "admin"
'passwd': login password, defaults to "admin
'''
pass
def get_mac_address(self):
pass
def gather_facts(self):
pass
| 4 | 1 | 11 | 1 | 8 | 2 | 1 | 0.22 | 1 | 1 | 1 | 0 | 3 | 0 | 3 | 8 | 39 | 6 | 27 | 10 | 23 | 6 | 24 | 10 | 20 | 1 | 2 | 0 | 3 |
6,248 |
Apstra/aeon-venos
|
Apstra_aeon-venos/pylib/aeon/opx/device.py
|
pylib.aeon.opx.device.Device
|
class Device(BaseDevice):
OS_NAME = 'OPX'
def __init__(self, target, **kwargs):
"""
:param target: hostname or ipaddr of target device
:param kwargs:
'user' : login user-name, defaults to "admin"
'passwd': login password, defaults to "admin
"""
BaseDevice.__init__(self, target, Connector, **kwargs)
def get_mac_address(self):
good, got = self.api.execute(['ip link show'])
data = got[0]['stdout']
macaddr = data.partition('link/ether ')[-1].split()[0]
return macaddr.upper()
def gather_facts(self):
facts = self.facts
facts['os_name'] = self.OS_NAME
good, got = self.api.execute([
'hostname',
"""grep -oP '^OS_VERSION=[\"]?\K.*\d' /etc/OPX-release-version""",
"""grep -oP '^PLATFORM=[\"]?\K.*\w' /etc/OPX-release-version"""
])
facts['fqdn'] = got[0]['stdout'].strip()
facts['hostname'] = facts['fqdn']
facts['os_version'] = got[1]['stdout'].strip()
facts['virtual'] = bool('vm' in got[2]['stdout'].lower())
facts['vendor'] = 'OPX'
facts['serial_number'] = self.get_mac_address().replace(':', '')
facts['mac_address'] = self.get_mac_address()
facts['hw_model'] = got[2]['stdout'].strip()
facts['hw_part_number'] = None
facts['hw_version'] = None
facts['service_tag'] = None
|
class Device(BaseDevice):
def __init__(self, target, **kwargs):
'''
:param target: hostname or ipaddr of target device
:param kwargs:
'user' : login user-name, defaults to "admin"
'passwd': login password, defaults to "admin
'''
pass
def get_mac_address(self):
pass
def gather_facts(self):
pass
| 4 | 1 | 12 | 1 | 9 | 2 | 1 | 0.21 | 1 | 2 | 1 | 0 | 3 | 0 | 3 | 8 | 40 | 6 | 28 | 10 | 24 | 6 | 24 | 10 | 20 | 1 | 2 | 0 | 3 |
6,249 |
Apstra/aeon-venos
|
Apstra_aeon-venos/pylib/aeon/nxos/exceptions.py
|
pylib.aeon.nxos.exceptions.RequestError
|
class RequestError(NxosException):
""" retains any exception at time of making the command request """
pass
|
class RequestError(NxosException):
''' retains any exception at time of making the command request '''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 3 | 0 | 2 | 1 | 1 | 1 | 2 | 1 | 1 | 0 | 4 | 0 | 0 |
6,250 |
Apstra/aeon-venos
|
Apstra_aeon-venos/pylib/aeon/nxos/exceptions.py
|
pylib.aeon.nxos.exceptions.ProbeError
|
class ProbeError(NxosException):
pass
|
class ProbeError(NxosException):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 4 | 0 | 0 |
6,251 |
Apstra/aeon-venos
|
Apstra_aeon-venos/pylib/aeon/nxos/exceptions.py
|
pylib.aeon.nxos.exceptions.NxosException
|
class NxosException(Exception):
pass
|
class NxosException(Exception):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 4 | 0 | 0 | 0 | 10 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 3 | 0 | 0 |
6,252 |
Apstra/aeon-venos
|
Apstra_aeon-venos/pylib/aeon/nxos/exceptions.py
|
pylib.aeon.nxos.exceptions.NoRespError
|
class NoRespError(NxosException):
""" indicates that the response does not have a results code """
pass
|
class NoRespError(NxosException):
''' indicates that the response does not have a results code '''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 3 | 0 | 2 | 1 | 1 | 1 | 2 | 1 | 1 | 0 | 4 | 0 | 0 |
6,253 |
Apstra/aeon-venos
|
Apstra_aeon-venos/pylib/aeon/nxos/exceptions.py
|
pylib.aeon.nxos.exceptions.CommandError
|
class CommandError(NxosException):
""" indicates the response code != 200 """
pass
|
class CommandError(NxosException):
''' indicates the response code != 200 '''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 3 | 0 | 2 | 1 | 1 | 1 | 2 | 1 | 1 | 0 | 4 | 0 | 0 |
6,254 |
Apstra/aeon-venos
|
Apstra_aeon-venos/pylib/aeon/nxos/device.py
|
pylib.aeon.nxos.device.Device
|
class Device(BaseDevice):
OS_NAME = 'nxos'
def __init__(self, target, **kwargs):
"""
:param target: hostname or ipaddr of target device
:param kwargs:
'user' : login user-name, defaults to "admin"
'passwd': login password, defaults to "admin
"""
BaseDevice.__init__(self, target, Connector, **kwargs)
def close(self):
# nothing to do for close at this time, yo!
pass
def gather_facts(self):
exec_show = partial(self.api.exec_opcmd, resp_fmt='json')
facts = self.facts
facts['os_name'] = self.OS_NAME
got = exec_show('show hostname')
facts['fqdn'] = got['hostname']
facts['hostname'], _, facts['domain_name'] = facts['fqdn'].partition('.')
attempts = 1
while attempts < 5:
try:
got = exec_show('show hardware')
except: # NOQA
attempts -= 1
else:
break
facts['os_version'] = got['kickstart_ver_str']
facts['chassis_id'] = got['chassis_id']
facts['virtual'] = bool('NX-OSv' in facts['chassis_id'])
row = got['TABLE_slot']['ROW_slot']['TABLE_slot_info']['ROW_slot_info'][0]
facts['serial_number'] = row['serial_num']
facts['hw_model'] = row['model_num']
facts['hw_part_number'] = row['part_num']
facts['hw_part_version'] = row['part_revision']
facts['hw_version'] = row['hw_ver']
got = exec_show('show interface mgmt0')
raw_mac = got['TABLE_interface']['ROW_interface']['eth_hw_addr'].replace('.', '')
facts['mac_address'] = ':'.join(s.encode('hex') for s in raw_mac.decode('hex'))
def __getattr__(self, item):
# ##
# ## this is rather perhaps being a bit "too clever", but I sometimes
# ## can't help myself ;-P
# ##
# if the named addon module does not exist, this will raise
# an ImportError. We might want to catch this and handle differently
mod = importlib.import_module('.autoload.%s' % item, package=__package__)
def wrapper(*vargs, **kvargs):
cls = getattr(mod, '_%s' % item)
self.__dict__[item] = cls(self, *vargs, **kvargs)
return wrapper
|
class Device(BaseDevice):
def __init__(self, target, **kwargs):
'''
:param target: hostname or ipaddr of target device
:param kwargs:
'user' : login user-name, defaults to "admin"
'passwd': login password, defaults to "admin
'''
pass
def close(self):
pass
def gather_facts(self):
pass
def __getattr__(self, item):
pass
def wrapper(*vargs, **kvargs):
pass
| 6 | 1 | 13 | 2 | 8 | 3 | 1 | 0.36 | 1 | 2 | 0 | 0 | 4 | 0 | 4 | 9 | 66 | 14 | 39 | 16 | 33 | 14 | 39 | 16 | 33 | 3 | 2 | 2 | 7 |
6,255 |
Apstra/aeon-venos
|
Apstra_aeon-venos/pylib/aeon/nxos/connector.py
|
pylib.aeon.nxos.connector.NxosRequest
|
class NxosRequest(object):
MESSGE_TYPES = ('cli_show', 'cli_show_ascii', 'cli_conf')
OUTPUT_FMTS = ('json', 'xml')
CHUNK_VALUES = (0, 1)
# !! WARNING !! the following string must not contain a leading newline ...
# !! WARNING !! that is, it must start immediately following the triple-quote
MESSAGE = """<?xml version="1.0"?>
<ins_api>
<type>{msg_type}</type>
<version>{api_ver}</version>
<chunk>{chunk}</chunk>
<sid>{session_id}</sid>
<input>{command}</input>
<output_format>{resp_fmt}</output_format>
</ins_api>
"""
DEFAULTS = dict(
msg_type='cli_show',
api_ver='0.1',
chunk=0,
session_id=1,
resp_fmt='json',
command=None
)
def __init__(self):
self.__dict__['params'] = copy(self.DEFAULTS)
def send(self, api, timeout=None):
_timeout = timeout if timeout is not None else api.DEFAULT_TIMEOUT
try:
resp = requests.post(
api.api_url, headers=api.api_headers,
timeout=_timeout,
auth=api.api_auth, data=str(self))
except requests.exceptions.ReadTimeout as exc:
cmd_exc = exceptions.TimeoutError(exc)
cmd_exc.timeout = timeout
raise cmd_exc
except Exception as exc:
raise NxosExc.RequestError(exc)
if 401 == resp.status_code:
cmd_exc = exceptions.UnauthorizedError()
cmd_exc.message = 'not authorized'
raise cmd_exc
if 200 != resp.status_code:
cmd_exc = NxosExc.CommandError()
cmd_exc.errorcode = resp.status_code
cmd_exc.message = "command failed, http_code={0} http_reason={1}".format(
resp.status_code, resp.reason)
raise cmd_exc
return resp
def __setattr__(self, key, value):
if key in self.__dict__['params'] and value is not None:
self.__dict__['params'][key] = value
def __getattr__(self, item):
return self.__dict__.get(item) or self.__dict__.get('params').get(item)
def __str__(self):
return self.MESSAGE.format(**self.params)
|
class NxosRequest(object):
def __init__(self):
pass
def send(self, api, timeout=None):
pass
def __setattr__(self, key, value):
pass
def __getattr__(self, item):
pass
def __str__(self):
pass
| 6 | 0 | 8 | 1 | 7 | 0 | 2 | 0.04 | 1 | 6 | 4 | 2 | 5 | 0 | 5 | 5 | 70 | 13 | 55 | 15 | 49 | 2 | 35 | 14 | 29 | 6 | 1 | 1 | 11 |
6,256 |
Apstra/aeon-venos
|
Apstra_aeon-venos/pylib/aeon/base/device.py
|
pylib.aeon.base.device.BaseDevice
|
class BaseDevice(object):
DEFAULT_PROBE_TIMEOUT = 10
def __init__(self, target, connector, **kwargs):
"""
:param target: hostname or ipaddr of target device
:param kwargs:
'user' : login user-name, defaults to "admin"
'passwd': login password, defaults to "admin
"""
self.target = target
self.port = kwargs.get('port')
self.user = kwargs.get('user', 'admin')
self.passwd = kwargs.get('passwd', 'admin')
self.timeout = kwargs.get('timeout', self.DEFAULT_PROBE_TIMEOUT)
self.facts = {}
self.api = connector(hostname=target, **kwargs)
if 'no_probe' not in kwargs:
self.probe()
if 'no_gather_facts' not in kwargs:
self.gather_facts()
def gather_facts(self):
"""
Will be overridden by subclass
:return: None
"""
pass
def probe(self):
interval = 1
start = datetime.datetime.now()
end = start + datetime.timedelta(seconds=self.timeout)
port = self.port or socket.getservbyname(self.api.proto)
while datetime.datetime.now() < end:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(interval)
try:
s.connect((self.target, int(port)))
s.shutdown(socket.SHUT_RDWR)
s.close()
elapsed = datetime.datetime.now() - start
return True, elapsed
except: # NOQA
time.sleep(interval)
pass
# Raise ProbeError if unable to reach in time allotted
raise ProbeError('Unable to reach device within %s seconds' % self.timeout)
def __repr__(self):
return 'Device(%r)' % self.target
def __str__(self):
return '{vendor} {os} at {target}'.format(vendor=self.facts['vendor'],
os=self.facts['os'],
target=self.target)
|
class BaseDevice(object):
def __init__(self, target, connector, **kwargs):
'''
:param target: hostname or ipaddr of target device
:param kwargs:
'user' : login user-name, defaults to "admin"
'passwd': login password, defaults to "admin
'''
pass
def gather_facts(self):
'''
Will be overridden by subclass
:return: None
'''
pass
def probe(self):
pass
def __repr__(self):
pass
def __str__(self):
pass
| 6 | 2 | 11 | 1 | 8 | 2 | 2 | 0.3 | 1 | 5 | 1 | 6 | 5 | 7 | 5 | 5 | 60 | 9 | 40 | 20 | 34 | 12 | 38 | 20 | 32 | 3 | 1 | 2 | 9 |
6,257 |
Apstra/aeon-venos
|
Apstra_aeon-venos/pylib/aeon/nxos/connector.py
|
pylib.aeon.nxos.connector.NxosOperRequest
|
class NxosOperRequest(NxosRequest):
def __init__(self, command=None):
super(self.__class__, self).__init__()
self.command = command
|
class NxosOperRequest(NxosRequest):
def __init__(self, command=None):
pass
| 2 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 1 | 1 | 1 | 6 | 4 | 0 | 4 | 3 | 2 | 0 | 4 | 3 | 2 | 1 | 2 | 0 | 1 |
6,258 |
Apstra/aeon-venos
|
Apstra_aeon-venos/pylib/aeon/nxos/connector.py
|
pylib.aeon.nxos.connector.NxosConfigRequest
|
class NxosConfigRequest(NxosRequest):
def __init__(self):
super(self.__class__, self).__init__()
self.msg_type = 'cli_conf'
self.resp_fmt = 'xml'
|
class NxosConfigRequest(NxosRequest):
def __init__(self):
pass
| 2 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 1 | 2 | 1 | 6 | 5 | 0 | 5 | 4 | 3 | 0 | 5 | 4 | 3 | 1 | 2 | 0 | 1 |
6,259 |
Apstra/aeon-venos
|
Apstra_aeon-venos/pylib/aeon/nxos/autoload/install_os.py
|
pylib.aeon.nxos.autoload.install_os._install_os
|
class _install_os(object):
DESTDIR = 'bootflash'
VRF_NAME = 'management'
def __init__(self, device, image=None):
self.device = device
self.image = image
# ##### -------------------------------------------------------------------
# #####
# ##### PROPERTIES
# #####
# ##### -------------------------------------------------------------------
@property
def md5sum(self):
"""
Check to see if the file exists on the device
:return:
"""
cmd = 'show file {dir}:{bin} md5sum'.format(
dir=self.DESTDIR, bin=self.image)
run = self.device.api.exec_opcmd
try:
got = run(cmd)
return got.get('file_content_md5sum').strip()
except: # NOQA
return None
@property
def available_space(self):
cmd = 'df -k /{dir} | grep {dir}'.format(dir=self.DESTDIR)
run = self.device.api.exec_opcmd
try:
got = run(cmd, msg_type='bash')
return int(got[3])
except: # NOQA
# @@@ TO-DO: need to handle this properly
raise
# ##### -------------------------------------------------------------------
# #####
# ##### PUBLIC METHODS
# #####
# ##### -------------------------------------------------------------------
def copy_from(self, location, timeout=10 * 60):
"""
This method will fetch the image; the fetch will happen from the
device-side using the 'copy' command. Note that the NXAPI appears to
be single-threaded, so the code needs to wait until this operation has
completed before attempting another API call. Therefore the :timeout:
value is set very high (10min)
:param location: URL to the location of the file. This URL must be a valid source
field to the NXOS 'copy' command
:keyword timeout: Timeout in seconds
:return:
"""
cmd = 'copy {location} {dir}: vrf {vrf_name}'.format(
location=location, dir=self.DESTDIR, vrf_name=self.VRF_NAME)
run = self.device.api.exec_opcmd
run(cmd, msg_type='cli_show_ascii', timeout=timeout)
def run(self, timeout=10 * 60):
"""
This will invoke the command to install the image, and then
cause the device to reboot.
:param timeout: time/seconds to perform the install action
"""
cmd = 'install all nxos {dir}:{bin}'.format(
dir=self.DESTDIR, bin=self.image)
# Don't prompt when upgrading
self.device.api.exec_opcmd('terminal dont-ask',
msg_type='cli_show_ascii',
timeout=timeout)
run = self.device.api.exec_opcmd
run(cmd, msg_type='cli_show_ascii', timeout=timeout)
|
class _install_os(object):
def __init__(self, device, image=None):
pass
@property
def md5sum(self):
'''
Check to see if the file exists on the device
:return:
'''
pass
@property
def available_space(self):
pass
def copy_from(self, location, timeout=10 * 60):
'''
This method will fetch the image; the fetch will happen from the
device-side using the 'copy' command. Note that the NXAPI appears to
be single-threaded, so the code needs to wait until this operation has
completed before attempting another API call. Therefore the :timeout:
value is set very high (10min)
:param location: URL to the location of the file. This URL must be a valid source
field to the NXOS 'copy' command
:keyword timeout: Timeout in seconds
:return:
'''
pass
def run(self, timeout=10 * 60):
'''
This will invoke the command to install the image, and then
cause the device to reboot.
:param timeout: time/seconds to perform the install action
'''
pass
| 8 | 3 | 13 | 2 | 7 | 5 | 1 | 0.89 | 1 | 1 | 0 | 0 | 5 | 2 | 5 | 5 | 85 | 15 | 38 | 22 | 30 | 34 | 31 | 20 | 25 | 2 | 1 | 1 | 7 |
6,260 |
Apstra/aeon-venos
|
Apstra_aeon-venos/pylib/aeon/nxos/autoload/guestshell.py
|
pylib.aeon.nxos.autoload.guestshell._guestshell
|
class _guestshell(object):
GUESTSHELL_CPU = 6
GUESTSHELL_DISK = 1024
GUESTSHELL_MEMORY = 3072
Resources = namedtuple('Resources', 'cpu memory disk')
def __init__(self, device,
cpu=GUESTSHELL_CPU, memory=GUESTSHELL_MEMORY,
disk=GUESTSHELL_DISK, log=None):
self.device = device
self.guestshell = partial(self.device.api.exec_opcmd, msg_type='cli_show_ascii')
self.cli = self.device.api.exec_opcmd
self.log = log or logging.getLogger()
self.sz_max = {}
self._get_sz_max()
self.sz_need = _guestshell.Resources(
cpu=min(cpu, self.sz_max['cpu']),
memory=min(memory, self.sz_max['memory']),
disk=min(disk, self.sz_max['disk']))
self.sz_has = None
self._state = None
self.exists = False
# ---------------------------------------------------------------
# -----
# ----- PROPERTIES
# -----
# ---------------------------------------------------------------
@property
def state(self):
cmd = 'show virtual-service detail name guestshell+'
try:
got = self.cli(cmd)
except CommandError:
# means there is no guestshell
self.exists = False
self._state = 'None'
return self._state
try:
self._state = got['TABLE_detail']['ROW_detail']['state']
return self._state
except TypeError:
# means there is no guestshell
self.exists = False
self._state = 'None'
return self._state
@property
def size(self):
self._get_sz_info()
return self.sz_has
# ---------------------------------------------------------------
# -----
# ----- PUBLIC METHODS
# -----
# ---------------------------------------------------------------
def setup(self):
self.log.info("/START(guestshell): setup")
state = self.state
self.log.info("/INFO(guestshell): current state: %s" % state)
if 'Activated' == state:
self._get_sz_info()
if self.sz_need != self.sz_has:
self.log.info("/INFO(guestshell): need to resize, please wait...")
self.resize()
self.reboot()
else:
self.log.info(
"/INFO(guestshell): not activated, enabling with proper size, "
"please wait ...")
self.resize()
self.enable()
self._get_sz_info()
self.log.info("/END(guestshell): setup")
def reboot(self):
self.guestshell('guestshell reboot')
self._wait_state('Activated')
def enable(self):
self.guestshell('guestshell enable')
self._wait_state('Activated')
def destroy(self):
if 'None' == self.state:
return
if 'Activating' == self.state:
self._wait_state('Activated')
if 'Deactivating' == self.state:
self._wait_state('Deactivated')
self.guestshell('guestshell destroy')
self._wait_state('None')
def disable(self):
self.guestshell('guestshell disable')
self._wait_state('Deactivated')
def resize_cpu(self, cpu):
value = min(cpu, self.sz_max['cpu'])
self.guestshell('guestshell resize cpu {}'.format(value))
def resize_memory(self, memory):
value = min(memory, self.sz_max['memory'])
self.guestshell('guestshell resize memory {}'.format(value))
def resize_disk(self, disk):
value = min(disk, self.sz_max['disk'])
self.guestshell('guestshell resize rootfs {}'.format(value))
def resize(self):
self.resize_cpu(self.sz_need.cpu)
self.resize_memory(self.sz_need.memory)
self.resize_disk(self.sz_need.disk)
def run(self, command):
return self.guestshell('guestshell run %s' % command)
def sudoers(self, enable):
"""
This method is used to enable/disable bash sudo commands running
through the guestshell virtual service. By default sudo access
is prevented due to the setting in the 'sudoers' file. Therefore
the setting must be disabled in the file to enable sudo commands.
This method assumes that the "bash-shell" feature is enabled.
@@@ TO-DO: have a mech to check &| control bash-shell feature support
:param enable:
True - enables sudo commands
False - disables sudo commands
:return:
returns the response of the sed command needed to make the
file change
"""
f_sudoers = "/isan/vdc_1/virtual-instance/guestshell+/rootfs/etc/sudoers"
if enable is True:
sed_cmd = r" 's/\(^Defaults *requiretty\)/#\1/g' "
elif enable is False:
sed_cmd = r" 's/^#\(Defaults *requiretty\)/\1/g' "
else:
raise RuntimeError('enable must be True or False')
self.guestshell("run bash sudo sed -i" + sed_cmd + f_sudoers)
# ---------------------------------------------------------------
# -----
# ----- PRIVATE METHODS
# -----
# ---------------------------------------------------------------
def _get_sz_max(self):
got = self.cli('show virtual-service global')
limits = got['TABLE_resource_limits']['ROW_resource_limits']
for resource in limits:
name = resource['media_name']
max_val = int(resource['quota'])
if 'CPU' in name:
self.sz_max['cpu'] = max_val
elif 'memory' in name:
self.sz_max['memory'] = max_val
elif 'flash' in name:
self.sz_max['disk'] = max_val
def _get_sz_info(self):
"""
Obtains the current resource allocations, assumes that the
guestshell is in an 'Activated' state
"""
if 'None' == self._state:
return None
cmd = 'show virtual-service detail name guestshell+'
got = self.cli(cmd)
got = got['TABLE_detail']['ROW_detail']
sz_cpu = int(got['cpu_reservation'])
sz_disk = int(got['disk_reservation'])
sz_memory = int(got['memory_reservation'])
self.sz_has = _guestshell.Resources(
cpu=sz_cpu, memory=sz_memory, disk=sz_disk)
def _wait_state(self, state, timeout=60, interval=1, retry=0):
now_state = None
time.sleep(interval)
while timeout:
now_state = self.state
if now_state == state:
return
time.sleep(interval)
timeout -= 1
if state == 'Activated' and now_state == 'Activating':
# maybe give it some more time ...
if retry > 2:
msg = '/INFO(guestshell): waiting too long for Activated state'
self.log.critical(msg)
raise RuntimeError(msg)
self.log.info('/INFO(guestshell): still Activating ... giving it some more time')
self._wait_state(state, retry + 1)
else:
msg = '/INFO(guestshell): state %s never happened, still %s' % (state, now_state)
self.log.critical(msg)
raise RuntimeError(msg)
|
class _guestshell(object):
def __init__(self, device,
cpu=GUESTSHELL_CPU, memory=GUESTSHELL_MEMORY,
disk=GUESTSHELL_DISK, log=None):
pass
@property
def state(self):
pass
@property
def size(self):
pass
def setup(self):
pass
def reboot(self):
pass
def enable(self):
pass
def destroy(self):
pass
def disable(self):
pass
def resize_cpu(self, cpu):
pass
def resize_memory(self, memory):
pass
def resize_disk(self, disk):
pass
def resize_cpu(self, cpu):
pass
def run(self, command):
pass
def sudoers(self, enable):
'''
This method is used to enable/disable bash sudo commands running
through the guestshell virtual service. By default sudo access
is prevented due to the setting in the 'sudoers' file. Therefore
the setting must be disabled in the file to enable sudo commands.
This method assumes that the "bash-shell" feature is enabled.
@@@ TO-DO: have a mech to check &| control bash-shell feature support
:param enable:
True - enables sudo commands
False - disables sudo commands
:return:
returns the response of the sed command needed to make the
file change
'''
pass
def _get_sz_max(self):
pass
def _get_sz_info(self):
'''
Obtains the current resource allocations, assumes that the
guestshell is in an 'Activated' state
'''
pass
def _wait_state(self, state, timeout=60, interval=1, retry=0):
pass
| 20 | 2 | 11 | 1 | 8 | 1 | 2 | 0.26 | 1 | 5 | 1 | 0 | 17 | 9 | 17 | 17 | 226 | 46 | 144 | 55 | 122 | 38 | 128 | 51 | 110 | 5 | 1 | 2 | 35 |
6,261 |
Apstra/aeon-venos
|
Apstra_aeon-venos/pylib/aeon/exceptions.py
|
pylib.aeon.exceptions.TargetError
|
class TargetError(Exception):
pass
|
class TargetError(Exception):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 3 | 0 | 0 |
6,262 |
Apstra/aeon-venos
|
Apstra_aeon-venos/pylib/aeon/exceptions.py
|
pylib.aeon.exceptions.ProbeError
|
class ProbeError(Exception):
pass
|
class ProbeError(Exception):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 3 | 0 | 0 |
6,263 |
Apstra/aeon-venos
|
Apstra_aeon-venos/pylib/aeon/exceptions.py
|
pylib.aeon.exceptions.LoginNotReadyError
|
class LoginNotReadyError(Exception):
def __init__(self, exc, message):
super(LoginNotReadyError, self).__init__(exc, message)
self.exc = exc
self.message = message
def __repr__(self):
return self.exc.message
|
class LoginNotReadyError(Exception):
def __init__(self, exc, message):
pass
def __repr__(self):
pass
| 3 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 2 | 2 | 2 | 12 | 8 | 1 | 7 | 5 | 4 | 0 | 7 | 5 | 4 | 1 | 3 | 0 | 2 |
6,264 |
Apstra/aeon-venos
|
Apstra_aeon-venos/pylib/aeon/exceptions.py
|
pylib.aeon.exceptions.ConfigError
|
class ConfigError(Exception):
def __init__(self, exc, contents):
super(ConfigError, self).__init__(exc, contents)
self.exc = exc
self.contents = contents
|
class ConfigError(Exception):
def __init__(self, exc, contents):
pass
| 2 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 1 | 2 | 1 | 11 | 5 | 0 | 5 | 4 | 3 | 0 | 5 | 4 | 3 | 1 | 3 | 0 | 1 |
6,265 |
Apstra/aeon-venos
|
Apstra_aeon-venos/pylib/aeon/eos/exceptions.py
|
pylib.aeon.eos.exceptions.EosException
|
class EosException(Exception):
pass
|
class EosException(Exception):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 3 | 0 | 0 |
6,266 |
Apstra/aeon-venos
|
Apstra_aeon-venos/pylib/aeon/eos/device.py
|
pylib.aeon.eos.device.Device
|
class Device(BaseDevice):
OS_NAME = 'eos'
def __init__(self, target, **kwargs):
"""
:param target: hostname or ipaddr of target device
:param kwargs:
'user' : login user-name, defaults to "admin"
'passwd': login password, defaults to "admin
"""
BaseDevice.__init__(self, target, Connector, **kwargs)
def gather_facts(self):
facts = self.facts
got_ver = self.api.execute('show version')
facts['vendor'] = 'arista'
facts['os_name'] = self.OS_NAME
facts['os_version'] = got_ver['version']
facts['hw_model'] = got_ver['modelName']
facts['hw_version'] = got_ver['hardwareRevision']
facts['hw_part_number'] = None
facts['hw_part_version'] = None
facts['chassis_id'] = None
facts['mac_address'] = got_ver['systemMacAddress']
facts['virtual'] = bool('vEOS' == facts['hw_model'])
if facts['virtual']:
got_ma1 = self.api.execute('show interfaces ma1')
macaddr = got_ma1['interfaces']['Management1']['physicalAddress']
facts['serial_number'] = macaddr.replace(':', '').upper()
else:
facts['serial_number'] = got_ver['serialNumber']
try:
got_host = self.api.execute('show hostname')
facts['fqdn'] = got_host.get('fqdn')
facts['hostname'] = got_host.get('hostname')
except: # NOQA
facts['fqdn'] = 'localhost'
facts['hostname'] = 'localhost'
|
class Device(BaseDevice):
def __init__(self, target, **kwargs):
'''
:param target: hostname or ipaddr of target device
:param kwargs:
'user' : login user-name, defaults to "admin"
'passwd': login password, defaults to "admin
'''
pass
def gather_facts(self):
pass
| 3 | 1 | 20 | 3 | 14 | 4 | 2 | 0.23 | 1 | 2 | 1 | 0 | 2 | 0 | 2 | 7 | 43 | 7 | 30 | 9 | 27 | 7 | 29 | 9 | 26 | 3 | 2 | 1 | 4 |
6,267 |
Apstra/aeon-venos
|
Apstra_aeon-venos/pylib/aeon/eos/connector.py
|
pylib.aeon.eos.connector.Connector
|
class Connector(object):
DEFAULT_PROTOCOL = 'http'
VRF_MGMT = 'management'
DEFAULT_VRF = 'default'
def __init__(self, hostname, **kwargs):
self.vrf = self.VRF_MGMT
self.hostname = hostname
self.proto = kwargs.get('proto') or self.DEFAULT_PROTOCOL
self.port = kwargs.get('port')
# explicit check for None, since setting port to 0 is
# valid for on-box EOS.
if self.port is None:
self.port = socket.getservbyname(self.proto)
self.user = kwargs.get('user')
self.passwd = kwargs.get('passwd')
if self.proto == 'socket':
self.eapi = pyeapi.client.make_connection(
'socket', username=self.user, password=self.passwd,
**kwargs.get('socket_opts'))
else:
self.eapi = pyeapi.connect(
transport=self.proto, host=self.hostname,
username=self.user, password=self.passwd,
timeout=240)
def execute(self, commands, encoding='json'):
# Make a copy of commands so that commands object isn't mutated outside of this function
commands = deepcopy(commands)
# Convert to list if not already a list
commands = commands if isinstance(commands, list) else [commands]
# Add 'enable' if not the first enty in the commands list
if commands[0] != 'enable':
commands.insert(0, 'enable')
try:
got = self.eapi.execute(commands=commands, encoding=encoding)
except Exception as exc:
raise CommandError(exc=exc, commands=commands)
# get the results. if ther was only one command return the actual
# results item (vs. making the caller do [0]).
results = got['result']
results.pop(0)
return results if len(results) > 1 else results.pop()
def configure(self, contents):
if not isinstance(contents, list):
raise RuntimeError('contents must be a list, for now')
# filters out empty lines
contents = ['enable', 'configure'] + list(filter(bool, contents))
try:
self.eapi.execute(contents)
except Exception as exc:
raise ConfigError(exc=exc, contents=contents)
|
class Connector(object):
def __init__(self, hostname, **kwargs):
pass
def execute(self, commands, encoding='json'):
pass
def configure(self, contents):
pass
| 4 | 0 | 19 | 4 | 13 | 3 | 4 | 0.19 | 1 | 7 | 2 | 0 | 3 | 7 | 3 | 3 | 65 | 15 | 42 | 18 | 38 | 8 | 36 | 16 | 32 | 5 | 1 | 1 | 11 |
6,268 |
Apstra/aeon-venos
|
Apstra_aeon-venos/pylib/aeon/cumulus/device.py
|
pylib.aeon.cumulus.device.Device
|
class Device(BaseDevice):
OS_NAME = 'cumulus'
def __init__(self, target, **kwargs):
"""
:param target: hostname or ipaddr of target device
:param kwargs:
'user' : login user-name, defaults to "admin"
'passwd': login password, defaults to "admin
"""
BaseDevice.__init__(self, target, Connector, **kwargs)
def _serial_from_link(self, link_name):
good, got = self.api.execute(['ip link show dev %s' % link_name])
data = got[0]['stdout']
macaddr = data.partition('link/ether ')[-1].split()[0]
return macaddr.upper()
def gather_facts(self):
facts = self.facts
facts['os_name'] = self.OS_NAME
good, got = self.api.execute([
'hostname',
'cat /etc/lsb-release | grep RELEASE | cut -d= -f2',
'test -e /usr/cumulus/bin/decode-syseeprom'
])
facts['fqdn'] = got[0]['stdout'].strip()
facts['hostname'] = facts['fqdn']
facts['os_version'] = got[1]['stdout'].strip()
virt2 = bool(0 != got[2]['exit_code'])
if virt2 is True:
# this is a Cumulus VX 2.x device
facts['virtual'] = True
facts['vendor'] = 'CUMULUS-NETWORKS'
facts['serial_number'] = self._serial_from_link("eth0")
facts['mac_address'] = self._serial_from_link("eth0")
facts['hw_model'] = 'CUMULUS-VX'
facts['hw_part_number'] = None
facts['hw_version'] = None
facts['service_tag'] = None
else:
good, got = self.api.execute([
'sudo decode-syseeprom',
])
syseeprom = got[0]['stdout']
scanner = re.compile(r'(.+) 0x[A-F0-9]{2}\s+\d+\s+(.+)')
decoded = {
tag.strip(): value
for tag, value in scanner.findall(syseeprom)}
facts['mac_address'] = decoded.get('Base MAC Address', 'no-mac-addr')
facts['vendor'] = decoded.get('Vendor Name', 'no-vendor-name')
facts['serial_number'] = decoded.get('Serial Number', 'no-serial-number')
facts['hw_model'] = decoded.get('Product Name', 'no-product-name')
facts['virtual'] = bool(facts['hw_model'] == 'VX')
facts['hw_part_number'] = decoded.get('Part Number', 'no-part-number')
facts['hw_version'] = decoded.get('Label Revision', 'no-hw-version')
facts['service_tag'] = decoded.get('Service Tag', 'no-service-tag')
|
class Device(BaseDevice):
def __init__(self, target, **kwargs):
'''
:param target: hostname or ipaddr of target device
:param kwargs:
'user' : login user-name, defaults to "admin"
'passwd': login password, defaults to "admin
'''
pass
def _serial_from_link(self, link_name):
pass
def gather_facts(self):
pass
| 4 | 1 | 19 | 2 | 15 | 2 | 1 | 0.15 | 1 | 2 | 1 | 0 | 3 | 0 | 3 | 8 | 63 | 9 | 47 | 14 | 43 | 7 | 38 | 14 | 34 | 2 | 2 | 1 | 4 |
6,269 |
Apstra/aeon-venos
|
Apstra_aeon-venos/pylib/aeon/nxos/connector.py
|
pylib.aeon.nxos.connector.NxosConnector
|
class NxosConnector(object):
DEFAULT_PROTOCOL = 'http'
DEFAULT_TIMEOUT = 60
def __init__(self, hostname, **kwargs):
self.hostname = hostname
self.proto = kwargs.get('proto') or self.DEFAULT_PROTOCOL
self.port = kwargs.get('port') or socket.getservbyname(self.proto)
self.api_url = "{proto}://{target}:{port}/ins".format(
proto=self.proto, port=self.port, target=self.hostname)
self.api_headers = {
'cookie': 'no-cookie',
'content-type': 'text/xml'
}
self.user = kwargs.get('user')
self.passwd = kwargs.get('passwd')
# ---------------------------------------------------------------
# PROPERTIES
# ---------------------------------------------------------------
@property
def passwd(self):
""" passwd is write-only """
raise RuntimeError("passwd property is write-only")
@passwd.setter
def passwd(self, value):
""" changes the auth user-password """
self._passwd = value
@property
def api_auth(self):
return HTTPBasicAuth(self.user, self._passwd)
def exec_config(self, contents, timeout=None):
rqst = NxosConfigRequest()
rqst.command = _RE_CONF.sub(' ; ', contents)
resp = rqst.send(self, timeout)
# now we need to check the contents of the NX-API response ...
# we will just check for one instance right now ... may try to gather
# all of them &| include the XML body as part of the exception at some
# later point in time.
as_xml = etree.XML(resp.text)
cli_error = as_xml.find(_NXOS_RESP_XPATH_CLIERR)
if cli_error is not None:
raise NxosExc.CommandError(cli_error.text)
# config OK, yea!
return True
def exec_opcmd(self, command, raw_resp=False, timeout=None, **kwargs):
rqst = NxosOperRequest(command=command)
rqst.msg_type = kwargs.get('msg_type')
rqst.resp_fmt = kwargs.get('resp_fmt')
resp = rqst.send(self, timeout)
def rsp_is_xml():
as_xml = etree.XML(resp.text)
if raw_resp is True:
return as_xml
return as_xml.find(_NXOS_RESP_XPATH_BODY)
def rsp_is_json():
as_json = resp.json()
outputs = as_json['ins_api']['outputs']['output']
if 'clierror' in outputs:
raise NxosExc.CommandError(outputs['clierror'])
return as_json if raw_resp is True else outputs['body']
proc_rsp = rsp_is_json if 'json' == rqst.resp_fmt else rsp_is_xml
return proc_rsp()
|
class NxosConnector(object):
def __init__(self, hostname, **kwargs):
pass
@property
def passwd(self):
''' passwd is write-only '''
pass
@passwd.setter
def passwd(self):
''' changes the auth user-password '''
pass
@property
def api_auth(self):
pass
def exec_config(self, contents, timeout=None):
pass
def exec_opcmd(self, command, raw_resp=False, timeout=None, **kwargs):
pass
def rsp_is_xml():
pass
def rsp_is_json():
pass
| 12 | 2 | 10 | 2 | 7 | 1 | 2 | 0.2 | 1 | 5 | 3 | 0 | 6 | 7 | 6 | 6 | 84 | 23 | 51 | 31 | 39 | 10 | 44 | 28 | 35 | 3 | 1 | 1 | 13 |
6,270 |
Apstra/aeon-venos
|
Apstra_aeon-venos/pylib/aeon/exceptions.py
|
pylib.aeon.exceptions.CommandError
|
class CommandError(Exception):
def __init__(self, exc, commands):
super(CommandError, self).__init__(exc, commands)
self.exc = exc
self.commands = commands
def __repr__(self):
return self.exc.message
|
class CommandError(Exception):
def __init__(self, exc, commands):
pass
def __repr__(self):
pass
| 3 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 2 | 2 | 2 | 12 | 8 | 1 | 7 | 5 | 4 | 0 | 7 | 5 | 4 | 1 | 3 | 0 | 2 |
6,271 |
ArabellaTech/aa-intercom
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ArabellaTech_aa-intercom/aa_intercom/tests/test_base.py
|
aa_intercom.tests.test_base.TestIntercomAPI
|
class TestIntercomAPI(BaseTestCase):
intercom_user = {
"type": "user",
"id": "530370b477ad7120001d",
"user_id": "25",
"email": "wash@serenity.io",
"phone": "+1123456789",
"name": "Hoban Washburne",
"updated_at": 1392734388,
"last_seen_ip": "1.2.3.4",
"unsubscribed_from_emails": False,
"last_request_at": 1397574667,
"signed_up_at": 1392731331,
"created_at": 1392734388,
"session_count": 179,
"user_agent_data": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9",
"pseudonym": None,
"anonymous": False,
"custom_attributes": {
"paid_subscriber": True,
"monthly_spend": 155.5,
"team_mates": 1
},
"avatar": {
"type": "avatar",
"image_url": "https://example.org/128Wash.jpg"
},
"location_data": {
"type": "location_data",
"city_name": "Dublin",
"continent_code": "EU",
"country_code": "IRL",
"country_name": "Ireland",
"latitude": 53.159233,
"longitude": -6.723,
"postal_code": None,
"region_name": "Dublin",
"timezone": "Europe/Dublin"
},
}
@override_settings(SKIP_INTERCOM=False)
def test_upload(self):
with requests_mock.Mocker() as m:
url = "https://api.intercom.io/users/"
m.register_uri("POST", url, text=json.dumps(self.intercom_user))
self._create_user()
self.user.refresh_from_db()
self.assertIsNotNone(self.user.intercom_last_api_response)
# test case in which user does not exist (was removed in the meantime)
user_id = 8282
with self.assertRaises(UserModel.DoesNotExist):
UserModel.objects.get(pk=user_id)
with mock.patch("aa_intercom.tasks.cache.delete") as mocked_delete:
push_account_task.apply_async(args=[user_id])
mocked_delete.assert_called()
@freeze_time("2017-01-01")
@override_settings(SKIP_INTERCOM=False)
def test_not_registered_user_data_upload(self):
with requests_mock.Mocker() as m:
url = "https://api.intercom.io/users/"
m.register_uri("POST", url, text=json.dumps(self.intercom_user))
push_not_registered_user_data_task.apply_async(args=[{
k: self.intercom_user[k] for k in ["email", "name", "pseudonym"]
}])
self.assertTrue(m.called)
self.assertDictEqual(m.last_request.json(), {
"email": self.intercom_user["email"],
"name": self.intercom_user["name"],
"last_request_at": datetime.now().strftime("%s"),
"custom_attributes": {
"pseudonym": self.intercom_user["pseudonym"]
}
})
# assure push_account task does not fail in case of ServiceUnavailableError
with mock.patch("aa_intercom.utils.intercom", FakeIntercom()):
self._create_user()
last_api_response_timestamp = self.user.intercom_api_response_timestamp
self.user.refresh_from_db()
self.assertEqual(
self.user.intercom_api_response_timestamp, last_api_response_timestamp)
# make sure cache is deleted in case of an error
with mock.patch("aa_intercom.tasks.upload_not_registered_user_data", side_effect=MultipleMatchingUsersError()):
with mock.patch("aa_intercom.tasks.cache.delete") as mocked_delete:
with self.assertRaises(MultipleMatchingUsersError):
push_not_registered_user_data_task.apply_async(args=[{
"email": "foo@bar.bar"
}])
mocked_delete.assert_called()
# test sending data other than a dictionary
with self.assertRaises(NotImplementedError):
upload_not_registered_user_data(object())
# test sending data without the "email" keyword
with self.assertRaises(KeyError):
upload_not_registered_user_data({"name": "n"})
def test_intercom_example_event(self):
self._create_user()
mail.outbox = []
self.assertEqual(IntercomEvent.objects.count(), 0)
with override_settings(SKIP_INTERCOM=False):
with requests_mock.Mocker() as endpoints:
url_events = "https://api.intercom.io/events/"
url_users = "https://api.intercom.io/users/"
endpoints.register_uri("POST", url_events)
endpoints.register_uri("POST", url_users)
ie = IntercomEvent.objects.create(
user=self.user, type=EVENT_TYPE_EXAMPLE, metadata={"abc": 1})
self.assertFalse(ie.is_sent)
ie.refresh_from_db()
events = IntercomEvent.objects.all()
for e in events:
self.assertEqual(e.type, EVENT_TYPE_EXAMPLE)
self.assertTrue(ie.is_sent)
# test resending event - already sent, should not be sent again
last_api_response = self.user.intercom_last_api_response
ie.save()
self.assertEqual(last_api_response,
self.user.intercom_last_api_response)
# test sending event w/o user
with mock.patch("aa_intercom.tasks.upload_not_registered_user_data") as mocked_upload:
metadata = {"email": "foo@bar.foo"}
IntercomEvent.objects.create(
type=EVENT_TYPE_EXAMPLE, metadata=metadata)
mocked_upload.assert_called_with(metadata)
# test handling Intercom API errors
with mock.patch("aa_intercom.tasks.upload_intercom_user") as mocked_upload:
mocked_upload.side_effect = IntercomError("Unknown Error")
with self.assertRaises(IntercomError):
ie = IntercomEvent.objects.create(
user=self.user, type=EVENT_TYPE_EXAMPLE)
ie.refresh_from_db()
self.assertFalse(ie.is_sent)
# test case in which event was removed in meantime (before the task ran)
# make sure the cache is deleted
event_id = 8282
with self.assertRaises(IntercomEvent.DoesNotExist):
IntercomEvent.objects.get(pk=event_id)
with mock.patch("aa_intercom.tasks.upload_not_registered_user_data", side_effect=IntercomEvent.DoesNotExist()):
with mock.patch("aa_intercom.tasks.cache.delete") as mocked_delete:
with self.assertRaises(IntercomEvent.DoesNotExist):
push_intercom_event_task(event_id)
mocked_delete.assert_called()
def test_intercom_user_last_seen(self):
self._create_user()
# # clearing intercom last API response as creating user sets this
# Account.objects.filter(pk=self.user.pk).update(intercom_last_api_response=None)
self.user.refresh_from_db()
self.assertIsNone(self.user.intercom_last_api_response)
with requests_mock.Mocker() as endpoints:
url_users = "https://api.intercom.io/users/"
endpoints.register_uri(
"POST", url_users, text=json.dumps(self.intercom_user))
# login
self._login()
self.user.refresh_from_db()
self.assertIsNone(self.user.intercom_last_api_response)
with override_settings(SKIP_INTERCOM=False):
# simulate authentication scenario (for example in authenticate_credentials() method)
push_account_last_seen_task.apply_async(args=[self.user.id])
self.user.refresh_from_db()
self.assertIsNotNone(self.user.intercom_last_api_response)
|
class TestIntercomAPI(BaseTestCase):
@override_settings(SKIP_INTERCOM=False)
def test_upload(self):
pass
@freeze_time("2017-01-01")
@override_settings(SKIP_INTERCOM=False)
def test_not_registered_user_data_upload(self):
pass
def test_intercom_example_event(self):
pass
def test_intercom_user_last_seen(self):
pass
| 8 | 0 | 32 | 4 | 24 | 4 | 1 | 0.1 | 1 | 7 | 3 | 0 | 4 | 1 | 4 | 9 | 174 | 20 | 140 | 29 | 132 | 14 | 88 | 19 | 83 | 2 | 2 | 3 | 5 |
6,272 |
ArabellaTech/aa-intercom
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ArabellaTech_aa-intercom/aa_intercom/mixins.py
|
aa_intercom.mixins.IntercomUserMixin.Meta
|
class Meta:
abstract = True
|
class Meta:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 0 | 0 | 0 |
6,273 |
ArabellaTech/aa-intercom
|
ArabellaTech_aa-intercom/aa_intercom/tests/test_utils.py
|
aa_intercom.tests.test_utils.BaseTestCase
|
class BaseTestCase(TestCase):
maxDiff = None
password = "dump-password"
def toDict(self, obj):
"""Helper function to make errors in tests more readable - use to parse answer before compare"""
if not isinstance(obj, (dict, list, OrderedDict)):
return obj
if isinstance(obj, OrderedDict):
obj = dict(obj)
for k, v in obj.items():
new_v = v
if isinstance(v, list):
new_v = []
for v2 in v:
v2 = self.toDict(v2)
new_v.append(v2)
elif isinstance(v, OrderedDict):
new_v = dict(v)
obj[k] = new_v
return obj
def get_context(self, user=None):
if user is None:
user = self.user
request = HttpRequest()
request.user = user
context = {
"request": request
}
return context
def _login(self):
self.client.login(email="joe+1@doe.com", password=self.password)
def _new_user(self, i, is_active=True):
user = UserModel.objects.create(first_name="Joe%i" % i,
last_name="Doe",
email="joe+%s@doe.com" % i,
is_active=is_active,
username="joe%i" % i,
# zipcode="11111",
)
user.set_password(self.password)
user.save()
return user
def _create_user(self, i=1):
self.user = self._new_user(i)
return self.user
|
class BaseTestCase(TestCase):
def toDict(self, obj):
'''Helper function to make errors in tests more readable - use to parse answer before compare'''
pass
def get_context(self, user=None):
pass
def _login(self):
pass
def _new_user(self, i, is_active=True):
pass
def _create_user(self, i=1):
pass
| 6 | 1 | 8 | 0 | 8 | 0 | 2 | 0.05 | 1 | 3 | 0 | 2 | 5 | 1 | 5 | 5 | 50 | 5 | 43 | 15 | 37 | 2 | 35 | 15 | 29 | 7 | 1 | 3 | 12 |
6,274 |
ArabellaTech/aa-intercom
|
ArabellaTech_aa-intercom/test_project/models.py
|
test_project.models.UserModel
|
class UserModel(AbstractUser, IntercomUserMixin):
pass
|
class UserModel(AbstractUser, IntercomUserMixin):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 2 | 0 | 0 |
6,275 |
ArabellaTech/aa-intercom
|
ArabellaTech_aa-intercom/aa_intercom/tests/test_commands.py
|
aa_intercom.tests.test_commands.TestCommands
|
class TestCommands(BaseTestCase):
def setUp(self):
self.user_count = 5
self.users = [self._new_user(i) for i in range(self.user_count)]
def test_resend_intercom_events(self):
# Disable post_save signal during the test to simulate that the events were not sent and the
# resend_intercom_event command should be used
post_save.disconnect(intercom_event_push_to_intercom_post_save, sender=IntercomEvent)
intercom_events = [IntercomEvent.objects.create(user=self.users[i], type="generic")
for i in range(self.user_count)]
for e in intercom_events:
self.assertFalse(e.is_sent)
with mock.patch("aa_intercom.tasks.upload_intercom_user") as upload_mocked:
call_command("resend_intercom_events")
calls = [mock.call(self.users[i].id) for i in range(self.user_count)]
upload_mocked.assert_has_calls(calls)
|
class TestCommands(BaseTestCase):
def setUp(self):
pass
def test_resend_intercom_events(self):
pass
| 3 | 0 | 8 | 1 | 7 | 1 | 2 | 0.14 | 1 | 2 | 1 | 0 | 2 | 2 | 2 | 7 | 18 | 2 | 14 | 9 | 11 | 2 | 13 | 8 | 10 | 2 | 2 | 1 | 3 |
6,276 |
ArabellaTech/aa-intercom
|
ArabellaTech_aa-intercom/aa_intercom/tests/test_base.py
|
aa_intercom.tests.test_base.FakeIntercomUserService
|
class FakeIntercomUserService(object):
def create(self, *args, **kwargs):
raise ServiceUnavailableError
|
class FakeIntercomUserService(object):
def create(self, *args, **kwargs):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 3 | 0 | 3 | 2 | 1 | 0 | 3 | 2 | 1 | 1 | 1 | 0 | 1 |
6,277 |
ArabellaTech/aa-intercom
|
ArabellaTech_aa-intercom/aa_intercom/tests/test_base.py
|
aa_intercom.tests.test_base.FakeIntercom
|
class FakeIntercom(object):
@property
def users(self):
return FakeIntercomUserService()
|
class FakeIntercom(object):
@property
def users(self):
pass
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 1 | 4 | 0 | 4 | 3 | 1 | 0 | 3 | 2 | 1 | 1 | 1 | 0 | 1 |
6,278 |
ArabellaTech/aa-intercom
|
ArabellaTech_aa-intercom/aa_intercom/models.py
|
aa_intercom.models.IntercomEvent
|
class IntercomEvent(models.Model):
"""
Fill types per project.
Example usage in test_project.
"""
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="intercom_events", null=True, blank=True,
on_delete=models.CASCADE)
type = models.CharField(max_length=100, choices=settings.INTERCOM_EVENT_TYPES)
text_content = models.TextField(blank=True, null=True)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
content_type = models.ForeignKey(ContentType, blank=True, null=True, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField(blank=True, null=True)
content_object = generic.GenericForeignKey("content_type", "object_id")
is_sent = models.BooleanField(default=False)
# see: https://developers.intercom.com/v2.0/reference#event-model
metadata = JSONField(help_text=_("Optional metadata about the event"))
def get_intercom_data(self):
"""Specify the data sent to Intercom API according to event type"""
data = {
"event_name": self.get_type_display(), # event type
"created_at": calendar.timegm(self.created.utctimetuple()), # date
"metadata": self.metadata
}
if self.user:
data["user_id"] = self.user.intercom_id
return data
|
class IntercomEvent(models.Model):
'''
Fill types per project.
Example usage in test_project.
'''
def get_intercom_data(self):
'''Specify the data sent to Intercom API according to event type'''
pass
| 2 | 2 | 10 | 0 | 9 | 3 | 2 | 0.38 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 28 | 1 | 21 | 13 | 19 | 8 | 16 | 13 | 14 | 2 | 1 | 1 | 2 |
6,279 |
ArabellaTech/aa-intercom
|
ArabellaTech_aa-intercom/aa_intercom/migrations/0001_initial.py
|
aa_intercom.migrations.0001_initial.Migration
|
class Migration(migrations.Migration):
initial = True
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='IntercomEvent',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('type', models.CharField(choices=[(b'example type', 'Example Type'), (b'generic type', 'Generic Type')], max_length=100)),
('text_content', models.TextField(blank=True, null=True)),
('created', models.DateTimeField(auto_now_add=True)),
('modified', models.DateTimeField(auto_now=True)),
('object_id', models.PositiveIntegerField(blank=True, null=True)),
('is_sent', models.BooleanField(default=False)),
('metadata', jsonfield.fields.JSONField(default=dict)),
('content_type', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType')),
('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='intercom_events', to=settings.AUTH_USER_MODEL)),
],
),
]
|
class Migration(migrations.Migration):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 26 | 3 | 23 | 4 | 22 | 0 | 4 | 4 | 3 | 0 | 1 | 0 | 0 |
6,280 |
ArabellaTech/aa-intercom
|
ArabellaTech_aa-intercom/aa_intercom/mixins.py
|
aa_intercom.mixins.IntercomUserMixin
|
class IntercomUserMixin(models.Model):
"""Add fields required by aa_intercom to the user model"""
intercom_last_api_response = models.TextField(blank=True, null=True)
intercom_api_response_timestamp = models.DateTimeField(blank=True, null=True)
class Meta:
abstract = True
@property
def intercom_id(self):
return "%s_%s" % (getattr(settings, "INTERCOM_ID_PREFIX", ""), self.pk)
def get_intercom_data(self):
"""Specify the user data sent to Intercom API"""
return {
"user_id": self.intercom_id,
"email": self.email,
"name": self.get_full_name(),
"last_request_at": self.last_login.strftime("%s") if self.last_login else "",
"created_at": self.date_joined.strftime("%s"),
"custom_attributes": {
"is_admin": self.is_superuser
}
}
|
class IntercomUserMixin(models.Model):
'''Add fields required by aa_intercom to the user model'''
class Meta:
@property
def intercom_id(self):
pass
def get_intercom_data(self):
'''Specify the user data sent to Intercom API'''
pass
| 5 | 2 | 7 | 0 | 7 | 1 | 2 | 0.11 | 1 | 0 | 0 | 1 | 2 | 0 | 2 | 2 | 24 | 3 | 19 | 8 | 14 | 2 | 9 | 7 | 5 | 2 | 1 | 0 | 3 |
6,281 |
ArabellaTech/aa-intercom
|
ArabellaTech_aa-intercom/aa_intercom/admin.py
|
aa_intercom.admin.IntercomEventAdmin
|
class IntercomEventAdmin(admin.ModelAdmin):
readonly_fields = ("id", "user", "type", "text_content", "created", "modified", "content_type", "object_id",
"content_object", "is_sent")
list_display = ("id", "user", "type", "is_sent", "created")
list_filter = ("id", "user", "type", "is_sent")
def has_add_permission(self, request):
return False
|
class IntercomEventAdmin(admin.ModelAdmin):
def has_add_permission(self, request):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 9 | 2 | 7 | 5 | 5 | 0 | 6 | 5 | 4 | 1 | 1 | 0 | 1 |
6,282 |
ArabellaTech/aa-intercom
|
ArabellaTech_aa-intercom/aa_intercom/management/commands/resend_intercom_events.py
|
aa_intercom.management.commands.resend_intercom_events.Command
|
class Command(BaseCommand):
help = "Resend intercom events in case something went wrong"
def handle(self, **options):
events = IntercomEvent.objects.filter(is_sent=False)
for e in events:
push_intercom_event_task.apply_async(args=[e.id], countdown=110)
|
class Command(BaseCommand):
def handle(self, **options):
pass
| 2 | 0 | 4 | 0 | 4 | 0 | 2 | 0 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 1 | 7 | 1 | 6 | 5 | 4 | 0 | 6 | 5 | 4 | 2 | 1 | 1 | 2 |
6,283 |
ArabellaTech/aa-stripe
|
ArabellaTech_aa-stripe/aa_stripe/models.py
|
aa_stripe.models.StripeCharge
|
class StripeCharge(StripeBasicModel):
user = models.ForeignKey(USER_MODEL, on_delete=models.CASCADE, related_name="stripe_charges")
customer = models.ForeignKey(StripeCustomer, on_delete=models.SET_NULL, null=True)
amount = models.IntegerField(null=True, help_text=_("in cents"))
amount_refunded = models.IntegerField(null=True, help_text=_("in cents"), default=0)
is_charged = models.BooleanField(default=False)
is_refunded = models.BooleanField(default=False)
# if True, it will not be triggered through stripe_charge command
is_manual_charge = models.BooleanField(default=False)
charge_attempt_failed = models.BooleanField(default=False)
stripe_charge_id = models.CharField(max_length=255, blank=True, db_index=True)
stripe_refund_id = models.CharField(max_length=255, blank=True, db_index=True)
description = models.CharField(max_length=255, help_text=_("Description sent to Stripe"))
comment = models.CharField(max_length=255, help_text=_("Comment for internal information"))
content_type = models.ForeignKey(ContentType, null=True, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField(null=True, db_index=True)
source = generic.GenericForeignKey("content_type", "object_id")
statement_descriptor = models.CharField(max_length=22, blank=True)
def charge(self, idempotency_key=None, payment_uuid=None):
self.refresh_from_db() # to minimize the chance of double charging
if self.is_charged:
raise StripeMethodNotAllowed("Already charged.")
stripe.api_key = stripe_settings.API_KEY
customer = StripeCustomer.get_latest_active_customer_for_user(self.user)
self.customer = customer
if customer:
metadata = {
"object_id": self.object_id,
"content_type_id": self.content_type_id,
}
if settings.PAYMENT_ORIGIN:
metadata["origin"] = settings.PAYMENT_ORIGIN
if hasattr(self.user, "uuid"):
metadata["member_uuid"] = str(self.user.uuid)
if payment_uuid:
metadata["payment_uuid"] = str(payment_uuid)
idempotency_key = "{}-{}-{}".format(
metadata["object_id"], metadata["content_type_id"], idempotency_key
)
params = {
"amount": self.amount,
"currency": "usd",
"customer": customer.stripe_customer_id,
"description": self.description,
"metadata": metadata,
}
if self.statement_descriptor:
params["statement_descriptor"] = self.statement_descriptor
try:
stripe_charge = stripe.Charge.create(idempotency_key=idempotency_key, **params)
except stripe.error.CardError as e:
self.charge_attempt_failed = True
self.is_charged = False
self.stripe_charge_id = e.json_body.get("error", {}).get("charge", "")
self.stripe_response = e.json_body
self.save()
stripe_charge_card_exception.send(sender=StripeCharge, instance=self, exception=e)
return # just exit.
except stripe.error.APIError as e:
self.charge_attempt_failed = True
self.is_charged = False
self.stripe_response = e.json_body
logger.error("Temporary Stripe API error")
self.save()
raise StripeInternalError
except stripe.error.StripeError as e:
self.is_charged = False
self.stripe_response = e.json_body
try:
# hard error
if self.stripe_response["error"]["type"] == "invalid_request_error":
self.charge_attempt_failed = True
self.save()
stripe_charge_card_exception.send(sender=StripeCharge, instance=self, exception=e)
return # just exit.
except KeyError:
pass
self.save()
raise
self.stripe_charge_id = stripe_charge["id"]
self.stripe_response = stripe_charge
self.is_charged = True
self.save()
stripe_charge_succeeded.send(sender=StripeCharge, instance=self)
return stripe_charge
def refund(self, amount_to_refund=None, retry_on_error=True):
stripe.api_key = stripe_settings.API_KEY
if not self.is_charged:
raise StripeMethodNotAllowed("Cannot refund not charged transaction.")
if self.is_refunded:
raise StripeMethodNotAllowed("Already refunded.")
if amount_to_refund is None:
# refund all remaining amount
amount_to_refund = self.amount - self.amount_refunded
else:
# just to make sure
amount_to_refund = abs(amount_to_refund)
if (amount_to_refund + self.amount_refunded) > self.amount:
raise StripeMethodNotAllowed("Refunds exceed charge")
idempotency_key = "{}-{}-{}-{}".format(
self.object_id, self.content_type_id, self.amount_refunded, amount_to_refund
)
refund_id = ""
try:
stripe_refund = stripe.Refund.create(
idempotency_key=idempotency_key,
charge=self.stripe_charge_id,
amount=amount_to_refund,
)
refund_id = stripe_refund["id"]
except stripe.error.InvalidRequestError as e:
# retry if we're not already retrying (prevent infinite loop)
if not retry_on_error:
raise e
if e.code == "charge_already_refunded":
# Ignore this error, just update the records
pass
else:
stripe_charge = stripe.Charge.retrieve(self.stripe_charge_id)
if stripe_charge.amount_refunded != self.amount_refunded and e.code != "charge_already_refunded":
# refresh data and retry
self.amount_refunded = stripe_charge.amount_refunded
# set amount_to_refund to None to request maximum refund
return self.refund(amount_to_refund=None, retry_on_error=False)
self.is_refunded = (amount_to_refund + self.amount_refunded) == self.amount
self.amount_refunded += amount_to_refund
self.stripe_refund_id = refund_id
self.save()
stripe_charge_refunded.send(sender=StripeCharge, instance=self)
|
class StripeCharge(StripeBasicModel):
def charge(self, idempotency_key=None, payment_uuid=None):
pass
def refund(self, amount_to_refund=None, retry_on_error=True):
pass
| 3 | 0 | 63 | 8 | 52 | 5 | 11 | 0.09 | 1 | 5 | 3 | 0 | 2 | 1 | 2 | 2 | 146 | 17 | 121 | 30 | 118 | 11 | 102 | 28 | 99 | 12 | 2 | 4 | 21 |
6,284 |
ArabellaTech/aa-stripe
|
ArabellaTech_aa-stripe/aa_stripe/models.py
|
aa_stripe.models.StripeCouponQuerySet
|
class StripeCouponQuerySet(models.query.QuerySet):
def delete(self):
# StripeCoupon.delete must be executed (along with post_save)
deleted_counter = 0
for obj in self:
obj.delete()
deleted_counter = deleted_counter + 1
return deleted_counter, {self.model._meta.label: deleted_counter}
|
class StripeCouponQuerySet(models.query.QuerySet):
def delete(self):
pass
| 2 | 0 | 8 | 1 | 6 | 1 | 2 | 0.14 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 9 | 1 | 7 | 4 | 5 | 1 | 7 | 4 | 5 | 2 | 1 | 1 | 2 |
6,285 |
ArabellaTech/aa-stripe
|
ArabellaTech_aa-stripe/aa_stripe/models.py
|
aa_stripe.models.StripeCustomer
|
class StripeCustomer(StripeBasicModel):
user = models.ForeignKey(USER_MODEL, on_delete=models.CASCADE, related_name="stripe_customers")
stripe_js_response = JSONField(blank=True)
stripe_customer_id = models.CharField(max_length=255, db_index=True)
is_active = models.BooleanField(default=True)
is_created_at_stripe = models.BooleanField(default=False)
sources = JSONField(blank=True, default=[])
default_source = models.CharField(max_length=255, blank=True, help_text="ID of default source from Stripe")
def __init__(self, *args, **kwargs):
super(StripeCustomer, self).__init__(*args, **kwargs)
self._old_sources = self.sources # to track changes in post_save
def create_at_stripe(self, description=None):
if self.is_created_at_stripe:
raise StripeMethodNotAllowed()
if description is None:
description = "{user} id: {user.id}".format(user=self.user)
stripe.api_key = stripe_settings.API_KEY
customer = stripe.Customer.create(source=self.stripe_js_response["id"], description=description)
self.stripe_customer_id = customer["id"]
self.stripe_response = customer
self.sources = customer.sources.data
self.default_source = customer.default_source
self.is_created_at_stripe = True
self.save()
return self
@classmethod
def get_latest_active_customer_for_user(cls, user):
"""Returns last active stripe customer for user"""
customer = cls.objects.filter(user_id=user.id, is_active=True).last()
return customer
def change_description(self, description):
customer = self.retrieve_from_stripe()
customer.description = description
customer.save()
return customer
def retrieve_from_stripe(self):
stripe.api_key = stripe_settings.API_KEY
return stripe.Customer.retrieve(self.stripe_customer_id)
def _update_from_stripe_object(self, stripe_customer):
self.sources = stripe_customer.sources.data
self.default_source = stripe_customer.default_source or ""
self.save()
def refresh_from_stripe(self):
customer = self.retrieve_from_stripe()
self._update_from_stripe_object(customer)
return customer
def add_new_source(self, source_token, stripe_js_response=None):
"""Add new source (for example: a new card) to the customer
The new source will be automatically set as customer's default payment source.
Passing stripe_js_response is optional. If set, StripeCustomer.stripe_js_response will be updated.
"""
customer = self.retrieve_from_stripe()
customer.source = source_token
customer.save()
if stripe_js_response:
self.stripe_js_response = stripe_js_response
self._update_from_stripe_object(customer)
@property
def default_source_data(self):
if not self.default_source:
return
for source in self.sources:
if source["id"] == self.default_source:
return source
class Meta:
ordering = ["id"]
|
class StripeCustomer(StripeBasicModel):
def __init__(self, *args, **kwargs):
pass
def create_at_stripe(self, description=None):
pass
@classmethod
def get_latest_active_customer_for_user(cls, user):
'''Returns last active stripe customer for user'''
pass
def change_description(self, description):
pass
def retrieve_from_stripe(self):
pass
def _update_from_stripe_object(self, stripe_customer):
pass
def refresh_from_stripe(self):
pass
def add_new_source(self, source_token, stripe_js_response=None):
'''Add new source (for example: a new card) to the customer
The new source will be automatically set as customer's default payment source.
Passing stripe_js_response is optional. If set, StripeCustomer.stripe_js_response will be updated.
'''
pass
@property
def default_source_data(self):
pass
class Meta:
| 13 | 2 | 6 | 0 | 5 | 1 | 2 | 0.1 | 1 | 2 | 1 | 0 | 8 | 2 | 9 | 9 | 80 | 14 | 61 | 29 | 48 | 6 | 59 | 27 | 48 | 4 | 2 | 2 | 15 |
6,286 |
ArabellaTech/aa-stripe
|
ArabellaTech_aa-stripe/aa_stripe/models.py
|
aa_stripe.models.StripeSubscription
|
class StripeSubscription(StripeBasicModel):
STATUS_TRIAL = "trialing"
STATUS_ACTIVE = "active"
STATUS_PAST_DUE = "past_due"
STATUS_CANCELED = "canceled"
STATUS_UNPAID = "unpaid"
STATUS_CHOICES = (
(STATUS_TRIAL, STATUS_TRIAL),
(STATUS_ACTIVE, STATUS_ACTIVE),
(STATUS_PAST_DUE, STATUS_PAST_DUE),
(STATUS_CANCELED, STATUS_CANCELED),
(STATUS_UNPAID, STATUS_UNPAID),
)
stripe_subscription_id = models.CharField(max_length=255, blank=True, db_index=True)
is_created_at_stripe = models.BooleanField(default=False)
plan = models.ForeignKey(StripeSubscriptionPlan, on_delete=models.CASCADE)
user = models.ForeignKey(USER_MODEL, on_delete=models.CASCADE, related_name="stripe_subscriptions")
customer = models.ForeignKey(StripeCustomer, on_delete=models.SET_NULL, null=True)
status = models.CharField(
max_length=255,
help_text="https://stripe.com/docs/api/python#subscription_object-status, "
"empty if not sent created at stripe",
blank=True,
choices=STATUS_CHOICES,
)
metadata = JSONField(
blank=True,
help_text="https://stripe.com/docs/api/python#create_subscription-metadata",
)
tax_percent = models.DecimalField(
default=0,
validators=[MinValueValidator(0), MaxValueValidator(100)],
decimal_places=2,
max_digits=3,
help_text="https://stripe.com/docs/api/python#subscription_object-tax_percent",
)
# application_fee_percent = models.DecimalField(
# default=0, validators=[MinValueValidator(0), MaxValueValidator(100)], decimal_places=2, max_digits=3,
# help_text="https://stripe.com/docs/api/python#create_subscription-application_fee_percent")
coupon = models.ForeignKey(
StripeCoupon,
blank=True,
null=True,
on_delete=models.SET_NULL,
help_text="https://stripe.com/docs/api/python#create_subscription-coupon",
)
end_date = models.DateField(null=True, blank=True, db_index=True)
canceled_at = models.DateTimeField(null=True, blank=True, db_index=True)
at_period_end = models.BooleanField(default=False)
def create_at_stripe(self):
if self.is_created_at_stripe:
raise StripeMethodNotAllowed()
stripe.api_key = stripe_settings.API_KEY
customer = StripeCustomer.get_latest_active_customer_for_user(self.user)
if customer:
data = {
"customer": customer.stripe_customer_id,
"plan": self.plan.id,
"metadata": self.metadata,
"tax_percent": self.tax_percent,
}
if self.coupon:
data["coupon"] = self.coupon.coupon_id
try:
subscription = stripe.Subscription.create(**data)
except stripe.error.StripeError:
self.is_created_at_stripe = False
self.save()
raise
self.set_stripe_data(subscription)
return subscription
def set_stripe_data(self, subscription):
self.stripe_subscription_id = subscription["id"]
# for some reason it doesnt work with subscription only
self.stripe_response = json.loads(str(subscription))
self.is_created_at_stripe = True
self.status = subscription["status"]
self.save()
def refresh_from_stripe(self):
stripe.api_key = stripe_settings.API_KEY
subscription = stripe.Subscription.retrieve(self.stripe_subscription_id)
self.set_stripe_data(subscription)
return subscription
def _stripe_cancel(self, at_period_end=False):
subscription = self.refresh_from_stripe()
if subscription["status"] != "canceled":
return subscription.delete(at_period_end=at_period_end)
def cancel(self, at_period_end=False):
sub = self._stripe_cancel(at_period_end=at_period_end)
if sub and sub["status"] == "canceled" or sub["cancel_at_period_end"]:
self.canceled_at = timezone.now()
self.status = self.STATUS_CANCELED
self.at_period_end = at_period_end
self.save()
@classmethod
def get_subcriptions_for_cancel(cls):
today = timezone.localtime(timezone.now() + relativedelta(hours=1)).date()
return cls.objects.filter(end_date__lte=today, status=cls.STATUS_ACTIVE)
@classmethod
def end_subscriptions(cls, at_period_end=False):
# do not use in cron - one broken subscription will exit script.
# Instead please use end_subscriptions.py script.
for subscription in cls.get_subcriptions_for_cancel():
subscription.cancel(at_period_end)
sleep(0.25)
|
class StripeSubscription(StripeBasicModel):
def create_at_stripe(self):
pass
def set_stripe_data(self, subscription):
pass
def refresh_from_stripe(self):
pass
def _stripe_cancel(self, at_period_end=False):
pass
def cancel(self, at_period_end=False):
pass
@classmethod
def get_subcriptions_for_cancel(cls):
pass
@classmethod
def end_subscriptions(cls, at_period_end=False):
pass
| 10 | 0 | 8 | 0 | 7 | 1 | 2 | 0.11 | 1 | 4 | 2 | 0 | 5 | 1 | 7 | 7 | 116 | 11 | 99 | 37 | 89 | 11 | 65 | 35 | 57 | 5 | 2 | 2 | 14 |
6,287 |
ArabellaTech/aa-stripe
|
ArabellaTech_aa-stripe/aa_stripe/models.py
|
aa_stripe.models.StripeCouponManager
|
class StripeCouponManager(models.Manager):
def all_with_deleted(self):
return StripeCouponQuerySet(self.model, using=self._db)
def deleted(self):
return self.all_with_deleted().filter(is_deleted=True)
def get_queryset(self):
return self.all_with_deleted().filter(is_deleted=False)
|
class StripeCouponManager(models.Manager):
def all_with_deleted(self):
pass
def deleted(self):
pass
def get_queryset(self):
pass
| 4 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 1 | 1 | 0 | 3 | 1 | 3 | 3 | 9 | 2 | 7 | 5 | 3 | 0 | 7 | 4 | 3 | 1 | 1 | 0 | 3 |
6,288 |
ArabellaTech/aa-stripe
|
ArabellaTech_aa-stripe/aa_stripe/models.py
|
aa_stripe.models.StripeSubscriptionPlan
|
class StripeSubscriptionPlan(StripeBasicModel):
INTERVAL_DAY = "day"
INTERVAL_WEEK = "week"
INTERVAL_MONTH = "month"
INTERVAL_YEAR = "year"
INTERVAL_CHOICES = (
(INTERVAL_DAY, INTERVAL_DAY),
(INTERVAL_WEEK, INTERVAL_WEEK),
(INTERVAL_MONTH, INTERVAL_MONTH),
(INTERVAL_YEAR, INTERVAL_YEAR),
)
is_created_at_stripe = models.BooleanField(default=False)
source = JSONField(blank=True, help_text=_('Source of the plan, ie: {"prescription": 1}'))
amount = models.BigIntegerField(help_text=_("In cents. More: https://stripe.com/docs/api#create_plan-amount"))
currency = models.CharField(
max_length=3,
help_text=_("3 letter ISO code, default USD, https://stripe.com/docs/api#create_plan-currency"),
default="USD",
)
name = models.CharField(
max_length=255,
help_text=_("Name of the plan, to be displayed on invoices and in the web interface."),
)
interval = models.CharField(
max_length=10,
help_text=_("Specifies billing frequency. Either day, week, month or year."),
choices=INTERVAL_CHOICES,
)
interval_count = models.IntegerField(default=1, validators=[MinValueValidator(1)])
metadata = JSONField(
blank=True,
help_text=_(
"A set of key/value pairs that you can attach to a plan object. It can be useful"
" for storing additional information about the plan in a structured format."
),
)
statement_descriptor = models.CharField(
max_length=22,
help_text=_("An arbitrary string to be displayed on your customer’s credit card statement."),
blank=True,
)
trial_period_days = models.IntegerField(
default=0,
validators=[MinValueValidator(0)],
help_text=_(
"Specifies a trial period in (an integer number of) days. If you include a trial period,"
" the customer won’t be billed for the first time until the trial period ends. If the customer "
"cancels before the trial period is over, she’ll never be billed at all."
),
)
def create_at_stripe(self):
if self.is_created_at_stripe:
raise StripeMethodNotAllowed()
stripe.api_key = stripe_settings.API_KEY
try:
plan = stripe.Plan.create(
id=self.id,
amount=self.amount,
currency=self.currency,
interval=self.interval,
interval_count=self.interval_count,
name=self.name,
metadata=self.metadata,
statement_descriptor=self.statement_descriptor,
trial_period_days=self.trial_period_days,
)
except stripe.error.StripeError:
self.is_created_at_stripe = False
self.save()
raise
self.stripe_response = plan
self.is_created_at_stripe = True
self.save()
return plan
|
class StripeSubscriptionPlan(StripeBasicModel):
def create_at_stripe(self):
pass
| 2 | 0 | 26 | 2 | 24 | 0 | 3 | 0.03 | 1 | 1 | 1 | 0 | 1 | 2 | 1 | 1 | 79 | 5 | 74 | 20 | 72 | 2 | 30 | 19 | 28 | 3 | 2 | 1 | 3 |
6,289 |
ArabellaTech/aa-stripe
|
ArabellaTech_aa-stripe/aa_stripe/models.py
|
aa_stripe.models.StripeCoupon
|
class StripeCoupon(StripeBasicModel):
# fields that are fetched from Stripe API
STRIPE_FIELDS = {
"amount_off",
"currency",
"duration",
"duration_in_months",
"livemode",
"max_redemptions",
"percent_off",
"redeem_by",
"times_redeemed",
"valid",
"metadata",
"created",
}
DURATION_FOREVER = "forever"
DURATION_ONCE = "once"
DURATION_REPEATING = "repeating"
DURATION_CHOICES = (
(DURATION_FOREVER, DURATION_FOREVER),
(DURATION_ONCE, DURATION_ONCE),
(DURATION_REPEATING, DURATION_REPEATING),
)
# choices must be lowercase, because that is how Stripe API returns currency
# fmt: off
CURRENCY_CHOICES = (
('usd', 'USD'), ('aed', 'AED'), ('afn', 'AFN'), ('all', 'ALL'), ('amd', 'AMD'), ('ang', 'ANG'), ('aoa', 'AOA'),
('ars', 'ARS'), ('aud', 'AUD'), ('awg', 'AWG'), ('azn', 'AZN'), ('bam', 'BAM'), ('bbd', 'BBD'), ('bdt', 'BDT'),
('bgn', 'BGN'), ('bif', 'BIF'), ('bmd', 'BMD'), ('bnd', 'BND'), ('bob', 'BOB'), ('brl', 'BRL'), ('bsd', 'BSD'),
('bwp', 'BWP'), ('bzd', 'BZD'), ('cad', 'CAD'), ('cdf', 'CDF'), ('chf', 'CHF'), ('clp', 'CLP'), ('cny', 'CNY'),
('cop', 'COP'), ('crc', 'CRC'), ('cve', 'CVE'), ('czk', 'CZK'), ('djf', 'DJF'), ('dkk', 'DKK'), ('dop', 'DOP'),
('dzd', 'DZD'), ('egp', 'EGP'), ('etb', 'ETB'), ('eur', 'EUR'), ('fjd', 'FJD'), ('fkp', 'FKP'), ('gbp', 'GBP'),
('gel', 'GEL'), ('gip', 'GIP'), ('gmd', 'GMD'), ('gnf', 'GNF'), ('gtq', 'GTQ'), ('gyd', 'GYD'), ('hkd', 'HKD'),
('hnl', 'HNL'), ('hrk', 'HRK'), ('htg', 'HTG'), ('huf', 'HUF'), ('idr', 'IDR'), ('ils', 'ILS'), ('inr', 'INR'),
('isk', 'ISK'), ('jmd', 'JMD'), ('jpy', 'JPY'), ('kes', 'KES'), ('kgs', 'KGS'), ('khr', 'KHR'), ('kmf', 'KMF'),
('krw', 'KRW'), ('kyd', 'KYD'), ('kzt', 'KZT'), ('lak', 'LAK'), ('lbp', 'LBP'), ('lkr', 'LKR'), ('lrd', 'LRD'),
('lsl', 'LSL'), ('mad', 'MAD'), ('mdl', 'MDL'), ('mga', 'MGA'), ('mkd', 'MKD'), ('mmk', 'MMK'), ('mnt', 'MNT'),
('mop', 'MOP'), ('mro', 'MRO'), ('mur', 'MUR'), ('mvr', 'MVR'), ('mwk', 'MWK'), ('mxn', 'MXN'), ('myr', 'MYR'),
('mzn', 'MZN'), ('nad', 'NAD'), ('ngn', 'NGN'), ('nio', 'NIO'), ('nok', 'NOK'), ('npr', 'NPR'), ('nzd', 'NZD'),
('pab', 'PAB'), ('pen', 'PEN'), ('pgk', 'PGK'), ('php', 'PHP'), ('pkr', 'PKR'), ('pln', 'PLN'), ('pyg', 'PYG'),
('qar', 'QAR'), ('ron', 'RON'), ('rsd', 'RSD'), ('rub', 'RUB'), ('rwf', 'RWF'), ('sar', 'SAR'), ('sbd', 'SBD'),
('scr', 'SCR'), ('sek', 'SEK'), ('sgd', 'SGD'), ('shp', 'SHP'), ('sll', 'SLL'), ('sos', 'SOS'), ('srd', 'SRD'),
('std', 'STD'), ('svc', 'SVC'), ('szl', 'SZL'), ('thb', 'THB'), ('tjs', 'TJS'), ('top', 'TOP'), ('try', 'TRY'),
('ttd', 'TTD'), ('twd', 'TWD'), ('tzs', 'TZS'), ('uah', 'UAH'), ('ugx', 'UGX'), ('uyu', 'UYU'), ('uzs', 'UZS'),
('vnd', 'VND'), ('vuv', 'VUV'), ('wst', 'WST'), ('xaf', 'XAF'), ('xcd', 'XCD'), ('xof', 'XOF'), ('xpf', 'XPF'),
('yer', 'YER'), ('zar', 'ZAR'), ('zmw', 'ZMW')
)
# fmt: on
coupon_id = models.CharField(max_length=255, help_text=_("Identifier for the coupon"))
amount_off = models.DecimalField(
blank=True,
null=True,
decimal_places=2,
max_digits=10,
help_text=_(
"Amount (in the currency specified) that will be taken off the subtotal of any invoices for this"
"customer."
),
)
currency = models.CharField(
max_length=3,
choices=CURRENCY_CHOICES,
blank=True,
null=True,
help_text=_(
"If amount_off has been set, the three-letter ISO code for the currency of the amount to take " "off."
),
)
duration = models.CharField(
max_length=255,
choices=DURATION_CHOICES,
help_text=_("Describes how long a customer who applies this coupon will get the discount."),
)
duration_in_months = models.PositiveIntegerField(
blank=True,
null=True,
help_text=_(
"If duration is repeating, the number of months the coupon applies. "
"Null if coupon duration is forever or once."
),
)
livemode = models.BooleanField(
default=False,
help_text=_("Flag indicating whether the object exists in live mode or test mode."),
)
max_redemptions = models.PositiveIntegerField(
blank=True,
null=True,
help_text=_("Maximum number of times this coupon can be redeemed, in total, before it is no longer valid."),
)
metadata = JSONField(
blank=True,
help_text=_(
"Set of key/value pairs that you can attach to an object. It can be useful for "
"storing additional information about the object in a structured format."
),
)
percent_off = models.PositiveIntegerField(
blank=True,
null=True,
help_text=_(
"Percent that will be taken off the subtotal of any invoicesfor this customer for the duration of "
"the coupon. For example, a coupon with percent_off of 50 will make a $100 invoice $50 instead."
),
)
redeem_by = models.DateTimeField(
blank=True,
null=True,
help_text=_("Date after which the coupon can no longer be redeemed."),
)
times_redeemed = models.PositiveIntegerField(
default=0,
help_text=_("Number of times this coupon has been applied to a customer."),
)
valid = models.BooleanField(
default=False,
help_text=_("Taking account of the above properties, whether this coupon can still be applied to a customer."),
)
created = models.DateTimeField()
is_deleted = models.BooleanField(default=False)
is_created_at_stripe = models.BooleanField(default=False)
objects = StripeCouponManager()
def __init__(self, *args, **kwargs):
super(StripeCoupon, self).__init__(*args, **kwargs)
self._previous_is_deleted = self.is_deleted
def __str__(self):
return self.coupon_id
def update_from_stripe_data(self, stripe_coupon, exclude_fields=None, commit=True):
"""
Update StripeCoupon object with data from stripe.Coupon without calling stripe.Coupon.retrieve.
To only update the object, set the commit param to False.
Returns the number of rows altered or None if commit is False.
"""
fields_to_update = self.STRIPE_FIELDS - set(exclude_fields or [])
update_data = {key: stripe_coupon[key] for key in fields_to_update}
for field in ["created", "redeem_by"]:
if update_data.get(field):
update_data[field] = timestamp_to_timezone_aware_date(update_data[field])
if update_data.get("amount_off"):
update_data["amount_off"] = Decimal(update_data["amount_off"]) / 100
# also make sure the object is up to date (without the need to call database)
for key, value in update_data.items():
setattr(self, key, value)
if commit:
return StripeCoupon.objects.filter(pk=self.pk).update(**update_data)
def save(self, force_retrieve=False, *args, **kwargs):
"""
Use the force_retrieve parameter to create a new StripeCoupon object from an existing coupon created at Stripe
API or update the local object with data fetched from Stripe.
"""
stripe.api_key = stripe_settings.API_KEY
if self._previous_is_deleted != self.is_deleted and self.is_deleted:
try:
stripe_coupon = stripe.Coupon.retrieve(self.coupon_id)
# make sure to delete correct coupon
if self.created == timestamp_to_timezone_aware_date(stripe_coupon["created"]):
stripe_coupon.delete()
except stripe.error.InvalidRequestError:
# means that the coupon has already been removed from stripe
pass
return super(StripeCoupon, self).save(*args, **kwargs)
if self.pk or force_retrieve:
try:
stripe_coupon = stripe.Coupon.retrieve(self.coupon_id)
if not force_retrieve:
stripe_coupon.metadata = self.metadata
stripe_coupon.save()
if force_retrieve:
# make sure we are not creating a duplicate
coupon_qs = StripeCoupon.objects.filter(coupon_id=self.coupon_id)
if coupon_qs.filter(created=timestamp_to_timezone_aware_date(stripe_coupon["created"])).exists():
raise StripeCouponAlreadyExists
# all old coupons should be deleted
for coupon in coupon_qs:
coupon.is_deleted = True
super(StripeCoupon, coupon).save() # use super save() to call pre/post save signals
# update all fields in the local object in case someone tried to change them
self.update_from_stripe_data(
stripe_coupon,
exclude_fields=["metadata"] if not force_retrieve else [],
)
self.stripe_response = stripe_coupon
except stripe.error.InvalidRequestError:
if force_retrieve:
raise
self.is_deleted = True
else:
self.stripe_response = stripe.Coupon.create(
id=self.coupon_id,
duration=self.duration,
amount_off=int(self.amount_off * 100) if self.amount_off else None,
currency=self.currency,
duration_in_months=self.duration_in_months,
max_redemptions=self.max_redemptions,
metadata=self.metadata,
percent_off=self.percent_off,
redeem_by=int(dateformat.format(self.redeem_by, "U")) if self.redeem_by else None,
)
# stripe will generate coupon_id if none was specified in the request
if not self.coupon_id:
self.coupon_id = self.stripe_response["id"]
self.created = timestamp_to_timezone_aware_date(self.stripe_response["created"])
# for future
self.is_created_at_stripe = True
return super(StripeCoupon, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
self.is_deleted = True
self.save()
return 0, {self._meta.label: 0}
|
class StripeCoupon(StripeBasicModel):
def __init__(self, *args, **kwargs):
pass
def __str__(self):
pass
def update_from_stripe_data(self, stripe_coupon, exclude_fields=None, commit=True):
'''
Update StripeCoupon object with data from stripe.Coupon without calling stripe.Coupon.retrieve.
To only update the object, set the commit param to False.
Returns the number of rows altered or None if commit is False.
'''
pass
def save(self, force_retrieve=False, *args, **kwargs):
'''
Use the force_retrieve parameter to create a new StripeCoupon object from an existing coupon created at Stripe
API or update the local object with data fetched from Stripe.
'''
pass
def delete(self, *args, **kwargs):
pass
| 6 | 2 | 20 | 2 | 14 | 4 | 5 | 0.12 | 1 | 5 | 1 | 0 | 5 | 2 | 5 | 5 | 230 | 20 | 189 | 37 | 183 | 22 | 79 | 37 | 73 | 15 | 2 | 4 | 24 |
6,290 |
ArabellaTech/aa-stripe
|
ArabellaTech_aa-stripe/aa_stripe/migrations/0022_stripecharge_amount_refunded.py
|
aa_stripe.migrations.0022_stripecharge_amount_refunded.Migration
|
class Migration(migrations.Migration):
dependencies = [
('aa_stripe', '0021_auto_20190906_1623'),
]
operations = [
migrations.AddField(
model_name='stripecharge',
name='amount_refunded',
field=models.IntegerField(default=0, help_text='in cents', null=True),
),
]
|
class Migration(migrations.Migration):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 13 | 2 | 11 | 3 | 10 | 0 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
6,291 |
ArabellaTech/aa-stripe
|
ArabellaTech_aa-stripe/aa_stripe/migrations/0010_auto_20170822_1004.py
|
aa_stripe.migrations.0010_auto_20170822_1004.Migration
|
class Migration(migrations.Migration):
dependencies = [
('aa_stripe', '0009_auto_20170725_1205'),
]
operations = [
migrations.CreateModel(
name='StripeCoupon',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('updated', models.DateTimeField(auto_now=True)),
('stripe_response', django_extensions.db.fields.json.JSONField(default=dict)),
('coupon_id', models.CharField(help_text='Identifier for the coupon', max_length=255)),
('amount_off', models.DecimalField(decimal_places=2, max_digits=10, blank=True, help_text='Amount (in the currency specified) that will be taken off the subtotal ofany invoices for this customer.', null=True)),
('currency', models.CharField(default='usd', max_length=3, null=True, blank=True, help_text='If amount_off has been set, the three-letter ISO code for the currency of the amount to take off.', choices=[('usd', 'USD'), ('aed', 'AED'), ('afn', 'AFN'), ('all', 'ALL'), ('amd', 'AMD'), ('ang', 'ANG'), ('aoa', 'AOA'), ('ars', 'ARS'), ('aud', 'AUD'), ('awg', 'AWG'), ('azn', 'AZN'), ('bam', 'BAM'), ('bbd', 'BBD'), ('bdt', 'BDT'), ('bgn', 'BGN'), ('bif', 'BIF'), ('bmd', 'BMD'), ('bnd', 'BND'), ('bob', 'BOB'), ('brl', 'BRL'), ('bsd', 'BSD'), ('bwp', 'BWP'), ('bzd', 'BZD'), ('cad', 'CAD'), ('cdf', 'CDF'), ('chf', 'CHF'), ('clp', 'CLP'), ('cny', 'CNY'), ('cop', 'COP'), ('crc', 'CRC'), ('cve', 'CVE'), ('czk', 'CZK'), ('djf', 'DJF'), ('dkk', 'DKK'), ('dop', 'DOP'), ('dzd', 'DZD'), ('egp', 'EGP'), ('etb', 'ETB'), ('eur', 'EUR'), ('fjd', 'FJD'), ('fkp', 'FKP'), ('gbp', 'GBP'), ('gel', 'GEL'), ('gip', 'GIP'), ('gmd', 'GMD'), ('gnf', 'GNF'), ('gtq', 'GTQ'), ('gyd', 'GYD'), ('hkd', 'HKD'), ('hnl', 'HNL'), ('hrk', 'HRK'), ('htg', 'HTG'), ('huf', 'HUF'), ('idr', 'IDR'), ('ils', 'ILS'), ('inr', 'INR'), ('isk', 'ISK'), ('jmd', 'JMD'), ('jpy', 'JPY'), ('kes', 'KES'), ('kgs', 'KGS'), ('khr', 'KHR'), ('kmf', 'KMF'), ('krw', 'KRW'), ('kyd', 'KYD'), ('kzt', 'KZT'), ('lak', 'LAK'), ('lbp', 'LBP'), ('lkr', 'LKR'), ('lrd', 'LRD'), ('lsl', 'LSL'), ('mad', 'MAD'), ('mdl', 'MDL'), ('mga', 'MGA'), ('mkd', 'MKD'), ('mmk', 'MMK'), ('mnt', 'MNT'), ('mop', 'MOP'), ('mro', 'MRO'), ('mur', 'MUR'), ('mvr', 'MVR'), ('mwk', 'MWK'), ('mxn', 'MXN'), ('myr', 'MYR'), ('mzn', 'MZN'), ('nad', 'NAD'), ('ngn', 'NGN'), ('nio', 'NIO'), ('nok', 'NOK'), ('npr', 'NPR'), ('nzd', 'NZD'), ('pab', 'PAB'), ('pen', 'PEN'), ('pgk', 'PGK'), ('php', 'PHP'), ('pkr', 'PKR'), ('pln', 'PLN'), ('pyg', 'PYG'), ('qar', 'QAR'), ('ron', 'RON'), ('rsd', 'RSD'), ('rub', 'RUB'), ('rwf', 'RWF'), ('sar', 'SAR'), ('sbd', 'SBD'), ('scr', 'SCR'), ('sek', 'SEK'), ('sgd', 'SGD'), ('shp', 'SHP'), ('sll', 'SLL'), ('sos', 'SOS'), ('srd', 'SRD'), ('std', 'STD'), ('svc', 'SVC'), ('szl', 'SZL'), ('thb', 'THB'), ('tjs', 'TJS'), ('top', 'TOP'), ('try', 'TRY'), ('ttd', 'TTD'), ('twd', 'TWD'), ('tzs', 'TZS'), ('uah', 'UAH'), ('ugx', 'UGX'), ('uyu', 'UYU'), ('uzs', 'UZS'), ('vnd', 'VND'), ('vuv', 'VUV'), ('wst', 'WST'), ('xaf', 'XAF'), ('xcd', 'XCD'), ('xof', 'XOF'), ('xpf', 'XPF'), ('yer', 'YER'), ('zar', 'ZAR'), ('zmw', 'ZMW')])),
('duration', models.CharField(choices=[('forever', 'forever'), ('once', 'once'), ('repeating', 'repeating')], help_text='Describes how long a customer who applies this coupon will get the discount.', max_length=255)),
('duration_in_months', models.PositiveIntegerField(blank=True, help_text='If duration is repeating, the number of months the coupon applies.Null if coupon duration is forever or once.', null=True)),
('livemode', models.BooleanField(default=False, help_text='Flag indicating whether the object exists in live mode or test mode.')),
('max_redemptions', models.PositiveIntegerField(blank=True, help_text='Maximum number of times this coupon can be redeemed, in total, before it is no longer valid.', null=True)),
('metadata', django_extensions.db.fields.json.JSONField(default=dict, help_text='Set of key/value pairs that you can attach to an object. It can be useful forstoring additional information about the object in a structured format.')),
('percent_off', models.PositiveIntegerField(blank=True, help_text='Percent that will be taken off the subtotal of any invoicesfor this customer for the duration ofthe coupon. For example, a coupon with percent_off of 50 will make a $100 invoice $50 instead.', null=True)),
('redeem_by', models.DateTimeField(blank=True, help_text='Date after which the coupon can no longer be redeemed.', null=True)),
('times_redeemed', models.PositiveIntegerField(default=0, help_text='Number of times this coupon has been applied to a customer.')),
('valid', models.BooleanField(default=False, help_text='Taking account of the above properties, whether this coupon can still be applied to a customer.')),
('created', models.DateTimeField()),
('is_deleted', models.BooleanField(default=False)),
('is_created_at_stripe', models.BooleanField(default=False)),
],
options={
'abstract': False,
},
),
migrations.RenameField(
model_name='stripesubscription',
old_name='coupon',
new_name='coupon_code',
),
migrations.AddField(
model_name='stripesubscription',
name='coupon',
field=models.ForeignKey(blank=True, help_text='https://stripe.com/docs/api/python#create_subscription-coupon', null=True, on_delete=django.db.models.deletion.SET_NULL, to='aa_stripe.StripeCoupon'),
),
migrations.RunPython(
code=migrate_subcription,
hints={'target_db': 'default'}
),
migrations.RemoveField(
model_name='stripesubscription',
name='coupon_code'
)
]
|
class Migration(migrations.Migration):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0.02 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 52 | 2 | 50 | 3 | 49 | 1 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
6,292 |
ArabellaTech/aa-stripe
|
ArabellaTech_aa-stripe/aa_stripe/migrations/0020_stripecharge_statement_descriptor.py
|
aa_stripe.migrations.0020_stripecharge_statement_descriptor.Migration
|
class Migration(migrations.Migration):
dependencies = [
('aa_stripe', '0019_stripecustomer_default_source'),
]
operations = [
migrations.AddField(
model_name='stripecharge',
name='statement_descriptor',
field=models.CharField(blank=True, max_length=22),
),
]
|
class Migration(migrations.Migration):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 13 | 2 | 11 | 3 | 10 | 0 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
6,293 |
ArabellaTech/aa-stripe
|
ArabellaTech_aa-stripe/aa_stripe/migrations/0019_stripecustomer_default_source.py
|
aa_stripe.migrations.0019_stripecustomer_default_source.Migration
|
class Migration(migrations.Migration):
dependencies = [
('aa_stripe', '0018_stripecustomer_sources'),
]
operations = [
migrations.AddField(
model_name='stripecustomer',
name='default_source',
field=models.CharField(blank=True, help_text='ID of default source from Stripe', max_length=255),
),
]
|
class Migration(migrations.Migration):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 13 | 2 | 11 | 3 | 10 | 0 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
6,294 |
ArabellaTech/aa-stripe
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ArabellaTech_aa-stripe/aa_stripe/models.py
|
aa_stripe.models.StripeWebhook.Meta
|
class Meta:
ordering = ["-created"]
|
class Meta:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 0 | 0 | 0 |
6,295 |
ArabellaTech/aa-stripe
|
ArabellaTech_aa-stripe/aa_stripe/migrations/0018_stripecustomer_sources.py
|
aa_stripe.migrations.0018_stripecustomer_sources.Migration
|
class Migration(migrations.Migration):
dependencies = [
('aa_stripe', '0017_stripecharge_manual_charge'),
]
operations = [
migrations.AddField(
model_name='stripecustomer',
name='sources',
field=django_extensions.db.fields.json.JSONField(default=[]),
),
]
|
class Migration(migrations.Migration):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 13 | 2 | 11 | 3 | 10 | 0 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
6,296 |
ArabellaTech/aa-stripe
|
ArabellaTech_aa-stripe/aa_stripe/migrations/0017_stripecharge_manual_charge.py
|
aa_stripe.migrations.0017_stripecharge_manual_charge.Migration
|
class Migration(migrations.Migration):
dependencies = [
('aa_stripe', '0016_stripecharge_is_refunded'),
]
operations = [
migrations.AddField(
model_name='stripecharge',
name='is_manual_charge',
field=models.BooleanField(default=False),
),
]
|
class Migration(migrations.Migration):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 13 | 2 | 11 | 3 | 10 | 0 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
6,297 |
ArabellaTech/aa-stripe
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ArabellaTech_aa-stripe/aa_stripe/models.py
|
aa_stripe.models.StripeCustomer.Meta
|
class Meta:
ordering = ["id"]
|
class Meta:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 0 | 0 | 0 |
6,298 |
ArabellaTech/aa-stripe
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ArabellaTech_aa-stripe/aa_stripe/models.py
|
aa_stripe.models.StripeBasicModel.Meta
|
class Meta:
abstract = True
|
class Meta:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 0 | 0 | 0 |
6,299 |
ArabellaTech/aa-stripe
|
ArabellaTech_aa-stripe/aa_stripe/migrations/0021_auto_20190906_1623.py
|
aa_stripe.migrations.0021_auto_20190906_1623.Migration
|
class Migration(migrations.Migration):
dependencies = [
('aa_stripe', '0020_stripecharge_statement_descriptor'),
]
operations = [
migrations.AlterField(
model_name='stripecharge',
name='stripe_refund_id',
field=models.CharField(blank=True, db_index=True, max_length=255),
),
migrations.AlterField(
model_name='stripecharge',
name='stripe_response',
field=django_extensions.db.fields.json.JSONField(blank=True, default=dict),
),
migrations.AlterField(
model_name='stripecoupon',
name='metadata',
field=django_extensions.db.fields.json.JSONField(blank=True, default=dict, help_text='Set of key/value pairs that you can attach to an object. It can be useful for storing additional information about the object in a structured format.'),
),
migrations.AlterField(
model_name='stripecoupon',
name='stripe_response',
field=django_extensions.db.fields.json.JSONField(blank=True, default=dict),
),
migrations.AlterField(
model_name='stripecustomer',
name='sources',
field=django_extensions.db.fields.json.JSONField(blank=True, default=[]),
),
migrations.AlterField(
model_name='stripecustomer',
name='stripe_js_response',
field=django_extensions.db.fields.json.JSONField(blank=True, default=dict),
),
migrations.AlterField(
model_name='stripecustomer',
name='stripe_response',
field=django_extensions.db.fields.json.JSONField(blank=True, default=dict),
),
migrations.AlterField(
model_name='stripesubscription',
name='metadata',
field=django_extensions.db.fields.json.JSONField(blank=True, default=dict, help_text='https://stripe.com/docs/api/python#create_subscription-metadata'),
),
migrations.AlterField(
model_name='stripesubscription',
name='stripe_response',
field=django_extensions.db.fields.json.JSONField(blank=True, default=dict),
),
migrations.AlterField(
model_name='stripesubscriptionplan',
name='metadata',
field=django_extensions.db.fields.json.JSONField(blank=True, default=dict, help_text='A set of key/value pairs that you can attach to a plan object. It can be useful for storing additional information about the plan in a structured format.'),
),
migrations.AlterField(
model_name='stripesubscriptionplan',
name='stripe_response',
field=django_extensions.db.fields.json.JSONField(blank=True, default=dict),
),
migrations.AlterField(
model_name='stripewebhook',
name='raw_data',
field=django_extensions.db.fields.json.JSONField(blank=True, default=dict),
),
]
|
class Migration(migrations.Migration):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0.02 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 68 | 2 | 66 | 3 | 65 | 1 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.