Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def print_float(self, value, decimal_digits=2, justify_right=True): format_string = '{{0:0.{0}F}}'.format(decimal_digits) self.print_number_str(format_string.format(value), justify_right)
[ "Print a numeric value to the display. If value is negative\n it will be printed with a leading minus sign. Decimal digits is the\n desired number of digits after the decimal point.\n " ]
Please provide a description of the function:def print_hex(self, value, justify_right=True): if value < 0 or value > 0xFFFF: # Ignore out of range values. return self.print_str('{0:X}'.format(value), justify_right)
[ "Print a numeric value in hexadecimal. Value should be from 0 to FFFF.\n " ]
Please provide a description of the function:def set_digit_raw(self, pos, bitmask): if pos < 0 or pos > 3: # Ignore out of bounds digits. return # Jump past the colon at position 2 by adding a conditional offset. offset = 0 if pos < 2 else 1 # Calculate ...
[ "Set digit at position to raw bitmask value. Position should be a value\n of 0 to 3 with 0 being the left most digit on the display." ]
Please provide a description of the function:def set_decimal(self, pos, decimal): if pos < 0 or pos > 3: # Ignore out of bounds digits. return # Jump past the colon at position 2 by adding a conditional offset. offset = 0 if pos < 2 else 1 # Calculate th...
[ "Turn decimal point on or off at provided position. Position should be\n a value 0 to 3 with 0 being the left most digit on the display. Decimal\n should be True to turn on the decimal point and False to turn it off.\n " ]
Please provide a description of the function:def set_digit(self, pos, digit, decimal=False): if self.invert: self.set_digit_raw(pos, IDIGIT_VALUES.get(str(digit).upper(), 0x00)) else: self.set_digit_raw(pos, DIGIT_VALUES.get(str(digit).upper(), 0x00)) if decimal...
[ "Set digit at position to provided value. Position should be a value\n of 0 to 3 with 0 being the left most digit on the display. Digit should\n be a number 0-9, character A-F, space (all LEDs off), or dash (-).\n " ]
Please provide a description of the function:def set_left_colon(self, show_colon): if show_colon: self.buffer[4] |= 0x04 self.buffer[4] |= 0x08 else: self.buffer[4] &= (~0x04) & 0xFF self.buffer[4] &= (~0x08) & 0xFF
[ "Turn the left colon on with show color True, or off with show colon\n False. Only the large 1.2\" 7-segment display has a left colon.\n " ]
Please provide a description of the function:def print_number_str(self, value, justify_right=True): # Calculate length of value without decimals. length = sum(map(lambda x: 1 if x != '.' else 0, value)) # Error if value without decimals is longer than 4 characters. if length > 4...
[ "Print a 4 character long string of numeric values to the display.\n Characters in the string should be any supported character by set_digit,\n or a decimal point. Decimal point characters will be associated with\n the previous character.\n " ]
Please provide a description of the function:def print_hex(self, value, justify_right=True): if value < 0 or value > 0xFFFF: # Ignore out of range values. return self.print_number_str('{0:X}'.format(value), justify_right)
[ "Print a numeric value in hexadecimal. Value should be from 0 to FFFF.\n " ]
Please provide a description of the function:def begin(self): # Turn on the oscillator. self._device.writeList(HT16K33_SYSTEM_SETUP | HT16K33_OSCILLATOR, []) # Turn display on with no blinking. self.set_blink(HT16K33_BLINK_OFF) # Set display to full brightness. s...
[ "Initialize driver with LEDs enabled and all turned off." ]
Please provide a description of the function:def set_blink(self, frequency): if frequency not in [HT16K33_BLINK_OFF, HT16K33_BLINK_2HZ, HT16K33_BLINK_1HZ, HT16K33_BLINK_HALFHZ]: raise ValueError('Frequency must be one of HT16K33_BLINK_OFF, HT16K33_BLINK_2HZ, HT1...
[ "Blink display at specified frequency. Note that frequency must be a\n value allowed by the HT16K33, specifically one of: HT16K33_BLINK_OFF,\n HT16K33_BLINK_2HZ, HT16K33_BLINK_1HZ, or HT16K33_BLINK_HALFHZ.\n " ]
Please provide a description of the function:def set_brightness(self, brightness): if brightness < 0 or brightness > 15: raise ValueError('Brightness must be a value of 0 to 15.') self._device.writeList(HT16K33_CMD_BRIGHTNESS | brightness, [])
[ "Set brightness of entire display to specified value (16 levels, from\n 0 to 15).\n " ]
Please provide a description of the function:def set_led(self, led, value): if led < 0 or led > 127: raise ValueError('LED must be value of 0 to 127.') # Calculate position in byte buffer and bit offset of desired LED. pos = led // 8 offset = led % 8 if not v...
[ "Sets specified LED (value of 0 to 127) to the specified value, 0/False\n for off and 1 (or any True/non-zero value) for on.\n " ]
Please provide a description of the function:def write_display(self): for i, value in enumerate(self.buffer): self._device.write8(i, value)
[ "Write display buffer to display hardware." ]
Please provide a description of the function:def clear(self): for i, value in enumerate(self.buffer): self.buffer[i] = 0
[ "Clear contents of display buffer." ]
Please provide a description of the function:def get_readonly_fields(self, request, obj=None): if obj: return list(self.readonly_fields) + ['id', 'identity', 'is_current'] return self.readonly_fields
[ "\n This is required a subclass of VersionedAdmin has readonly_fields\n ours won't be undone\n " ]
Please provide a description of the function:def get_list_display(self, request): # Force cast to list as super get_list_display could return a tuple list_display = list( super(VersionedAdmin, self).get_list_display(request)) # Preprend the following fields to list display...
[ "\n This method determines which fields go in the changelist\n " ]
Please provide a description of the function:def get_list_filter(self, request): list_filter = super(VersionedAdmin, self).get_list_filter(request) return list(list_filter) + [('version_start_date', DateTimeFilter), IsCurrentFilter]
[ "\n Adds versionable custom filtering ability to changelist\n " ]
Please provide a description of the function:def restore(self, request, *args, **kwargs): paths = request.path_info.split('/') object_id_index = paths.index("restore") - 2 object_id = paths[object_id_index] obj = super(VersionedAdmin, self).get_object(request, object_id) ...
[ "\n View for restoring object from change view\n " ]
Please provide a description of the function:def will_not_clone(self, request, *args, **kwargs): paths = request.path_info.split('/') index_of_object_id = paths.index("will_not_clone") - 1 object_id = paths[index_of_object_id] self.change_view(request, object_id) admin_...
[ "\n Add save but not clone capability in the changeview\n " ]
Please provide a description of the function:def exclude(self): exclude = self.VERSIONED_EXCLUDE if super(VersionedAdmin, self).exclude is not None: # Force cast to list as super exclude could return a tuple exclude = list(super(VersionedAdmin, self).exclude) + exclude ...
[ "\n Custom descriptor for exclude since there is no get_exclude method to\n be overridden\n " ]
Please provide a description of the function:def get_object(self, request, object_id, from_field=None): # from_field breaks in 1.7.8 obj = super(VersionedAdmin, self).get_object(request, object_id) # Only clone if update view as get_o...
[ "\n our implementation of get_object allows for cloning when updating an\n object, not cloning when the button 'save but not clone' is pushed\n and at no other time will clone be called\n " ]
Please provide a description of the function:def history_view(self, request, object_id, extra_context=None): "The 'history' admin view for this model." from django.contrib.admin.models import LogEntry # First check if the user can see this history. model = self.model obj = get_ob...
[]
Please provide a description of the function:def get_urls(self): not_clone_url = [url(r'^(.+)/will_not_clone/$', admin.site.admin_view(self.will_not_clone))] restore_url = [ url(r'^(.+)/restore/$', admin.site.admin_view(self.restore))] return not...
[ "\n Appends the custom will_not_clone url to the admin site\n " ]
Please provide a description of the function:def remove_uuid_id_like_indexes(app_name, database=None): removed_indexes = 0 with database_connection(database).cursor() as cursor: for model in versionable_models(app_name, include_auto_created=True): indexes = select_uuid_like_indexes_on_...
[ "\n Remove all of varchar_pattern_ops indexes that django created for uuid\n columns.\n A search is never done with a filter of the style (uuid__like='1ae3c%'), so\n all such indexes can be removed from Versionable models.\n This will only try to remove indexes if they exist in the database, so it\n ...
Please provide a description of the function:def get_uuid_like_indexes_on_table(model): with default_connection.cursor() as c: indexes = select_uuid_like_indexes_on_table(model, c) return indexes
[ "\n Gets a list of database index names for the given model for the\n uuid-containing fields that have had a like-index created on them.\n\n :param model: Django model\n :return: list of database rows; the first field of each row is an index\n name\n " ]
Please provide a description of the function:def select_uuid_like_indexes_on_table(model, cursor): # VersionedForeignKey fields as well as the id fields have these useless # like indexes field_names = ["'%s'" % f.column for f in model._meta.fields if isinstance(f, VersionedForeignKe...
[ "\n Gets a list of database index names for the given model for the\n uuid-containing fields that have had a like-index created on them.\n\n :param model: Django model\n :param cursor: database connection cursor\n :return: list of database rows; the first field of each row is an index\n name\n...
Please provide a description of the function:def create_current_version_unique_indexes(app_name, database=None): indexes_created = 0 connection = database_connection(database) with connection.cursor() as cursor: for model in versionable_models(app_name): unique_field_groups = getat...
[ "\n Add unique indexes for models which have a VERSION_UNIQUE attribute.\n These must be defined as partially unique indexes, which django\n does not support.\n The unique indexes are defined so that no two *current* versions can have\n the same value.\n This will only try to create indexes if the...
Please provide a description of the function:def create_current_version_unique_identity_indexes(app_name, database=None): indexes_created = 0 connection = database_connection(database) with connection.cursor() as cursor: for model in versionable_models(app_name): if getattr(model._...
[ "\n Add partial unique indexes for the the identity column of versionable\n models.\n\n This enforces that no two *current* versions can have the same identity.\n\n This will only try to create indexes if they do not exist in the database,\n so it should be safe to run in a post_migrate signal handle...
Please provide a description of the function:def get_queryset(self): qs = VersionedQuerySet(self.model, using=self._db) if hasattr(self, 'instance') and hasattr(self.instance, '_querytime'): qs.querytime = self.instance._querytime return qs
[ "\n Returns a VersionedQuerySet capable of handling version time\n restrictions.\n\n :return: VersionedQuerySet\n " ]
Please provide a description of the function:def next_version(self, object, relations_as_of='end'): if object.version_end_date is None: next = object else: next = self.filter( Q(identity=object.identity), Q(version_start_date__gte=object.v...
[ "\n Return the next version of the given object.\n\n In case there is no next object existing, meaning the given\n object is the current version, the function returns this version.\n\n Note that if object's version_end_date is None, this does not check\n the database to see if the...
Please provide a description of the function:def previous_version(self, object, relations_as_of='end'): if object.version_birth_date == object.version_start_date: previous = object else: previous = self.filter( Q(identity=object.identity), ...
[ "\n Return the previous version of the given object.\n\n In case there is no previous object existing, meaning the given object\n is the first version of the object, then the function returns this\n version.\n\n ``relations_as_of`` is used to fix the point in time for the version;...
Please provide a description of the function:def current_version(self, object, relations_as_of=None, check_db=False): if object.version_end_date is None and not check_db: current = object else: current = self.current.filter(identity=object.identity).first() retu...
[ "\n Return the current version of the given object.\n\n The current version is the one having its version_end_date set to NULL.\n If there is not such a version then it means the object has been\n 'deleted' and so there is no current version available. In this case\n the function ...
Please provide a description of the function:def adjust_version_as_of(version, relations_as_of): if not version: return version if relations_as_of == 'end': if version.is_current: # Ensure that version._querytime is active, in case it wasn't ...
[ "\n Adjusts the passed version's as_of time to an appropriate value, and\n returns it.\n\n ``relations_as_of`` is used to fix the point in time for the version;\n this affects which related objects are returned when querying for\n object relations.\n Valid ``relations_as_of...
Please provide a description of the function:def _create_at(self, timestamp=None, id=None, forced_identity=None, **kwargs): id = Versionable.uuid(id) if forced_identity: ident = Versionable.uuid(forced_identity) else: ident = id if tim...
[ "\n WARNING: Only for internal use and testing.\n\n Create a Versionable having a version_start_date and\n version_birth_date set to some pre-defined timestamp\n\n :param timestamp: point in time at which the instance has to be created\n :param id: version 4 UUID unicode object. ...
Please provide a description of the function:def as_sql(self, qn, connection): # self.children is an array of VersionedExtraWhere-objects from versions.fields import VersionedExtraWhere for child in self.children: if isinstance(child, VersionedExtraWhere) and not child.param...
[ "\n This method identifies joined table aliases in order for\n VersionedExtraWhere.as_sql() to be able to add time restrictions for\n those tables based on the VersionedQuery's querytime value.\n\n :param qn: In Django 1.7 & 1.8 this is a compiler\n :param connection: A DB connect...
Please provide a description of the function:def _set_child_joined_alias(child, alias_map): for table in alias_map: join = alias_map[table] if not isinstance(join, Join): continue lhs = join.parent_alias if (lhs == child.alias and table ==...
[ "\n Set the joined alias on the child, for Django >= 1.8.0\n :param child:\n :param alias_map:\n " ]
Please provide a description of the function:def get_compiler(self, *args, **kwargs): if self.querytime.active and \ (not hasattr(self, '_querytime_filter_added') or not self._querytime_filter_added): time = self.querytime.time if time is None...
[ "\n Add the query time restriction limit at the last moment. Applying it\n earlier (e.g. by adding a filter to the queryset) does not allow the\n caching of related object to work (they are attached to a queryset;\n filter() returns a new queryset).\n " ]
Please provide a description of the function:def build_filter(self, filter_expr, **kwargs): lookup, value = filter_expr if self.querytime.active \ and isinstance(value, Versionable) and not value.is_latest: new_lookup = \ lookup + LOOKUP_SEP + Version...
[ "\n When a query is filtered with an expression like\n .filter(team=some_team_object), where team is a VersionedForeignKey\n field, and some_team_object is a Versionable object, adapt the filter\n value to be (team__identity=some_team_object.identity).\n\n When the query is built,...
Please provide a description of the function:def querytime(self, value): self._querytime = value self.query.querytime = value
[ "\n Sets self._querytime as well as self.query.querytime.\n :param value: None or datetime\n :return:\n " ]
Please provide a description of the function:def _fetch_all(self): if self._result_cache is None: self._result_cache = list(self.iterator()) # TODO: Do we have to test for ValuesListIterable, ValuesIterable, # and FlatValuesListIterable here? if self._ite...
[ "\n Completely overrides the QuerySet._fetch_all method by adding the\n timestamp to all objects\n\n :return: See django.db.models.query.QuerySet._fetch_all for return\n values\n " ]
Please provide a description of the function:def _clone(self, *args, **kwargs): clone = super(VersionedQuerySet, self)._clone(**kwargs) clone.querytime = self.querytime return clone
[ "\n Overrides the QuerySet._clone method by adding the cloning of the\n VersionedQuerySet's query_time parameter\n\n :param kwargs: Same as the original QuerySet._clone params\n :return: Just as QuerySet._clone, this method returns a clone of the\n original object\n " ]
Please provide a description of the function:def _set_item_querytime(self, item, type_check=True): if isinstance(item, Versionable): item._querytime = self.querytime elif isinstance(item, VersionedQuerySet): item.querytime = self.querytime else: if ty...
[ "\n Sets the time for which the query was made on the resulting item\n\n :param item: an item of type Versionable\n :param type_check: Check the item to be a Versionable\n :return: Returns the item itself with the time set\n " ]
Please provide a description of the function:def as_of(self, qtime=None): clone = self._clone() clone.querytime = QueryTime(time=qtime, active=True) return clone
[ "\n Sets the time for which we want to retrieve an object.\n\n :param qtime: The UTC date and time; if None then use the current\n state (where version_end_date = NULL)\n :return: A VersionedQuerySet\n " ]
Please provide a description of the function:def delete(self): assert self.query.can_filter(), \ "Cannot use 'limit' or 'offset' with delete." # Ensure that only current objects are selected. del_query = self.filter(version_end_date__isnull=True) # The delete is ac...
[ "\n Deletes the records in the QuerySet.\n " ]
Please provide a description of the function:def _delete_at(self, timestamp, using=None): if self.version_end_date is None: self.version_end_date = timestamp self.save(force_update=True, using=using) else: raise DeletionOfNonCurrentVersionError( ...
[ "\n WARNING: This method is only for internal use, it should not be used\n from outside.\n\n It is used only in the case when you want to make sure a group of\n related objects are deleted at the exact same time.\n\n It is certainly not meant to be used for deleting an object and ...
Please provide a description of the function:def uuid(uuid_value=None): if uuid_value: if not validate_uuid(uuid_value): raise ValueError( "uuid_value must be a valid UUID version 4 object") else: uuid_value = uuid.uuid4() if ...
[ "\n Returns a uuid value that is valid to use for id and identity fields.\n\n :return: unicode uuid object if using UUIDFields, uuid unicode string\n otherwise.\n " ]
Please provide a description of the function:def clone(self, forced_version_date=None, in_bulk=False): if not self.pk: raise ValueError('Instance must be saved before it can be cloned') if self.version_end_date: raise ValueError( 'This is a historical it...
[ "\n Clones a Versionable and returns a fresh copy of the original object.\n Original source: ClonableMixin snippet\n (http://djangosnippets.org/snippets/1271), with the pk/id change\n suggested in the comments\n\n :param forced_version_date: a timestamp including tzinfo; this valu...
Please provide a description of the function:def at(self, timestamp): # Ensure, it's not a historic item if not self.is_current: raise SuspiciousOperation( "Cannot relocate this Versionable instance in time, since it " "is a historical item") ...
[ "\n Force the create date of an object to be at a certain time; This\n method can be invoked only on a freshly created Versionable object.\n It must not have been cloned yet. Raises a SuspiciousOperation\n exception, otherwise.\n :param timestamp: a datetime.datetime instance\n ...
Please provide a description of the function:def restore(self, **kwargs): if not self.pk: raise ValueError( 'Instance must be saved and terminated before it can be ' 'restored.') if self.is_current: raise ValueError( 'This...
[ "\n Restores this version as a new version, and returns this new version.\n\n If a current version already exists, it will be terminated before\n restoring this version.\n\n Relations (foreign key, reverse foreign key, many-to-many) are not\n restored with the old version. If pro...
Please provide a description of the function:def detach(self): self.id = self.identity = self.uuid() self.version_start_date = self.version_birth_date = get_utc_now() self.version_end_date = None return self
[ "\n Detaches the instance from its history.\n\n Similar to creating a new object with the same field values. The id and\n identity fields are set to a new value. The returned object has not\n been saved, call save() afterwards when you are ready to persist the\n object.\n\n ...
Please provide a description of the function:def matches_querytime(instance, querytime): if not querytime.active: return True if not querytime.time: return instance.version_end_date is None return (instance.version_start_date <= querytime.time and ...
[ "\n Checks whether the given instance satisfies the given QueryTime object.\n\n :param instance: an instance of Versionable\n :param querytime: QueryTime value to check against\n " ]
Please provide a description of the function:def contribute_to_related_class(self, cls, related): # Internal FK's - i.e., those with a related name ending with '+' - # and swapped models don't get a related descriptor. super(VersionedForeignKey, self).contribute_to_related_class(cls, ...
[ "\n Override ForeignKey's methods, and replace the descriptor, if set by\n the parent's methods\n " ]
Please provide a description of the function:def get_extra_restriction(self, where_class, alias, remote_alias): historic_sql = '''{alias}.version_start_date <= %s AND ({alias}.version_end_date > %s OR {alias}.version_end_date is NULL )''' ...
[ "\n Overrides ForeignObject's get_extra_restriction function that returns\n an SQL statement which is appended to a JOIN's conditional filtering\n part\n\n :return: SQL conditional statement\n :rtype: WhereNode\n " ]
Please provide a description of the function:def get_joining_columns(self, reverse_join=False): source = self.reverse_related_fields if reverse_join \ else self.related_fields joining_columns = tuple() for lhs_field, rhs_field in source: lhs_col_name = lhs_field....
[ "\n Get and return joining columns defined by this foreign key relationship\n\n :return: A tuple containing the column names of the tables to be\n joined (<local_col_name>, <remote_col_name>)\n :rtype: tuple\n " ]
Please provide a description of the function:def contribute_to_class(self, cls, name, **kwargs): # TODO: Apply 3 edge cases when not to create an intermediary model # specified in django.db.models.fields.related:1566 # self.rel.through needs to be set prior to calling super, since ...
[ "\n Called at class type creation. So, this method is called, when\n metaclasses get created\n " ]
Please provide a description of the function:def contribute_to_related_class(self, cls, related): super(VersionedManyToManyField, self). \ contribute_to_related_class(cls, related) accessor_name = related.get_accessor_name() if accessor_name and hasattr(cls, accessor_name): ...
[ "\n Called at class type creation. So, this method is called, when\n metaclasses get created\n " ]
Please provide a description of the function:def _set_child_joined_alias_using_join_map(child, join_map, alias_map): for lhs, table, join_cols in join_map: if lhs is None: continue if lhs == child.alias: relevant_alias = child.related_alias ...
[ "\n Set the joined alias on the child, for Django <= 1.7.x.\n :param child:\n :param join_map:\n :param alias_map:\n " ]
Please provide a description of the function:def get_versioned_delete_collector_class(): key = 'VERSIONED_DELETE_COLLECTOR' try: cls = _cache[key] except KeyError: collector_class_string = getattr(settings, key) cls = import_from_string(collector_class_string, key) _cach...
[ "\n Gets the class to use for deletion collection.\n\n :return: class\n " ]
Please provide a description of the function:def related_objects(self, related, objs): from versions.models import Versionable related_model = related.related_model if issubclass(related_model, Versionable): qs = related_model.objects.current else: qs = ...
[ "\n Gets a QuerySet of current objects related to ``objs`` via the\n relation ``related``.\n " ]
Please provide a description of the function:def versionable_delete(self, instance, timestamp): instance._delete_at(timestamp, using=self.using)
[ "\n Soft-deletes the instance, setting it's version_end_date to timestamp.\n\n Override this method to implement custom behaviour.\n\n :param Versionable instance:\n :param datetime timestamp:\n " ]
Please provide a description of the function:def get_prefetch_queryset(self, instances, queryset=None): if queryset is None: queryset = self.get_queryset() queryset._add_hints(instance=instances[0]) # CleanerVersion change 1: force the querytime to be the same as the ...
[ "\n Overrides the parent method to:\n - force queryset to use the querytime of the parent objects\n - ensure that the join is done on identity, not id\n - make the cache key identity, not id.\n " ]
Please provide a description of the function:def get_current_m2m_diff(self, instance, new_objects): new_ids = self.pks_from_objects(new_objects) relation_manager = self.__get__(instance) filter = Q(**{relation_manager.source_field.attname: instance.pk}) qs = self.through.object...
[ "\n :param instance: Versionable object\n :param new_objects: objects which are about to be associated with\n instance\n :return: (being_removed id list, being_added id list)\n :rtype : tuple\n " ]
Please provide a description of the function:def pks_from_objects(self, objects): return {o.pk if isinstance(o, Model) else o for o in objects}
[ "\n Extract all the primary key strings from the given objects.\n Objects may be Versionables, or bare primary keys.\n\n :rtype : set\n " ]
Please provide a description of the function:def fit(self, vecs, iter=20, seed=123): assert vecs.dtype == np.float32 assert vecs.ndim == 2 N, D = vecs.shape assert self.Ks < N, "the number of training vector should be more than Ks" assert D % self.M == 0, "input dimensio...
[ "Given training vectors, run k-means for each sub-space and create\n codewords for each sub-space.\n\n This function should be run once first of all.\n\n Args:\n vecs (np.ndarray): Training vectors with shape=(N, D) and dtype=np.float32.\n iter (int): The number of iterati...
Please provide a description of the function:def encode(self, vecs): assert vecs.dtype == np.float32 assert vecs.ndim == 2 N, D = vecs.shape assert D == self.Ds * self.M, "input dimension must be Ds * M" # codes[n][m] : code of n-th vec, m-th subspace codes = np...
[ "Encode input vectors into PQ-codes.\n\n Args:\n vecs (np.ndarray): Input vectors with shape=(N, D) and dtype=np.float32.\n\n Returns:\n np.ndarray: PQ codes with shape=(N, M) and dtype=self.code_dtype\n\n " ]
Please provide a description of the function:def decode(self, codes): assert codes.ndim == 2 N, M = codes.shape assert M == self.M assert codes.dtype == self.code_dtype vecs = np.empty((N, self.Ds * self.M), dtype=np.float32) for m in range(self.M): ...
[ "Given PQ-codes, reconstruct original D-dimensional vectors\n approximately by fetching the codewords.\n\n Args:\n codes (np.ndarray): PQ-cdoes with shape=(N, M) and dtype=self.code_dtype.\n Each row is a PQ-code\n\n Returns:\n np.ndarray: Reconstructed vect...
Please provide a description of the function:def dtable(self, query): assert query.dtype == np.float32 assert query.ndim == 1, "input must be a single vector" D, = query.shape assert D == self.Ds * self.M, "input dimension must be Ds * M" # dtable[m] : distance between ...
[ "Compute a distance table for a query vector.\n The distances are computed by comparing each sub-vector of the query\n to the codewords for each sub-subspace.\n `dtable[m][ks]` contains the squared Euclidean distance between\n the `m`-th sub-vector of the query and the `ks`-th codeword\n...
Please provide a description of the function:def adist(self, codes): assert codes.ndim == 2 N, M = codes.shape assert M == self.dtable.shape[0] # Fetch distance values using codes. The following codes are dists = np.sum(self.dtable[range(M), codes], axis=1) # ...
[ "Given PQ-codes, compute Asymmetric Distances between the query (self.dtable)\n and the PQ-codes.\n\n Args:\n codes (np.ndarray): PQ codes with shape=(N, M) and\n dtype=pq.code_dtype where pq is a pq instance that creates the codes\n\n Returns:\n np.ndarray:...
Please provide a description of the function:def fit(self, vecs, pq_iter=20, rotation_iter=10, seed=123): assert vecs.dtype == np.float32 assert vecs.ndim == 2 _, D = vecs.shape self.R = np.eye(D, dtype=np.float32) for i in range(rotation_iter): print("OPQ r...
[ "Given training vectors, this function alternatively trains\n (a) codewords and (b) a rotation matrix.\n The procedure of training codewords is same as :func:`PQ.fit`.\n The rotation matrix is computed so as to minimize the quantization error\n given codewords (Orthogonal Procrustes prob...
Please provide a description of the function:def rotate(self, vecs): assert vecs.dtype == np.float32 assert vecs.ndim in [1, 2] if vecs.ndim == 2: return vecs @ self.R elif vecs.ndim == 1: return (vecs.reshape(1, -1) @ self.R).reshape(-1)
[ "Rotate input vector(s) by the rotation matrix.`\n\n Args:\n vecs (np.ndarray): Input vector(s) with dtype=np.float32.\n The shape can be a single vector (D, ) or several vectors (N, D)\n\n Returns:\n np.ndarray: Rotated vectors with the same shape and dtype to the...
Please provide a description of the function:def decode(self, codes): # Because R is a rotation matrix (R^t * R = I), R^-1 should be R^t return self.pq.decode(codes) @ self.R.T
[ "Given PQ-codes, reconstruct original D-dimensional vectors via :func:`PQ.decode`,\n and applying an inverse-rotation.\n\n Args:\n codes (np.ndarray): PQ-cdoes with shape=(N, M) and dtype=self.code_dtype.\n Each row is a PQ-code\n\n Returns:\n np.ndarray: Re...
Please provide a description of the function:def transaction(): client = default_client() _thread.client = client.pipeline() try: yield _thread.client.execute() finally: _thread.client = client
[ "\n Swaps out the current client with a pipeline instance,\n so that each Redis method call inside the context will be\n pipelined. Once the context is exited, we execute the pipeline.\n " ]
Please provide a description of the function:def _get_lua_path(self, name): parts = (os.path.dirname(os.path.abspath(__file__)), "lua", name) return os.path.join(*parts)
[ "\n Joins the given name with the relative path of the module.\n " ]
Please provide a description of the function:def _get_lua_funcs(self): with open(self._get_lua_path("atoms.lua")) as f: for func in f.read().strip().split("function "): if func: bits = func.split("\n", 1) name = bits[0].split("(")[0].s...
[ "\n Returns the name / code snippet pair for each Lua function\n in the atoms.lua file.\n " ]
Please provide a description of the function:def _create_lua_method(self, name, code): script = self.register_script(code) setattr(script, "name", name) # Helps debugging redis lib. method = lambda key, *a, **k: script(keys=[key], args=a, **k) setattr(self, name, method)
[ "\n Registers the code snippet as a Lua script, and binds the\n script to the client as a method that can be called with\n the same signature as regular client methods, eg with a\n single key arg.\n " ]
Please provide a description of the function:def value_left(self, other): return other.value if isinstance(other, self.__class__) else other
[ "\n Returns the value of the other type instance to use in an\n operator method, namely when the method's instance is on the\n left side of the expression.\n " ]
Please provide a description of the function:def value_right(self, other): return self if isinstance(other, self.__class__) else self.value
[ "\n Returns the value of the type instance calling an to use in an\n operator method, namely when the method's instance is on the\n right side of the expression.\n " ]
Please provide a description of the function:def op_left(op): def method(self, other): return op(self.value, value_left(self, other)) return method
[ "\n Returns a type instance method for the given operator, applied\n when the instance appears on the left side of the expression.\n " ]
Please provide a description of the function:def op_right(op): def method(self, other): return op(value_left(self, other), value_right(self, other)) return method
[ "\n Returns a type instance method for the given operator, applied\n when the instance appears on the right side of the expression.\n " ]
Please provide a description of the function:def inplace(method_name): def method(self, other): getattr(self, method_name)(value_left(self, other)) return self return method
[ "\n Returns a type instance method that will call the given method\n name, used for inplace operators such as __iadd__ and __imul__.\n " ]
Please provide a description of the function:def on(self, event, f=None): def _on(f): self._add_event_handler(event, f, f) return f if f is None: return _on else: return _on(f)
[ "Registers the function ``f`` to the event name ``event``.\n\n If ``f`` isn't provided, this method returns a function that\n takes ``f`` as a callback; in other words, you can use this method\n as a decorator, like so::\n\n @ee.on('data')\n def data_handler(data):\n ...
Please provide a description of the function:def emit(self, event, *args, **kwargs): handled = False for f in list(self._events[event].values()): self._emit_run(f, args, kwargs) handled = True if not handled: self._emit_handle_potential_error(event,...
[ "Emit ``event``, passing ``*args`` and ``**kwargs`` to each attached\n function. Returns ``True`` if any functions are attached to ``event``;\n otherwise returns ``False``.\n\n Example::\n\n ee.emit('data', '00101001')\n\n Assuming ``data`` is an attached function, this will c...
Please provide a description of the function:def once(self, event, f=None): def _wrapper(f): def g(*args, **kwargs): self.remove_listener(event, f) # f may return a coroutine, so we need to return that # result here so that emit can schedule i...
[ "The same as ``ee.on``, except that the listener is automatically\n removed after being called.\n " ]
Please provide a description of the function:def remove_all_listeners(self, event=None): if event is not None: self._events[event] = OrderedDict() else: self._events = defaultdict(OrderedDict)
[ "Remove all listeners attached to ``event``.\n If ``event`` is ``None``, remove all listeners on all events.\n " ]
Please provide a description of the function:def offsetcopy(s, newoffset): assert 0 <= newoffset < 8 if not s.bitlength: return copy.copy(s) else: if newoffset == s.offset % 8: return ByteStore(s.getbyteslice(s.byteoffset, s.byteoffset + s.bytelength), s.bitlength, newoffset...
[ "Return a copy of a ByteStore with the newoffset.\n\n Not part of public interface.\n " ]
Please provide a description of the function:def equal(a, b): # We want to return False for inequality as soon as possible, which # means we get lots of special cases. # First the easy one - compare lengths: a_bitlength = a.bitlength b_bitlength = b.bitlength if a_bitlength != b_bitlength: ...
[ "Return True if ByteStores a == b.\n\n Not part of public interface.\n " ]
Please provide a description of the function:def structparser(token): m = STRUCT_PACK_RE.match(token) if not m: return [token] else: endian = m.group('endian') if endian is None: return [token] # Split the format string into a list of 'q', '4h' etc. f...
[ "Parse struct-like format string token into sub-token list." ]
Please provide a description of the function:def tokenparser(fmt, keys=None, token_cache={}): try: return token_cache[(fmt, keys)] except KeyError: token_key = (fmt, keys) # Very inefficient expanding of brackets. fmt = expand_brackets(fmt) # Split tokens by ',' and remove white...
[ "Divide the format string into tokens and parse them.\n\n Return stretchy token and list of [initialiser, length, value]\n initialiser is one of: hex, oct, bin, uint, int, se, ue, 0x, 0o, 0b etc.\n length is None if not known, as is value.\n\n If the token is in the keyword dictionary (keys) then it cou...
Please provide a description of the function:def expand_brackets(s): s = ''.join(s.split()) while True: start = s.find('(') if start == -1: break count = 1 # Number of hanging open brackets p = start + 1 while p < len(s): if s[p] == '(': ...
[ "Remove whitespace and expand all brackets." ]
Please provide a description of the function:def pack(fmt, *values, **kwargs): tokens = [] if isinstance(fmt, basestring): fmt = [fmt] try: for f_item in fmt: _, tkns = tokenparser(f_item, tuple(sorted(kwargs.keys()))) tokens.extend(tkns) except ValueError as...
[ "Pack the values according to the format string and return a new BitStream.\n\n fmt -- A single string or a list of strings with comma separated tokens\n describing how to create the BitStream.\n values -- Zero or more values to pack according to the format.\n kwargs -- A dictionary or keyword-va...
Please provide a description of the function:def getbyteslice(self, start, end): c = self._rawarray[start:end] return c
[ "Direct access to byte data." ]
Please provide a description of the function:def _appendstore(self, store): if not store.bitlength: return # Set new array offset to the number of bits in the final byte of current array. store = offsetcopy(store, (self.offset + self.bitlength) % 8) if store.offset: ...
[ "Join another store on to the end of this one." ]
Please provide a description of the function:def _prependstore(self, store): if not store.bitlength: return # Set the offset of copy of store so that it's final byte # ends in a position that matches the offset of self, # then join self on to the end of it. ...
[ "Join another store on to the start of this one." ]
Please provide a description of the function:def _assertsanity(self): assert self.len >= 0 assert 0 <= self._offset, "offset={0}".format(self._offset) assert (self.len + self._offset + 7) // 8 == self._datastore.bytelength + self._datastore.byteoffset return True
[ "Check internal self consistency as a debugging aid." ]
Please provide a description of the function:def _setauto(self, s, length, offset): # As s can be so many different things it's important to do the checks # in the correct order, as some types are also other allowed types. # So basestring must be checked before Iterable # and by...
[ "Set bitstring from a bitstring, file, bool, integer, array, iterable or string." ]
Please provide a description of the function:def _setfile(self, filename, length, offset): source = open(filename, 'rb') if offset is None: offset = 0 if length is None: length = os.path.getsize(source.name) * 8 - offset byteoffset, offset = divmod(offset...
[ "Use file as source of bits." ]
Please provide a description of the function:def _setbytes_safe(self, data, length=None, offset=0): data = bytearray(data) if length is None: # Use to the end of the data length = len(data)*8 - offset self._datastore = ByteStore(data, length, offset) ...
[ "Set the data from a string." ]
Please provide a description of the function:def _setbytes_unsafe(self, data, length, offset): self._datastore = ByteStore(data[:], length, offset) assert self._assertsanity()
[ "Unchecked version of _setbytes_safe." ]
Please provide a description of the function:def _readbytes(self, length, start): assert length % 8 == 0 assert start + length <= self.len if not (start + self._offset) % 8: return bytes(self._datastore.getbyteslice((start + self._offset) // 8, ...
[ "Read bytes and return them. Note that length is in bits." ]
Please provide a description of the function:def _setuint(self, uint, length=None): try: if length is None: # Use the whole length. Deliberately not using .len here. length = self._datastore.bitlength except AttributeError: # bitstring doe...
[ "Reset the bitstring to have given unsigned int interpretation." ]