INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Fetch ancestors quotas that have the same name and are registered as aggregator quotas.
def get_aggregator_quotas(self, quota): """ Fetch ancestors quotas that have the same name and are registered as aggregator quotas. """ ancestors = quota.scope.get_quota_ancestors() aggregator_quotas = [] for ancestor in ancestors: for ancestor_quota_field in ancestor.get_quo...
Adds a new event handler.
def subscribe(self, handler): """Adds a new event handler.""" assert callable(handler), "Invalid handler %s" % handler self.handlers.append(handler)
* Safely * triggers the event by invoking all its handlers even if few of them raise an exception.
def safe_trigger(self, *args): """*Safely* triggers the event by invoking all its handlers, even if few of them raise an exception. If a set of exceptions is raised during handler invocation sequence, this method rethrows the first one. :param args: the arguments to invoke even...
Attaches the handler to the specified event.
def on(self, event, handler): """Attaches the handler to the specified event. @param event: event to attach the handler to. Any object can be passed as event, but string is preferable. If qcore.EnumBase instance is passed, its name is used as event key. ...
Detaches the handler from the specified event.
def off(self, event, handler): """Detaches the handler from the specified event. @param event: event to detach the handler to. Any object can be passed as event, but string is preferable. If qcore.EnumBase instance is passed, its name is used as event key. ...
Triggers the specified event by invoking EventHook. trigger under the hood.
def trigger(self, event, *args): """Triggers the specified event by invoking EventHook.trigger under the hood. @param event: event to trigger. Any object can be passed as event, but string is preferable. If qcore.EnumBase instance is passed, its name is used ...
Safely triggers the specified event by invoking EventHook. safe_trigger under the hood.
def safe_trigger(self, event, *args): """Safely triggers the specified event by invoking EventHook.safe_trigger under the hood. @param event: event to trigger. Any object can be passed as event, but string is preferable. If qcore.EnumBase instance is ...
Gets or creates a new event hook for the specified event ( key ).
def get_or_create(self, event): """Gets or creates a new event hook for the specified event (key). This method treats qcore.EnumBase-typed event keys specially: enum_member.name is used as key instead of enum instance in case such a key is passed. Note that on/off/trigger/safe_...
Invitation lifetime must be specified in Waldur Core settings with parameter INVITATION_LIFETIME. If invitation creation time is less than expiration time the invitation will set as expired.
def cancel_expired_invitations(invitations=None): """ Invitation lifetime must be specified in Waldur Core settings with parameter "INVITATION_LIFETIME". If invitation creation time is less than expiration time, the invitation will set as expired. """ expiration_date = timezone.now() - settings.WALD...
Lookup sighash from 4bytes. directory create a pseudo api and try to decode it with the parsed abi. May return multiple results as sighashes may collide.: param s: bytes input: return: pseudo abi for method
def get_pseudo_abi_for_input(s, timeout=None, proxies=None): """ Lookup sighash from 4bytes.directory, create a pseudo api and try to decode it with the parsed abi. May return multiple results as sighashes may collide. :param s: bytes input :return: pseudo abi for method ...
Prepare the contract json abi for sighash lookups and fast access
def _prepare_abi(self, jsonabi): """ Prepare the contract json abi for sighash lookups and fast access :param jsonabi: contracts abi in json format :return: """ self.signatures = {} for element_description in jsonabi: abi_e = AbiMethod(element_descrip...
Describe the input bytesequence ( constructor arguments ) s based on the loaded contract abi definition
def describe_constructor(self, s): """ Describe the input bytesequence (constructor arguments) s based on the loaded contract abi definition :param s: bytes constructor arguments :return: AbiMethod instance """ method = self.signatures.get(b"__constructor__") ...
Describe the input bytesequence s based on the loaded contract abi definition
def describe_input(self, s): """ Describe the input bytesequence s based on the loaded contract abi definition :param s: bytes input :return: AbiMethod instance """ signatures = self.signatures.items() for sighash, method in signatures: if sighash is...
Return a new AbiMethod object from an input stream: param s: binary input: return: new AbiMethod object matching the provided input stream
def from_input_lookup(s): """ Return a new AbiMethod object from an input stream :param s: binary input :return: new AbiMethod object matching the provided input stream """ for pseudo_abi in FourByteDirectory.get_pseudo_abi_for_input(s): method = AbiMethod(pse...
Raises an AssertionError if expected is not actual.
def assert_is(expected, actual, message=None, extra=None): """Raises an AssertionError if expected is not actual.""" assert expected is actual, _assert_fail_message( message, expected, actual, "is not", extra )
Raises an AssertionError if expected is actual.
def assert_is_not(expected, actual, message=None, extra=None): """Raises an AssertionError if expected is actual.""" assert expected is not actual, _assert_fail_message( message, expected, actual, "is", extra )
Raises an AssertionError if value is not an instance of type ( s ).
def assert_is_instance(value, types, message=None, extra=None): """Raises an AssertionError if value is not an instance of type(s).""" assert isinstance(value, types), _assert_fail_message( message, value, types, "is not an instance of", extra )
Raises an AssertionError if expected ! = actual.
def assert_eq(expected, actual, message=None, tolerance=None, extra=None): """Raises an AssertionError if expected != actual. If tolerance is specified, raises an AssertionError if either - expected or actual isn't a number, or - the difference between expected and actual is larger than the tolerance. ...
Asserts that two dictionaries are equal producing a custom message if they are not.
def assert_dict_eq(expected, actual, number_tolerance=None, dict_path=[]): """Asserts that two dictionaries are equal, producing a custom message if they are not.""" assert_is_instance(expected, dict) assert_is_instance(actual, dict) expected_keys = set(expected.keys()) actual_keys = set(actual.key...
Raises an AssertionError if left_hand < = right_hand.
def assert_gt(left, right, message=None, extra=None): """Raises an AssertionError if left_hand <= right_hand.""" assert left > right, _assert_fail_message(message, left, right, "<=", extra)
Raises an AssertionError if left_hand < right_hand.
def assert_ge(left, right, message=None, extra=None): """Raises an AssertionError if left_hand < right_hand.""" assert left >= right, _assert_fail_message(message, left, right, "<", extra)
Raises an AssertionError if left_hand > = right_hand.
def assert_lt(left, right, message=None, extra=None): """Raises an AssertionError if left_hand >= right_hand.""" assert left < right, _assert_fail_message(message, left, right, ">=", extra)
Raises an AssertionError if left_hand > right_hand.
def assert_le(left, right, message=None, extra=None): """Raises an AssertionError if left_hand > right_hand.""" assert left <= right, _assert_fail_message(message, left, right, ">", extra)
Raises an AssertionError if obj is not in seq.
def assert_in(obj, seq, message=None, extra=None): """Raises an AssertionError if obj is not in seq.""" assert obj in seq, _assert_fail_message(message, obj, seq, "is not in", extra)
Raises an AssertionError if obj is in iter.
def assert_not_in(obj, seq, message=None, extra=None): """Raises an AssertionError if obj is in iter.""" # for very long strings, provide a truncated error if isinstance(seq, six.string_types) and obj in seq and len(seq) > 200: index = seq.find(obj) start_index = index - 50 if start_...
Raises an AssertionError if obj is not in seq using assert_eq cmp.
def assert_in_with_tolerance(obj, seq, tolerance, message=None, extra=None): """Raises an AssertionError if obj is not in seq using assert_eq cmp.""" for i in seq: try: assert_eq(obj, i, tolerance=tolerance, message=message, extra=extra) return except AssertionError: ...
Raises an AssertionError if substring is not a substring of subject.
def assert_is_substring(substring, subject, message=None, extra=None): """Raises an AssertionError if substring is not a substring of subject.""" assert ( (subject is not None) and (substring is not None) and (subject.find(substring) != -1) ), _assert_fail_message(message, substring,...
Raises an AssertionError if substring is a substring of subject.
def assert_is_not_substring(substring, subject, message=None, extra=None): """Raises an AssertionError if substring is a substring of subject.""" assert ( (subject is not None) and (substring is not None) and (subject.find(substring) == -1) ), _assert_fail_message(message, substring,...
Raises an AssertionError if the objects contained in expected are not equal to the objects contained in actual without regard to their order.
def assert_unordered_list_eq(expected, actual, message=None): """Raises an AssertionError if the objects contained in expected are not equal to the objects contained in actual without regard to their order. This takes quadratic time in the umber of elements in actual; don't use it for very long lists....
Execute function only if one of input parameters is not empty
def _execute_if_not_empty(func): """ Execute function only if one of input parameters is not empty """ def wrapper(*args, **kwargs): if any(args[1:]) or any(kwargs.items()): return func(*args, **kwargs) return wrapper
Prepare body for elasticsearch query
def prepare_search_body(self, should_terms=None, must_terms=None, must_not_terms=None, search_text='', start=None, end=None): """ Prepare body for elasticsearch query Search parameters ^^^^^^^^^^^^^^^^^ These parameters are dictionaries and have format: <term>: [<value 1>, <val...
Execute high level - operation
def execute(cls, instance, async=True, countdown=2, is_heavy_task=False, **kwargs): """ Execute high level-operation """ cls.pre_apply(instance, async=async, **kwargs) result = cls.apply_signature(instance, async=async, countdown=countdown, is_heavy_task=is_h...
Serialize input data and apply signature
def apply_signature(cls, instance, async=True, countdown=None, is_heavy_task=False, **kwargs): """ Serialize input data and apply signature """ serialized_instance = utils.serialize_instance(instance) signature = cls.get_task_signature(instance, serialized_instance, **kwargs) link = cls...
Synchronously execute callback
def _apply_callback(cls, callback, result): """ Synchronously execute callback """ if not callback.immutable: callback.args = (result.id, ) + callback.args callback.apply()
Returns description in format: * entity human readable name * docstring
def get_entity_description(entity): """ Returns description in format: * entity human readable name * docstring """ try: entity_name = entity.__name__.strip('_') except AttributeError: # entity is a class instance entity_name = entity.__class__.__name__ label =...
Returns validators description in format: ### Validators: * validator1 name * validator1 docstring * validator2 name * validator2 docstring
def get_validators_description(view): """ Returns validators description in format: ### Validators: * validator1 name * validator1 docstring * validator2 name * validator2 docstring """ action = getattr(view, 'action', None) if action is None: return '' description...
Returns actions permissions description in format: * permission1 name * permission1 docstring * permission2 name * permission2 docstring
def get_actions_permission_description(view, method): """ Returns actions permissions description in format: * permission1 name * permission1 docstring * permission2 name * permission2 docstring """ action = getattr(view, 'action', None) if action is None: return '' if...
Returns permissions description in format: ### Permissions: * permission1 name * permission1 docstring * permission2 name * permission2 docstring
def get_permissions_description(view, method): """ Returns permissions description in format: ### Permissions: * permission1 name * permission1 docstring * permission2 name * permission2 docstring """ if not hasattr(view, 'permission_classes'): return '' description = ...
Returns validation description in format: ### Validation: validate method docstring * field1 name * field1 validation docstring * field2 name * field2 validation docstring
def get_validation_description(view, method): """ Returns validation description in format: ### Validation: validate method docstring * field1 name * field1 validation docstring * field2 name * field2 validation docstring """ if method not in ('PUT', 'PATCH', 'POST') or not has...
Returns field type/ possible values.
def get_field_type(field): """ Returns field type/possible values. """ if isinstance(field, core_filters.MappedMultipleChoiceFilter): return ' | '.join(['"%s"' % f for f in sorted(field.mapped_to_model)]) if isinstance(field, OrderingFilter) or isinstance(field, ChoiceFilter): return...
Checks whether Link action is disabled.
def is_disabled_action(view): """ Checks whether Link action is disabled. """ if not isinstance(view, core_views.ActionsViewSet): return False action = getattr(view, 'action', None) return action in view.disabled_actions if action is not None else False
Return a list of the valid HTTP methods for this endpoint.
def get_allowed_methods(self, callback): """ Return a list of the valid HTTP methods for this endpoint. """ if hasattr(callback, 'actions'): return [method.upper() for method in callback.actions.keys() if method != 'head'] return [ method for method in ...
Given a callback return an actual view instance.
def create_view(self, callback, method, request=None): """ Given a callback, return an actual view instance. """ view = super(WaldurSchemaGenerator, self).create_view(callback, method, request) if is_disabled_action(view): view.exclude_from_schema = True retu...
Determine a link description.
def get_description(self, path, method, view): """ Determine a link description. This will be based on the method docstring if one exists, or else the class docstring. """ description = super(WaldurSchemaGenerator, self).get_description(path, method, view) permi...
Return a list of coreapi. Field instances corresponding to any request body input as determined by the serializer class.
def get_serializer_fields(self, path, method, view): """ Return a list of `coreapi.Field` instances corresponding to any request body input, as determined by the serializer class. """ if method not in ('PUT', 'PATCH', 'POST'): return [] if not hasattr(view, '...
Delete error message if instance state changed from erred
def delete_error_message(sender, instance, name, source, target, **kwargs): """ Delete error message if instance state changed from erred """ if source != StateMixin.States.ERRED: return instance.error_message = '' instance.save(update_fields=['error_message'])
read __init__. py
def find_version(*file_paths): """ read __init__.py """ file_path = os.path.join(*file_paths) with open(file_path, 'r') as version_file: line = version_file.readline() while line: if line.startswith('__version__'): version_match = re.search( ...
This decorator prints entry and exit message when the decorated method is called as well as call arguments result and thrown exception ( if any ).
def trace(enter=False, exit=True): """ This decorator prints entry and exit message when the decorated method is called, as well as call arguments, result and thrown exception (if any). :param enter: indicates whether entry message should be printed. :param exit: indicates whether exit message ...
Instantiates an enum with an arbitrary value.
def _make_value(self, value): """Instantiates an enum with an arbitrary value.""" member = self.__new__(self, value) member.__init__(value) return member
Creates a new enum type based on this one ( cls ) and adds newly passed members to the newly created subclass of cls.
def create(cls, name, members): """Creates a new enum type based on this one (cls) and adds newly passed members to the newly created subclass of cls. This method helps to create enums having the same member values as values of other enum(s). :param name: name of the newly crea...
Parses an enum member name or value into an enum member.
def parse(cls, value, default=_no_default): """Parses an enum member name or value into an enum member. Accepts the following types: - Members of this enum class. These are returned directly. - Integers. If there is an enum member with the integer as a value, that member is returned. ...
Parses a flag integer or string into a Flags instance.
def parse(cls, value, default=_no_default): """Parses a flag integer or string into a Flags instance. Accepts the following types: - Members of this enum class. These are returned directly. - Integers. These are converted directly into a Flags instance with the given name. - Str...
To get a list of price estimates run ** GET ** against */ api/ price - estimates/ * as authenticated user. You can filter price estimates by scope type scope URL customer UUID.
def list(self, request, *args, **kwargs): """ To get a list of price estimates, run **GET** against */api/price-estimates/* as authenticated user. You can filter price estimates by scope type, scope URL, customer UUID. `scope_type` is generic type of object for which price estimate is c...
To get a list of price list items run ** GET ** against */ api/ price - list - items/ * as an authenticated user.
def list(self, request, *args, **kwargs): """ To get a list of price list items, run **GET** against */api/price-list-items/* as an authenticated user. """ return super(PriceListItemViewSet, self).list(request, *args, **kwargs)
Run ** POST ** request against */ api/ price - list - items/ * to create new price list item. Customer owner and staff can create price items.
def create(self, request, *args, **kwargs): """ Run **POST** request against */api/price-list-items/* to create new price list item. Customer owner and staff can create price items. Example of request: .. code-block:: http POST /api/price-list-items/ HTTP/1.1 ...
Run ** PATCH ** request against */ api/ price - list - items/ <uuid >/ * to update price list item. Only item_type key value and units can be updated. Only customer owner and staff can update price items.
def update(self, request, *args, **kwargs): """ Run **PATCH** request against */api/price-list-items/<uuid>/* to update price list item. Only item_type, key value and units can be updated. Only customer owner and staff can update price items. """ return super(PriceListIte...
Run ** DELETE ** request against */ api/ price - list - items/ <uuid >/ * to delete price list item. Only customer owner and staff can delete price items.
def destroy(self, request, *args, **kwargs): """ Run **DELETE** request against */api/price-list-items/<uuid>/* to delete price list item. Only customer owner and staff can delete price items. """ return super(PriceListItemViewSet, self).destroy(request, *args, **kwargs)
To get a list of default price list items run ** GET ** against */ api/ default - price - list - items/ * as authenticated user.
def list(self, request, *args, **kwargs): """ To get a list of default price list items, run **GET** against */api/default-price-list-items/* as authenticated user. Price lists can be filtered by: - ?key=<string> - ?item_type=<string> has to be from list of available i...
To get a list of price list items run ** GET ** against */ api/ merged - price - list - items/ * as authenticated user.
def list(self, request, *args, **kwargs): """ To get a list of price list items, run **GET** against */api/merged-price-list-items/* as authenticated user. If service is not specified default price list items are displayed. Otherwise service specific price list items are display...
A remote notebook finder. Place a * into a url to generalize the finder. It returns a context manager
def Remote(path=None, loader=Notebook, **globals): """A remote notebook finder. Place a `*` into a url to generalize the finder. It returns a context manager """ class Remote(RemoteMixin, loader): ... return Remote(path=path, **globals)
Get permission checks that will be executed for current action.
def get_permission_checks(self, request, view): """ Get permission checks that will be executed for current action. """ if view.action is None: return [] # if permissions are defined for view directly - use them. if hasattr(view, view.action + '_permissions'):...
Registers the function to the server s default fixed function manager.
def add_function(self, function): """ Registers the function to the server's default fixed function manager. """ #noinspection PyTypeChecker if not len(self.settings.FUNCTION_MANAGERS): raise ConfigurationError( 'Where have the default function manager...
When ElasticSearch analyzes string it breaks it into parts. In order make query for not - analyzed exact string values we should use subfield instead.
def format_raw_field(key): """ When ElasticSearch analyzes string, it breaks it into parts. In order make query for not-analyzed exact string values, we should use subfield instead. The index template for Elasticsearch 5.0 has been changed. The subfield for string multi-fields has changed from .raw...
Creates a decorator function that applies the decorator_cls that was passed in.
def decorate(decorator_cls, *args, **kwargs): """Creates a decorator function that applies the decorator_cls that was passed in.""" global _wrappers wrapper_cls = _wrappers.get(decorator_cls, None) if wrapper_cls is None: class PythonWrapper(decorator_cls): pass wrapper_cl...
States that method is deprecated.
def deprecated(replacement_description): """States that method is deprecated. :param replacement_description: Describes what must be used instead. :return: the original method with modified docstring. """ def decorate(fn_or_class): if isinstance(fn_or_class, type): pass # Can...
Decorator that can convert the result of a function call.
def convert_result(converter): """Decorator that can convert the result of a function call.""" def decorate(fn): @inspection.wraps(fn) def new_fn(*args, **kwargs): return converter(fn(*args, **kwargs)) return new_fn return decorate
Decorator for retrying a function if it throws an exception.
def retry(exception_cls, max_tries=10, sleep=0.05): """Decorator for retrying a function if it throws an exception. :param exception_cls: an exception type or a parenthesized tuple of exception types :param max_tries: maximum number of times this function can be executed. Must be at least 1. :param sle...
Converts a context manager into a decorator.
def decorator_of_context_manager(ctxt): """Converts a context manager into a decorator. This decorator will run the decorated function in the context of the manager. :param ctxt: Context to run the function in. :return: Wrapper around the original function. """ def decorator_fn(*outer_ar...
A helper function gets standard information from the error.
def get_error(self, error): """ A helper function, gets standard information from the error. """ error_type = type(error) if error.error_type == ET_CLIENT: error_type_name = 'Client' else: error_type_name = 'Server' return { 'ty...
Get error messages about object and his ancestor quotas that will be exceeded if quota_delta will be added.
def validate_quota_change(self, quota_deltas, raise_exception=False): """ Get error messages about object and his ancestor quotas that will be exceeded if quota_delta will be added. raise_exception - if True QuotaExceededException will be raised if validation fails quota_deltas - dictio...
Return dictionary with sum of all scopes quotas.
def get_sum_of_quotas_as_dict(cls, scopes, quota_names=None, fields=['usage', 'limit']): """ Return dictionary with sum of all scopes' quotas. Dictionary format: { 'quota_name1': 'sum of limits for quotas with such quota_name1', 'quota_name1_usage': 'sum of usage...
To get a list of events - run ** GET ** against */ api/ events/ * as authenticated user. Note that a user can only see events connected to objects she is allowed to see.
def list(self, request, *args, **kwargs): """ To get a list of events - run **GET** against */api/events/* as authenticated user. Note that a user can only see events connected to objects she is allowed to see. Sorting is supported in ascending and descending order by specifying a field...
To get a count of events - run ** GET ** against */ api/ events/ count/ * as authenticated user. Endpoint support same filters as events list.
def count(self, request, *args, **kwargs): """ To get a count of events - run **GET** against */api/events/count/* as authenticated user. Endpoint support same filters as events list. Response example: .. code-block:: javascript {"count": 12321} """ ...
To get a historical data of events amount - run ** GET ** against */ api/ events/ count/ history/ *. Endpoint support same filters as events list. More about historical data - read at section * Historical data *.
def count_history(self, request, *args, **kwargs): """ To get a historical data of events amount - run **GET** against */api/events/count/history/*. Endpoint support same filters as events list. More about historical data - read at section *Historical data*. Response example: ...
Returns a list of scope types acceptable by events filter.
def scope_types(self, request, *args, **kwargs): """ Returns a list of scope types acceptable by events filter. """ return response.Response(utils.get_scope_types_mapping().keys())
To get a list of alerts run ** GET ** against */ api/ alerts/ * as authenticated user.
def list(self, request, *args, **kwargs): """ To get a list of alerts, run **GET** against */api/alerts/* as authenticated user. Alert severity field can take one of this values: "Error", "Warning", "Info", "Debug". Field scope will contain link to object that cause alert. Conte...
Run ** POST ** against */ api/ alerts/ * to create or update alert. If alert with posted scope and alert_type already exists - it will be updated. Only users with staff privileges can create alerts.
def create(self, request, *args, **kwargs): """ Run **POST** against */api/alerts/* to create or update alert. If alert with posted scope and alert_type already exists - it will be updated. Only users with staff privileges can create alerts. Request example: .. code-block:: jav...
To close alert - run ** POST ** against */ api/ alerts/ <alert_uuid >/ close/ *. No data is required. Only users with staff privileges can close alerts.
def close(self, request, *args, **kwargs): """ To close alert - run **POST** against */api/alerts/<alert_uuid>/close/*. No data is required. Only users with staff privileges can close alerts. """ if not request.user.is_staff: raise PermissionDenied() alert = s...
To acknowledge alert - run ** POST ** against */ api/ alerts/ <alert_uuid >/ acknowledge/ *. No payload is required. All users that can see alerts can also acknowledge it. If alert is already acknowledged endpoint will return error with code 409 ( conflict ).
def acknowledge(self, request, *args, **kwargs): """ To acknowledge alert - run **POST** against */api/alerts/<alert_uuid>/acknowledge/*. No payload is required. All users that can see alerts can also acknowledge it. If alert is already acknowledged endpoint will return error with code 4...
To get count of alerts per severities - run ** GET ** request against */ api/ alerts/ stats/ *. This endpoint supports all filters that are available for alerts list ( */ api/ alerts/ * ).
def stats(self, request, *args, **kwargs): """ To get count of alerts per severities - run **GET** request against */api/alerts/stats/*. This endpoint supports all filters that are available for alerts list (*/api/alerts/*). Response example: .. code-block:: javascript ...
To create new web hook issue ** POST ** against */ api/ hooks - web/ * as an authenticated user. You should specify list of event_types or event_groups.
def create(self, request, *args, **kwargs): """ To create new web hook issue **POST** against */api/hooks-web/* as an authenticated user. You should specify list of event_types or event_groups. Example of a request: .. code-block:: http POST /api/hooks-web/ HTTP/1....
To create new email hook issue ** POST ** against */ api/ hooks - email/ * as an authenticated user. You should specify list of event_types or event_groups.
def create(self, request, *args, **kwargs): """ To create new email hook issue **POST** against */api/hooks-email/* as an authenticated user. You should specify list of event_types or event_groups. Example of a request: .. code-block:: http POST /api/hooks-email/ H...
To create new push hook issue ** POST ** against */ api/ hooks - push/ * as an authenticated user. You should specify list of event_types or event_groups.
def create(self, request, *args, **kwargs): """ To create new push hook issue **POST** against */api/hooks-push/* as an authenticated user. You should specify list of event_types or event_groups. Example of a request: .. code-block:: http POST /api/hooks-push/ HTTP...
Import this instrument s settings from the given file. Will automatically add the instrument s synth and table to the song s synths and tables if needed.
def import_from_file(self, index, filename): """Import this instrument's settings from the given file. Will automatically add the instrument's synth and table to the song's synths and tables if needed. Note that this may invalidate existing instrument accessor objects. :param i...
Load a Project from a. lsdsng file.
def load_lsdsng(filename): """Load a Project from a ``.lsdsng`` file. :param filename: the name of the file from which to load :rtype: :py:class:`pylsdj.Project` """ # Load preamble data so that we know the name and version of the song with open(filename, 'rb') as fp: preamble_data = b...
Load a Project from an. srm file.
def load_srm(filename): """Load a Project from an ``.srm`` file. :param filename: the name of the file from which to load :rtype: :py:class:`pylsdj.Project` """ # .srm files are just decompressed projects without headers # In order to determine the file's size in compressed blocks, we have to...
the song associated with the project
def song(self): """the song associated with the project""" if self._song is None: self._song = Song(self._song_data) return self._song
Save a project in. lsdsng format to the target file.
def save(self, filename): """Save a project in .lsdsng format to the target file. :param filename: the name of the file to which to save :deprecated: use ``save_lsdsng(filename)`` instead """ with open(filename, 'wb') as fp: writer = BlockWriter() factor...
Save a project in. srm format to the target file.
def save_srm(self, filename): """Save a project in .srm format to the target file. :param filename: the name of the file to which to save """ with open(filename, 'wb') as fp: raw_data = bread.write(self._song_data, spec.song) fp.write(raw_data)
compresses the waveform horizontally ; one of normal resync resync2
def phase_type(self, value): '''compresses the waveform horizontally; one of ``"normal"``, ``"resync"``, ``"resync2"``''' self._params.phase_type = value self._overwrite_lock.disable()
The list of: py: class: pylsdj. Project s that the. sav file contains
def project_list(self): """The list of :py:class:`pylsdj.Project` s that the .sav file contains""" return [(i, self.projects[i]) for i in sorted(self.projects.keys())]
Save this file.
def save(self, filename, callback=_noop_callback): """Save this file. :param filename: the file to which to save the .sav file :type filename: str :param callback: a progress callback function :type callback: function """ with open(filename, 'wb') as fp: ...
Splits compressed data into blocks.
def split(compressed_data, segment_size, block_factory): """Splits compressed data into blocks. :param compressed_data: the compressed data to split :param segment_size: the size of a block in bytes :param block_factory: a BlockFactory used to construct the blocks :rtype: a list of block IDs of bl...
Renumber a block map s indices so that tehy match the blocks block switch statements.
def renumber_block_keys(blocks): """Renumber a block map's indices so that tehy match the blocks' block switch statements. :param blocks a block map to renumber :rtype: a renumbered copy of the block map """ # There is an implicit block switch to the 0th block at the start of the # file ...
Merge the given blocks into a contiguous block of compressed data.
def merge(blocks): """Merge the given blocks into a contiguous block of compressed data. :param blocks: the list of blocks :rtype: a list of compressed bytes """ current_block = blocks[sorted(blocks.keys())[0]] compressed_data = [] eof = False while not eof: data_size_to_appe...
Add zeroes to a segment until it reaches a certain size.
def pad(segment, size): """Add zeroes to a segment until it reaches a certain size. :param segment: the segment to pad :param size: the size to which to pad the segment """ for i in range(size - len(segment)): segment.append(0) assert len(segment) == size
Decompress data that has been compressed by the filepack algorithm.
def decompress(compressed_data): """Decompress data that has been compressed by the filepack algorithm. :param compressed_data: an array of compressed data bytes to decompress :rtype: an array of decompressed bytes""" raw_data = [] index = 0 while index < len(compressed_data): curren...
Compress raw bytes with the filepack algorithm.
def compress(raw_data): """Compress raw bytes with the filepack algorithm. :param raw_data: an array of raw data bytes to compress :rtype: a list of compressed bytes """ raw_data = bytearray(raw_data) compressed_data = [] data_size = len(raw_data) index = 0 next_bytes = [-1, -1, ...
Return a human - readable name without LSDJ s trailing zeroes.
def name_without_zeroes(name): """ Return a human-readable name without LSDJ's trailing zeroes. :param name: the name from which to strip zeroes :rtype: the name, without trailing zeroes """ first_zero = name.find(b'\0') if first_zero == -1: return name else: return str...
the instrument s name ( 5 characters zero - padded )
def name(self): """the instrument's name (5 characters, zero-padded)""" instr_name = self.song.song_data.instrument_names[self.index] if type(instr_name) == bytes: instr_name = instr_name.decode('utf-8') return instr_name