sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def syncBuffer( self ): """ I detect and correct corruption in the buffer. Corruption in the buffer is defined as the following conditions both being true: 1. The buffer contains at least one newline; 2. The text until the first newline is not a ...
I detect and correct corruption in the buffer. Corruption in the buffer is defined as the following conditions both being true: 1. The buffer contains at least one newline; 2. The text until the first newline is not a STOMP command. In this case...
entailment
def connected(self, msg): """Once I've connected I want to subscribe to my the message queue. """ super(MyStomp, self).connected(msg) self.log.info("connected: session %s" % msg['headers']['session']) f = stomper.Frame() f.unpack(stomper.subscribe(DESTINATION)) r...
Once I've connected I want to subscribe to my the message queue.
entailment
def delete_entity_signal_handler(sender, instance, **kwargs): """ Defines a signal handler for syncing an individual entity. Called when an entity is saved or deleted. """ if instance.__class__ in entity_registry.entity_registry: Entity.all_objects.delete_for_obj(instance)
Defines a signal handler for syncing an individual entity. Called when an entity is saved or deleted.
entailment
def save_entity_signal_handler(sender, instance, **kwargs): """ Defines a signal handler for saving an entity. Syncs the entity to the entity mirror table. """ if instance.__class__ in entity_registry.entity_registry: sync_entities(instance) if instance.__class__ in entity_registry.enti...
Defines a signal handler for saving an entity. Syncs the entity to the entity mirror table.
entailment
def m2m_changed_entity_signal_handler(sender, instance, action, **kwargs): """ Defines a signal handler for a manytomany changed signal. Only listens for the post actions so that entities are synced once (rather than twice for a pre and post action). """ if action == 'post_add' or action == 'post_re...
Defines a signal handler for a manytomany changed signal. Only listens for the post actions so that entities are synced once (rather than twice for a pre and post action).
entailment
def turn_off_syncing(for_post_save=True, for_post_delete=True, for_m2m_changed=True, for_post_bulk_operation=True): """ Disables all of the signals for syncing entities. By default, everything is turned off. If the user wants to turn off everything but one signal, for example the post_save signal, they woul...
Disables all of the signals for syncing entities. By default, everything is turned off. If the user wants to turn off everything but one signal, for example the post_save signal, they would do: turn_off_sync(for_post_save=False)
entailment
def turn_on_syncing(for_post_save=True, for_post_delete=True, for_m2m_changed=True, for_post_bulk_operation=False): """ Enables all of the signals for syncing entities. Everything is True by default, except for the post_bulk_operation signal. The reason for this is because when any bulk operation occurs on ...
Enables all of the signals for syncing entities. Everything is True by default, except for the post_bulk_operation signal. The reason for this is because when any bulk operation occurs on any mirrored entity model, it will result in every single entity being synced again. This is not a desired behavior by the m...
entailment
def add(self, value): """Add element *value* to the set.""" # Raise TypeError if value is not hashable hash(value) self.redis.sadd(self.key, self._pickle(value))
Add element *value* to the set.
entailment
def discard(self, value): """Remove element *value* from the set if it is present.""" # Raise TypeError if value is not hashable hash(value) self.redis.srem(self.key, self._pickle(value))
Remove element *value* from the set if it is present.
entailment
def isdisjoint(self, other): """ Return ``True`` if the set has no elements in common with *other*. Sets are disjoint if and only if their intersection is the empty set. :param other: Any kind of iterable. :rtype: boolean """ def isdisjoint_trans_pure(pipe): ...
Return ``True`` if the set has no elements in common with *other*. Sets are disjoint if and only if their intersection is the empty set. :param other: Any kind of iterable. :rtype: boolean
entailment
def pop(self): """ Remove and return an arbitrary element from the set. Raises :exc:`KeyError` if the set is empty. """ result = self.redis.spop(self.key) if result is None: raise KeyError return self._unpickle(result)
Remove and return an arbitrary element from the set. Raises :exc:`KeyError` if the set is empty.
entailment
def random_sample(self, k=1): """ Return a *k* length list of unique elements chosen from the Set. Elements are not removed. Similar to :func:`random.sample` function from standard library. :param k: Size of the sample, defaults to 1. :rtype: :class:`list` """ ...
Return a *k* length list of unique elements chosen from the Set. Elements are not removed. Similar to :func:`random.sample` function from standard library. :param k: Size of the sample, defaults to 1. :rtype: :class:`list`
entailment
def remove(self, value): """ Remove element *value* from the set. Raises :exc:`KeyError` if it is not contained in the set. """ # Raise TypeError if value is not hashable hash(value) result = self.redis.srem(self.key, self._pickle(value)) if not result: ...
Remove element *value* from the set. Raises :exc:`KeyError` if it is not contained in the set.
entailment
def scan_elements(self): """ Yield each of the elements from the collection, without pulling them all into memory. .. warning:: This method is not available on the set collections provided by Python. This method may return the element multiple times....
Yield each of the elements from the collection, without pulling them all into memory. .. warning:: This method is not available on the set collections provided by Python. This method may return the element multiple times. See the `Redis SCAN documentatio...
entailment
def intersection_update(self, *others): """ Update the set, keeping only elements found in it and all *others*. :param others: Iterables, each one as a single positional argument. :rtype: None .. note:: The same behavior as at :func:`difference_update` applies. ...
Update the set, keeping only elements found in it and all *others*. :param others: Iterables, each one as a single positional argument. :rtype: None .. note:: The same behavior as at :func:`difference_update` applies.
entailment
def update(self, *others): """ Update the set, adding elements from all *others*. :param others: Iterables, each one as a single positional argument. :rtype: None .. note:: If all *others* are :class:`Set` instances, the operation is performed completely...
Update the set, adding elements from all *others*. :param others: Iterables, each one as a single positional argument. :rtype: None .. note:: If all *others* are :class:`Set` instances, the operation is performed completely in Redis. Otherwise, values are retrieved ...
entailment
def difference_update(self, *others): """ Update the set, removing elements found in *others*. :param others: Iterables, each one as a single positional argument. :rtype: None .. note:: The same behavior as at :func:`update` applies. """ return self....
Update the set, removing elements found in *others*. :param others: Iterables, each one as a single positional argument. :rtype: None .. note:: The same behavior as at :func:`update` applies.
entailment
def discard_member(self, member, pipe=None): """ Remove *member* from the collection, unconditionally. """ pipe = self.redis if pipe is None else pipe pipe.zrem(self.key, self._pickle(member))
Remove *member* from the collection, unconditionally.
entailment
def scan_items(self): """ Yield each of the ``(member, score)`` tuples from the collection, without pulling them all into memory. .. warning:: This method may return the same (member, score) tuple multiple times. See the `Redis SCAN documentation ...
Yield each of the ``(member, score)`` tuples from the collection, without pulling them all into memory. .. warning:: This method may return the same (member, score) tuple multiple times. See the `Redis SCAN documentation <http://redis.io/commands/scan#sca...
entailment
def update(self, other): """ Update the collection with items from *other*. Accepts other :class:`SortedSetBase` instances, dictionaries mapping members to numeric scores, or sequences of ``(member, score)`` tuples. """ def update_trans(pipe): other_items = me...
Update the collection with items from *other*. Accepts other :class:`SortedSetBase` instances, dictionaries mapping members to numeric scores, or sequences of ``(member, score)`` tuples.
entailment
def count_between(self, min_score=None, max_score=None): """ Returns the number of members whose score is between *min_score* and *max_score* (inclusive). """ min_score = float('-inf') if min_score is None else float(min_score) max_score = float('inf') if max_score is Non...
Returns the number of members whose score is between *min_score* and *max_score* (inclusive).
entailment
def discard_between( self, min_rank=None, max_rank=None, min_score=None, max_score=None, ): """ Remove members whose ranking is between *min_rank* and *max_rank* OR whose score is between *min_score* and *max_score* (both ranges inclusive). If ...
Remove members whose ranking is between *min_rank* and *max_rank* OR whose score is between *min_score* and *max_score* (both ranges inclusive). If no bounds are specified, no members will be removed.
entailment
def get_score(self, member, default=None, pipe=None): """ Return the score of *member*, or *default* if it is not in the collection. """ pipe = self.redis if pipe is None else pipe score = pipe.zscore(self.key, self._pickle(member)) if (score is None) and (defaul...
Return the score of *member*, or *default* if it is not in the collection.
entailment
def get_or_set_score(self, member, default=0): """ If *member* is in the collection, return its value. If not, store it with a score of *default* and return *default*. *default* defaults to 0. """ default = float(default) def get_or_set_score_trans(pipe): ...
If *member* is in the collection, return its value. If not, store it with a score of *default* and return *default*. *default* defaults to 0.
entailment
def get_rank(self, member, reverse=False, pipe=None): """ Return the rank of *member* in the collection. By default, the member with the lowest score has rank 0. If *reverse* is ``True``, the member with the highest score has rank 0. """ pipe = self.redis if pipe is None ...
Return the rank of *member* in the collection. By default, the member with the lowest score has rank 0. If *reverse* is ``True``, the member with the highest score has rank 0.
entailment
def increment_score(self, member, amount=1): """ Adjust the score of *member* by *amount*. If *member* is not in the collection it will be stored with a score of *amount*. """ return self.redis.zincrby( self.key, float(amount), self._pickle(member) )
Adjust the score of *member* by *amount*. If *member* is not in the collection it will be stored with a score of *amount*.
entailment
def items( self, min_rank=None, max_rank=None, min_score=None, max_score=None, reverse=False, pipe=None, ): """ Return a list of ``(member, score)`` tuples whose ranking is between *min_rank* and *max_rank* AND whose score is between *m...
Return a list of ``(member, score)`` tuples whose ranking is between *min_rank* and *max_rank* AND whose score is between *min_score* and *max_score* (both ranges inclusive). If no bounds are specified, all items will be returned.
entailment
def set_score(self, member, score, pipe=None): """ Set the score of *member* to *score*. """ pipe = self.redis if pipe is None else pipe pipe.zadd(self.key, {self._pickle(member): float(score)})
Set the score of *member* to *score*.
entailment
def distance_between(self, place_1, place_2, unit='km'): """ Return the great-circle distance between *place_1* and *place_2*, in the *unit* specified. The default unit is ``'km'``, but ``'m'``, ``'mi'``, and ``'ft'`` can also be specified. """ pickled_place_1 = ...
Return the great-circle distance between *place_1* and *place_2*, in the *unit* specified. The default unit is ``'km'``, but ``'m'``, ``'mi'``, and ``'ft'`` can also be specified.
entailment
def get_hash(self, place): """ Return the Geohash of *place*. If it's not present in the collection, ``None`` will be returned instead. """ pickled_place = self._pickle(place) try: return self.redis.geohash(self.key, pickled_place)[0] except (A...
Return the Geohash of *place*. If it's not present in the collection, ``None`` will be returned instead.
entailment
def get_location(self, place): """ Return a dict with the coordinates *place*. The dict's keys are ``'latitude'`` and ``'longitude'``. If it's not present in the collection, ``None`` will be returned instead. """ pickled_place = self._pickle(place) try: ...
Return a dict with the coordinates *place*. The dict's keys are ``'latitude'`` and ``'longitude'``. If it's not present in the collection, ``None`` will be returned instead.
entailment
def places_within_radius( self, place=None, latitude=None, longitude=None, radius=0, **kwargs ): """ Return descriptions of the places stored in the collection that are within the circle specified by the given location and radius. A list of dicts will be returned. Th...
Return descriptions of the places stored in the collection that are within the circle specified by the given location and radius. A list of dicts will be returned. The center of the circle can be specified by the identifier of another place in the collection with the *place* keyword arg...
entailment
def set_location(self, place, latitude, longitude, pipe=None): """ Set the location of *place* to the location specified by *latitude* and *longitude*. *place* can be any pickle-able Python object. """ pipe = self.redis if pipe is None else pipe pipe.geoadd(self....
Set the location of *place* to the location specified by *latitude* and *longitude*. *place* can be any pickle-able Python object.
entailment
def update(self, other): """ Update the collection with items from *other*. Accepts other :class:`GeoDB` instances, dictionaries mapping places to ``{'latitude': latitude, 'longitude': longitude}`` dicts, or sequences of ``(place, latitude, longitude)`` tuples. """ ...
Update the collection with items from *other*. Accepts other :class:`GeoDB` instances, dictionaries mapping places to ``{'latitude': latitude, 'longitude': longitude}`` dicts, or sequences of ``(place, latitude, longitude)`` tuples.
entailment
def copy(self, key=None): """ Creates another collection with the same items and maxsize with the given *key*. """ other = self.__class__( maxsize=self.maxsize, redis=self.persistence.redis, key=key ) other.update(self) return other
Creates another collection with the same items and maxsize with the given *key*.
entailment
def fromkeys(cls, seq, value=None, **kwargs): """ Create a new collection with keys from *seq* and values set to *value*. The keyword arguments are passed to the persistent ``Dict``. """ other = cls(**kwargs) other.update(((key, value) for key in seq)) return oth...
Create a new collection with keys from *seq* and values set to *value*. The keyword arguments are passed to the persistent ``Dict``.
entailment
def sync(self, clear_cache=False): """ Copy items from the local cache to the persistent Dict. If *clear_cache* is ``True``, clear out the local cache after pushing its items to Redis. """ self.persistence.update(self) if clear_cache: self.cache.clear...
Copy items from the local cache to the persistent Dict. If *clear_cache* is ``True``, clear out the local cache after pushing its items to Redis.
entailment
def _data(self, pipe=None): """ Return a :obj:`list` of all values from Redis (without checking the local cache). """ pipe = self.redis if pipe is None else pipe return [self._unpickle(v) for v in pipe.lrange(self.key, 0, -1)]
Return a :obj:`list` of all values from Redis (without checking the local cache).
entailment
def append(self, value): """Insert *value* at the end of this collection.""" len_self = self.redis.rpush(self.key, self._pickle(value)) if self.writeback: self.cache[len_self - 1] = value
Insert *value* at the end of this collection.
entailment
def copy(self, key=None): """ Return a new collection with the same items as this one. If *key* is specified, create the new collection with the given Redis key. """ other = self.__class__( redis=self.redis, key=key, writeback=self.writeback ) ...
Return a new collection with the same items as this one. If *key* is specified, create the new collection with the given Redis key.
entailment
def extend(self, other): """ Adds the values from the iterable *other* to the end of this collection. """ def extend_trans(pipe): values = list(other.__iter__(pipe)) if use_redis else other len_self = pipe.rpush(self.key, *(self._pickle(v) for v in values)...
Adds the values from the iterable *other* to the end of this collection.
entailment
def index(self, value, start=None, stop=None): """ Return the index of the first occurence of *value*. If *start* or *stop* are provided, return the smallest index such that ``s[index] == value`` and ``start <= index < stop``. """ def index_trans(pipe): len_se...
Return the index of the first occurence of *value*. If *start* or *stop* are provided, return the smallest index such that ``s[index] == value`` and ``start <= index < stop``.
entailment
def insert(self, index, value): """ Insert *value* into the collection at *index*. """ if index == 0: return self._insert_left(value) def insert_middle_trans(pipe): self._insert_middle(index, value, pipe=pipe) return self._transaction(insert_midd...
Insert *value* into the collection at *index*.
entailment
def pop(self, index=-1): """ Retrieve the value at *index*, remove it from the collection, and return it. """ if index == 0: return self._pop_left() elif index == -1: return self._pop_right() else: return self._pop_middle(index)
Retrieve the value at *index*, remove it from the collection, and return it.
entailment
def remove(self, value): """Remove the first occurence of *value*.""" def remove_trans(pipe): # If we're caching, we'll need to synchronize before removing. if self.writeback: self._sync_helper(pipe) delete_count = pipe.lrem(self.key, 1, self._pickle(...
Remove the first occurence of *value*.
entailment
def reverse(self): """ Reverses the items of this collection "in place" (only two values are retrieved from Redis at a time). """ def reverse_trans(pipe): if self.writeback: self._sync_helper(pipe) n = self.__len__(pipe) for i ...
Reverses the items of this collection "in place" (only two values are retrieved from Redis at a time).
entailment
def sort(self, key=None, reverse=False): """ Sort the items of this collection according to the optional callable *key*. If *reverse* is set then the sort order is reversed. .. note:: This sort requires all items to be retrieved from Redis and stored in memory. ...
Sort the items of this collection according to the optional callable *key*. If *reverse* is set then the sort order is reversed. .. note:: This sort requires all items to be retrieved from Redis and stored in memory.
entailment
def append(self, value): """Add *value* to the right side of the collection.""" def append_trans(pipe): self._append_helper(value, pipe) self._transaction(append_trans)
Add *value* to the right side of the collection.
entailment
def appendleft(self, value): """Add *value* to the left side of the collection.""" def appendleft_trans(pipe): self._appendleft_helper(value, pipe) self._transaction(appendleft_trans)
Add *value* to the left side of the collection.
entailment
def copy(self, key=None): """ Return a new collection with the same items as this one. If *key* is specified, create the new collection with the given Redis key. """ other = self.__class__( self.__iter__(), self.maxlen, redis=self.redis...
Return a new collection with the same items as this one. If *key* is specified, create the new collection with the given Redis key.
entailment
def extend(self, other): """ Extend the right side of the the collection by appending values from the iterable *other*. """ def extend_trans(pipe): values = list(other.__iter__(pipe)) if use_redis else other for v in values: self._append_he...
Extend the right side of the the collection by appending values from the iterable *other*.
entailment
def extendleft(self, other): """ Extend the left side of the the collection by appending values from the iterable *other*. Note that the appends will reverse the order of the given values. """ def extendleft_trans(pipe): values = list(other.__iter__(pipe)) if ...
Extend the left side of the the collection by appending values from the iterable *other*. Note that the appends will reverse the order of the given values.
entailment
def insert(self, index, value): """ Insert *value* into the collection at *index*. If the insertion would the collection to grow beyond ``maxlen``, raise ``IndexError``. """ def insert_trans(pipe): len_self = self.__len__(pipe) if (self.maxlen is n...
Insert *value* into the collection at *index*. If the insertion would the collection to grow beyond ``maxlen``, raise ``IndexError``.
entailment
def rotate(self, n=1): """ Rotate the deque n steps to the right. If n is negative, rotate to the left. """ # No work to do for a 0-step rotate if n == 0: return def rotate_trans(pipe): # Synchronize the cache before rotating i...
Rotate the deque n steps to the right. If n is negative, rotate to the left.
entailment
def get_entities_by_kind(membership_cache=None, is_active=True): """ Builds a dict with keys of entity kinds if and values are another dict. Each of these dicts are keyed off of a super entity id and optional have an 'all' key for any group that has a null super entity. Example structure: { ...
Builds a dict with keys of entity kinds if and values are another dict. Each of these dicts are keyed off of a super entity id and optional have an 'all' key for any group that has a null super entity. Example structure: { entity_kind_id: { entity1_id: [1, 2, 3], entity2_id: ...
entailment
def is_sub_to_all(self, *super_entities): """ Given a list of super entities, return the entities that have those as a subset of their super entities. """ if super_entities: if len(super_entities) == 1: # Optimize for the case of just one super entity since th...
Given a list of super entities, return the entities that have those as a subset of their super entities.
entailment
def is_sub_to_any(self, *super_entities): """ Given a list of super entities, return the entities that have super entities that interset with those provided. """ if super_entities: return self.filter(id__in=EntityRelationship.objects.filter( super_entity__in=s...
Given a list of super entities, return the entities that have super entities that interset with those provided.
entailment
def is_sub_to_all_kinds(self, *super_entity_kinds): """ Each returned entity will have superentites whos combined entity_kinds included *super_entity_kinds """ if super_entity_kinds: if len(super_entity_kinds) == 1: # Optimize for the case of just one ...
Each returned entity will have superentites whos combined entity_kinds included *super_entity_kinds
entailment
def is_sub_to_any_kind(self, *super_entity_kinds): """ Find all entities that have super_entities of any of the specified kinds """ if super_entity_kinds: # get the pks of the desired subs from the relationships table if len(super_entity_kinds) == 1: ...
Find all entities that have super_entities of any of the specified kinds
entailment
def cache_relationships(self, cache_super=True, cache_sub=True): """ Caches the super and sub relationships by doing a prefetch_related. """ relationships_to_cache = compress( ['super_relationships__super_entity', 'sub_relationships__sub_entity'], [cache_super, cache_sub]) ...
Caches the super and sub relationships by doing a prefetch_related.
entailment
def get_for_obj(self, entity_model_obj): """ Given a saved entity model object, return the associated entity. """ return self.get(entity_type=ContentType.objects.get_for_model( entity_model_obj, for_concrete_model=False), entity_id=entity_model_obj.id)
Given a saved entity model object, return the associated entity.
entailment
def delete_for_obj(self, entity_model_obj): """ Delete the entities associated with a model object. """ return self.filter( entity_type=ContentType.objects.get_for_model( entity_model_obj, for_concrete_model=False), entity_id=entity_model_obj.id).delete( ...
Delete the entities associated with a model object.
entailment
def cache_relationships(self, cache_super=True, cache_sub=True): """ Caches the super and sub relationships by doing a prefetch_related. """ return self.get_queryset().cache_relationships(cache_super=cache_super, cache_sub=cache_sub)
Caches the super and sub relationships by doing a prefetch_related.
entailment
def get_membership_cache(self, group_ids=None, is_active=True): """ Build a dict cache with the group membership info. Keyed off the group id and the values are a 2 element list of entity id and entity kind id (same values as the membership model). If no group ids are passed, then all gr...
Build a dict cache with the group membership info. Keyed off the group id and the values are a 2 element list of entity id and entity kind id (same values as the membership model). If no group ids are passed, then all groups will be fetched :param is_active: Flag indicating whether to filter on...
entailment
def all_entities(self, is_active=True): """ Return all the entities in the group. Because groups can contain both individual entities, as well as whole groups of entities, this method acts as a convenient way to get a queryset of all the entities in the group. """ ...
Return all the entities in the group. Because groups can contain both individual entities, as well as whole groups of entities, this method acts as a convenient way to get a queryset of all the entities in the group.
entailment
def get_all_entities(self, membership_cache=None, entities_by_kind=None, return_models=False, is_active=True): """ Returns a list of all entity ids in this group or optionally returns a queryset for all entity models. In order to reduce queries for multiple group lookups, it is expected that the...
Returns a list of all entity ids in this group or optionally returns a queryset for all entity models. In order to reduce queries for multiple group lookups, it is expected that the membership_cache and entities_by_kind are built outside of this method and passed in as arguments. :param membersh...
entailment
def add_entity(self, entity, sub_entity_kind=None): """ Add an entity, or sub-entity group to this EntityGroup. :type entity: Entity :param entity: The entity to add. :type sub_entity_kind: Optional EntityKind :param sub_entity_kind: If a sub_entity_kind is given, all ...
Add an entity, or sub-entity group to this EntityGroup. :type entity: Entity :param entity: The entity to add. :type sub_entity_kind: Optional EntityKind :param sub_entity_kind: If a sub_entity_kind is given, all sub_entities of the entity will be added to this ...
entailment
def bulk_add_entities(self, entities_and_kinds): """ Add many entities and sub-entity groups to this EntityGroup. :type entities_and_kinds: List of (Entity, EntityKind) pairs. :param entities_and_kinds: A list of entity, entity-kind pairs to add to the group. In the pairs th...
Add many entities and sub-entity groups to this EntityGroup. :type entities_and_kinds: List of (Entity, EntityKind) pairs. :param entities_and_kinds: A list of entity, entity-kind pairs to add to the group. In the pairs the entity-kind can be ``None``, to add a single entity, or...
entailment
def remove_entity(self, entity, sub_entity_kind=None): """ Remove an entity, or sub-entity group to this EntityGroup. :type entity: Entity :param entity: The entity to remove. :type sub_entity_kind: Optional EntityKind :param sub_entity_kind: If a sub_entity_kind is giv...
Remove an entity, or sub-entity group to this EntityGroup. :type entity: Entity :param entity: The entity to remove. :type sub_entity_kind: Optional EntityKind :param sub_entity_kind: If a sub_entity_kind is given, all sub_entities of the entity will be removed from this ...
entailment
def bulk_remove_entities(self, entities_and_kinds): """ Remove many entities and sub-entity groups to this EntityGroup. :type entities_and_kinds: List of (Entity, EntityKind) pairs. :param entities_and_kinds: A list of entity, entity-kind pairs to remove from the group. In t...
Remove many entities and sub-entity groups to this EntityGroup. :type entities_and_kinds: List of (Entity, EntityKind) pairs. :param entities_and_kinds: A list of entity, entity-kind pairs to remove from the group. In the pairs, the entity-kind can be ``None``, to add a single e...
entailment
def bulk_overwrite(self, entities_and_kinds): """ Update the group to the given entities and sub-entity groups. After this operation, the only members of this EntityGroup will be the given entities, and sub-entity groups. :type entities_and_kinds: List of (Entity, EntityKind) p...
Update the group to the given entities and sub-entity groups. After this operation, the only members of this EntityGroup will be the given entities, and sub-entity groups. :type entities_and_kinds: List of (Entity, EntityKind) pairs. :param entities_and_kinds: A list of entity, entity-...
entailment
def generate_slug(value): "A copy of spectator.core.models.SluggedModelMixin._generate_slug()" alphabet = 'abcdefghijkmnopqrstuvwxyz23456789' salt = 'Django Spectator' if hasattr(settings, 'SPECTATOR_SLUG_ALPHABET'): alphabet = settings.SPECTATOR_SLUG_ALPHABET if hasattr(settings, 'SPECTAT...
A copy of spectator.core.models.SluggedModelMixin._generate_slug()
entailment
def set_slug(apps, schema_editor, class_name): """ Create a slug for each Work already in the DB. """ Cls = apps.get_model('spectator_events', class_name) for obj in Cls.objects.all(): obj.slug = generate_slug(obj.pk) obj.save(update_fields=['slug'])
Create a slug for each Work already in the DB.
entailment
def kind_name(self): "e.g. 'Gig' or 'Movie'." return {k:v for (k,v) in self.KIND_CHOICES}[self.kind]
e.g. 'Gig' or 'Movie'.
entailment
def get_kind_name_plural(kind): "e.g. 'Gigs' or 'Movies'." if kind in ['comedy', 'cinema', 'dance', 'theatre']: return kind.title() elif kind == 'museum': return 'Galleries/Museums' else: return '{}s'.format(Event.get_kind_name(kind))
e.g. 'Gigs' or 'Movies'.
entailment
def get_kinds_data(): """ Returns a dict of all the data about the kinds, keyed to the kind value. e.g: { 'gig': { 'name': 'Gig', 'slug': 'gigs', 'name_plural': 'Gigs', }, # et...
Returns a dict of all the data about the kinds, keyed to the kind value. e.g: { 'gig': { 'name': 'Gig', 'slug': 'gigs', 'name_plural': 'Gigs', }, # etc }
entailment
def get_list_url(self, kind_slug=None): """ Get the list URL for this Work. You can also pass a kind_slug in (e.g. 'movies') and it will use that instead of the Work's kind_slug. (Why? Useful in views. Or tests of views, at least.) """ if kind_slug is None: ...
Get the list URL for this Work. You can also pass a kind_slug in (e.g. 'movies') and it will use that instead of the Work's kind_slug. (Why? Useful in views. Or tests of views, at least.)
entailment
def convert_descriptor_and_rows(self, descriptor, rows): """Convert descriptor and rows to Pandas """ # Prepare primary_key = None schema = tableschema.Schema(descriptor) if len(schema.primary_key) == 1: primary_key = schema.primary_key[0] elif len(sc...
Convert descriptor and rows to Pandas
entailment
def convert_type(self, type): """Convert type to Pandas """ # Mapping mapping = { 'any': np.dtype('O'), 'array': np.dtype(list), 'boolean': np.dtype(bool), 'date': np.dtype('O'), 'datetime': np.dtype('datetime64[ns]'), ...
Convert type to Pandas
entailment
def restore_descriptor(self, dataframe): """Restore descriptor from Pandas """ # Prepare fields = [] primary_key = None # Primary key if dataframe.index.name: field_type = self.restore_type(dataframe.index.dtype) field = { ...
Restore descriptor from Pandas
entailment
def restore_row(self, row, schema, pk): """Restore row from Pandas """ result = [] for field in schema.fields: if schema.primary_key and schema.primary_key[0] == field.name: if field.type == 'number' and np.isnan(pk): pk = None ...
Restore row from Pandas
entailment
def restore_type(self, dtype, sample=None): """Restore type from Pandas """ # Pandas types if pdc.is_bool_dtype(dtype): return 'boolean' elif pdc.is_datetime64_any_dtype(dtype): return 'datetime' elif pdc.is_integer_dtype(dtype): retur...
Restore type from Pandas
entailment
def change_object_link_card(obj, perms): """ If the user has permission to change `obj`, show a link to its Admin page. obj -- An object like Movie, Play, ClassicalWork, Publication, etc. perms -- The `perms` object that it's the template. """ # eg: 'movie' or 'classicalwork': name = obj.__c...
If the user has permission to change `obj`, show a link to its Admin page. obj -- An object like Movie, Play, ClassicalWork, Publication, etc. perms -- The `perms` object that it's the template.
entailment
def domain_urlize(value): """ Returns an HTML link to the supplied URL, but only using the domain as the text. Strips 'www.' from the start of the domain, if present. e.g. if `my_url` is 'http://www.example.org/foo/' then: {{ my_url|domain_urlize }} returns: <a href="http://www.ex...
Returns an HTML link to the supplied URL, but only using the domain as the text. Strips 'www.' from the start of the domain, if present. e.g. if `my_url` is 'http://www.example.org/foo/' then: {{ my_url|domain_urlize }} returns: <a href="http://www.example.org/foo/" rel="nofollow">example...
entailment
def current_url_name(context): """ Returns the name of the current URL, namespaced, or False. Example usage: {% current_url_name as url_name %} <a href="#"{% if url_name == 'myapp:home' %} class="active"{% endif %}">Home</a> """ url_name = False if context.request.resolver_ma...
Returns the name of the current URL, namespaced, or False. Example usage: {% current_url_name as url_name %} <a href="#"{% if url_name == 'myapp:home' %} class="active"{% endif %}">Home</a>
entailment
def query_string(context, key, value): """ For adding/replacing a key=value pair to the GET string for a URL. eg, if we're viewing ?p=3 and we do {% query_string order 'taken' %} then this returns "p=3&order=taken" And, if we're viewing ?p=3&order=uploaded and we do the same thing, we get the ...
For adding/replacing a key=value pair to the GET string for a URL. eg, if we're viewing ?p=3 and we do {% query_string order 'taken' %} then this returns "p=3&order=taken" And, if we're viewing ?p=3&order=uploaded and we do the same thing, we get the same result (ie, the existing "order=uploaded" is r...
entailment
def most_read_creators_card(num=10): """ Displays a card showing the Creators who have the most Readings associated with their Publications. In spectator_core tags, rather than spectator_reading so it can still be used on core pages, even if spectator_reading isn't installed. """ if spectat...
Displays a card showing the Creators who have the most Readings associated with their Publications. In spectator_core tags, rather than spectator_reading so it can still be used on core pages, even if spectator_reading isn't installed.
entailment
def most_visited_venues_card(num=10): """ Displays a card showing the Venues that have the most Events. In spectator_core tags, rather than spectator_events so it can still be used on core pages, even if spectator_events isn't installed. """ if spectator_apps.is_enabled('events'): obje...
Displays a card showing the Venues that have the most Events. In spectator_core tags, rather than spectator_events so it can still be used on core pages, even if spectator_events isn't installed.
entailment
def has_urls(self): "Handy for templates." if self.isbn_uk or self.isbn_us or self.official_url or self.notes_url: return True else: return False
Handy for templates.
entailment
def get_entity(package, entity): """ eg, get_entity('spectator', 'version') returns `__version__` value in `__init__.py`. """ init_py = open(os.path.join(package, '__init__.py')).read() find = "__%s__ = ['\"]([^'\"]+)['\"]" % entity return re.search(find, init_py).group(1)
eg, get_entity('spectator', 'version') returns `__version__` value in `__init__.py`.
entailment
def get_queryset(self): "Reduce the number of queries and speed things up." qs = super().get_queryset() qs = qs.select_related('publication__series') \ .prefetch_related('publication__roles__creator') return qs
Reduce the number of queries and speed things up.
entailment
def set_slug(apps, schema_editor): """ Create a slug for each Creator already in the DB. """ Creator = apps.get_model('spectator_core', 'Creator') for c in Creator.objects.all(): c.slug = generate_slug(c.pk) c.save(update_fields=['slug'])
Create a slug for each Creator already in the DB.
entailment
def forwards(apps, schema_editor): """ Copy the ClassicalWork and DancePiece data to use the new through models. """ Event = apps.get_model('spectator_events', 'Event') ClassicalWorkSelection = apps.get_model( 'spectator_events', 'ClassicalWorkSelection') DancePie...
Copy the ClassicalWork and DancePiece data to use the new through models.
entailment
def forwards(apps, schema_editor): """ Set the venue_name field of all Events that have a Venue. """ Event = apps.get_model('spectator_events', 'Event') for event in Event.objects.all(): if event.venue is not None: event.venue_name = event.venue.name event.save()
Set the venue_name field of all Events that have a Venue.
entailment
def forwards(apps, schema_editor): """ Migrate all 'exhibition' Events to the new 'museum' Event kind. """ Event = apps.get_model('spectator_events', 'Event') for ev in Event.objects.filter(kind='exhibition'): ev.kind = 'museum' ev.save()
Migrate all 'exhibition' Events to the new 'museum' Event kind.
entailment
def truncate_string(text, strip_html=True, chars=255, truncate='…', at_word_boundary=False): """Truncate a string to a certain length, removing line breaks and mutliple spaces, optionally removing HTML, and appending a 'truncate' string. Keyword arguments: strip_html -- boolean. chars -- Number of ...
Truncate a string to a certain length, removing line breaks and mutliple spaces, optionally removing HTML, and appending a 'truncate' string. Keyword arguments: strip_html -- boolean. chars -- Number of characters to return. at_word_boundary -- Only truncate at a word boundary, which will probably ...
entailment
def chartify(qs, score_field, cutoff=0, ensure_chartiness=True): """ Given a QuerySet it will go through and add a `chart_position` property to each object returning a list of the objects. If adjacent objects have the same 'score' (based on `score_field`) then they will have the same `chart_positio...
Given a QuerySet it will go through and add a `chart_position` property to each object returning a list of the objects. If adjacent objects have the same 'score' (based on `score_field`) then they will have the same `chart_position`. This can then be used in templates for the `value` of <li> elements i...
entailment
def by_visits(self, event_kind=None): """ Gets Venues in order of how many Events have been held there. Adds a `num_visits` field to each one. event_kind filters by kind of Event, e.g. 'theatre', 'cinema', etc. """ qs = self.get_queryset() if event_kind is not N...
Gets Venues in order of how many Events have been held there. Adds a `num_visits` field to each one. event_kind filters by kind of Event, e.g. 'theatre', 'cinema', etc.
entailment
def by_views(self, kind=None): """ Gets Works in order of how many times they've been attached to Events. kind is the kind of Work, e.g. 'play', 'movie', etc. """ qs = self.get_queryset() if kind is not None: qs = qs.filter(kind=kind) qs = q...
Gets Works in order of how many times they've been attached to Events. kind is the kind of Work, e.g. 'play', 'movie', etc.
entailment
def naturalize_thing(self, string): """ Make a naturalized version of a general string, not a person's name. e.g., title of a book, a band's name, etc. string -- a lowercase string. """ # Things we want to move to the back of the string: articles = [ ...
Make a naturalized version of a general string, not a person's name. e.g., title of a book, a band's name, etc. string -- a lowercase string.
entailment